LLVM 24.0.0git
SystemZISelLowering.cpp
Go to the documentation of this file.
1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
17#include "llvm/ADT/SmallSet.h"
23#include "llvm/IR/GlobalAlias.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/IntrinsicsS390.h"
27#include "llvm/IR/Module.h"
32#include <cctype>
33#include <optional>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "systemz-lower"
38
39namespace {
40// Represents information about a comparison.
41struct Comparison {
42 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
43 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
44 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
45
46 // The operands to the comparison.
47 SDValue Op0, Op1;
48
49 // Chain if this is a strict floating-point comparison.
50 SDValue Chain;
51
52 // The opcode that should be used to compare Op0 and Op1.
53 unsigned Opcode;
54
55 // A SystemZICMP value. Only used for integer comparisons.
56 unsigned ICmpType;
57
58 // The mask of CC values that Opcode can produce.
59 unsigned CCValid;
60
61 // The mask of CC values for which the original condition is true.
62 unsigned CCMask;
63};
64} // end anonymous namespace
65
66// Classify VT as either 32 or 64 bit.
67static bool is32Bit(EVT VT) {
68 switch (VT.getSimpleVT().SimpleTy) {
69 case MVT::i32:
70 return true;
71 case MVT::i64:
72 return false;
73 default:
74 llvm_unreachable("Unsupported type");
75 }
76}
77
78// Return a version of MachineOperand that can be safely used before the
79// final use.
81 if (Op.isReg())
82 Op.setIsKill(false);
83 return Op;
84}
85
87 const SystemZSubtarget &STI)
88 : TargetLowering(TM, STI), Subtarget(STI) {
89 MVT PtrVT = MVT::i64;
90
91 auto *Regs = STI.getSpecialRegisters();
92
93 // Set up the register classes.
94 if (Subtarget.hasHighWord())
95 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
96 else
97 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
98 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
99 if (!useSoftFloat()) {
100 if (Subtarget.hasVector()) {
101 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
102 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
103 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
104 } else {
105 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
106 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
107 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
108 }
109 if (Subtarget.hasVectorEnhancements1())
110 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
111 else
112 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
113
114 if (Subtarget.hasVector()) {
115 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
116 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
117 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
118 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
119 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
120 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
121 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
122 }
123
124 if (Subtarget.hasVector())
125 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
126 }
127
128 // Without vector support, model GR128 register pairs as v2i64.
129 if (!Subtarget.hasVector())
130 addRegisterClass(MVT::v2i64, &SystemZ::GR128BitRegClass);
131
132 // Compute derived properties from the register classes
133 computeRegisterProperties(Subtarget.getRegisterInfo());
134
135 // Set up special registers.
136 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
137
138 // TODO: It may be better to default to latency-oriented scheduling, however
139 // LLVM's current latency-oriented scheduler can't handle physreg definitions
140 // such as SystemZ has with CC, so set this to the register-pressure
141 // scheduler, because it can.
143
146
148
149 // Instructions are strings of 2-byte aligned 2-byte values.
151 // For performance reasons we prefer 16-byte alignment.
153
154 // Handle operations that are handled in a similar way for all types.
155 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
156 I <= MVT::LAST_FP_VALUETYPE;
157 ++I) {
159 if (isTypeLegal(VT)) {
160 // Lower SET_CC into an IPM-based sequence.
164
165 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
167
168 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
171 }
172 }
173
174 // Expand jump table branches as address arithmetic followed by an
175 // indirect jump.
177
178 // Expand BRCOND into a BR_CC (see above).
180
181 // Handle integer types except i128.
182 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
183 I <= MVT::LAST_INTEGER_VALUETYPE;
184 ++I) {
186 if (isTypeLegal(VT) && VT != MVT::i128) {
188
189 // Expand individual DIV and REMs into DIVREMs.
196
197 // Support addition/subtraction with overflow.
200
201 // Support multiplication with overflow (MSC, MSGC, MSRKC, MSGRKC).
202 if (Subtarget.hasMiscellaneousExtensions2())
204
205 // Support addition/subtraction with carry.
208
209 // Support carry in as value rather than glue.
212
213 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
214 // available, or if the operand is constant.
216
217 // Use POPCNT on z196 and above.
218 if (Subtarget.hasPopulationCount())
220 else
222
223 // No special instructions for these.
226
227 // Use *MUL_LOHI where possible instead of MULH*.
232
233 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
234 // unsigned on z10 (only z196 and above have native support for
235 // unsigned conversions).
242 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
243 auto OpAction =
244 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
245 setOperationAction(Op, VT, OpAction);
246 }
247 }
248 }
249
250 // Handle i128 if legal.
251 if (isTypeLegal(MVT::i128)) {
252 // No special instructions for these.
259
260 // We may be able to use VSLDB/VSLD/VSRD for these.
263
264 // No special instructions for these before z17.
265 if (!Subtarget.hasVectorEnhancements3()) {
275 } else {
276 // Even if we do have a legal 128-bit multiply, we do not
277 // want 64-bit multiply-high operations to use it.
280 }
281
282 // Support addition/subtraction with carry.
287
288 // Use VPOPCT and add up partial results.
290
291 // Additional instructions available with z17.
292 if (Subtarget.hasVectorEnhancements3()) {
293 setOperationAction(ISD::ABS, MVT::i128, Legal);
294
296 MVT::i128, Legal);
297
299 }
300 }
301
302 // These need custom handling in order to handle the f16 conversions.
311
312 // Lower 8- and 16-bit atomic operations into full i32 operations during
313 // type legalization.
319 {MVT::i8, MVT::i16}, Custom);
320
321 // Whether or not i128 is not a legal type, we need to custom lower
322 // the atomic operations in order to exploit SystemZ instructions.
327
328 // Mark sign/zero extending atomic loads as legal, which will make
329 // DAGCombiner fold extensions into atomic loads if possible.
331 {MVT::i8, MVT::i16, MVT::i32}, Legal);
333 {MVT::i8, MVT::i16}, Legal);
335 MVT::i8, Legal);
336
337 // We can use the CC result of compare-and-swap to implement
338 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
342
344
345 // Traps are legal, as we will convert them to "j .+2".
346 setOperationAction(ISD::TRAP, MVT::Other, Legal);
347
348 // We have native support for a 64-bit CTLZ, via FLOGR.
352
353 // On z17 we have native support for a 64-bit CTTZ, PDEP, and PEXT.
354 if (Subtarget.hasMiscellaneousExtensions4()) {
360 }
361
362 // On z15 we have native support for a 64-bit CTPOP.
363 if (Subtarget.hasMiscellaneousExtensions3()) {
366 }
367
368 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
370
371 // Expand 128 bit shifts without using a libcall.
375
376 // Also expand 256 bit shifts if i128 is a legal type.
377 if (isTypeLegal(MVT::i128)) {
381 }
382
383 // Handle bitcast from fp128 to i128.
384 if (!isTypeLegal(MVT::i128))
386
387 // We have native instructions for i8, i16 and i32 extensions, but not i1.
389 for (MVT VT : MVT::integer_valuetypes()) {
393 }
394
395 // Handle the various types of symbolic address.
401
402 // We need to handle dynamic allocations specially because of the
403 // 160-byte area at the bottom of the stack.
406
409
410 // Handle prefetches with PFD or PFDRL.
412
413 // Handle readcyclecounter with STCKF.
415
417 // Assume by default that all vector operations need to be expanded.
418 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
419 if (getOperationAction(Opcode, VT) == Legal)
420 setOperationAction(Opcode, VT, Expand);
421
422 // Likewise all truncating stores and extending loads.
423 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
424 setTruncStoreAction(VT, InnerVT, Expand);
427 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
428 }
429
430 if (Subtarget.hasVector() && isTypeLegal(VT)) {
431 // These operations are legal for anything that can be stored in a
432 // vector register, even if there is no native support for the format
433 // as such. In particular, we can do these for v4f32 even though there
434 // are no specific instructions for that format.
440
441 // Likewise, except that we need to replace the nodes with something
442 // more specific.
445 }
446 }
447
448 if (!Subtarget.hasVector()) {
449 // A v2i64 GR128 pair can only be built from or split into its halves.
450 // Loads and stores are expanded to avoid tying up a register pair.
453 MVT::v2i64, Legal);
455 MVT::v2i64, Custom);
456 }
457
458 // Handle integer vector types.
460 if (Subtarget.hasVector() && isTypeLegal(VT)) {
461 // These operations have direct equivalents.
466 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
470 }
471 if (Subtarget.hasVectorEnhancements3() &&
472 VT != MVT::v16i8 && VT != MVT::v8i16) {
477 }
482 if (Subtarget.hasVectorEnhancements1())
484 else
488
489 // Convert a GPR scalar to a vector by inserting it into element 0.
491
492 // Use a series of unpacks for extensions.
495
496 // Detect shifts/rotates by a scalar amount and convert them into
497 // V*_BY_SCALAR.
502
503 // Add ISD::VECREDUCE_ADD as custom in order to implement
504 // it with VZERO+VSUM
506
507 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
508 // and inverting the result as necessary.
510
512 Legal);
514 }
515 }
516
517 if (Subtarget.hasVector()) {
518 // There should be no need to check for float types other than v2f64
519 // since <2 x f32> isn't a legal type.
528
537 }
538
539 if (Subtarget.hasVectorEnhancements2()) {
548
557 }
558
559 // Handle floating-point types.
560 if (!useSoftFloat()) {
561 // Promote all f16 operations to float, with some exceptions below.
562 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
563 setOperationAction(Opc, MVT::f16, Promote);
565 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
566 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
567 setTruncStoreAction(VT, MVT::f16, Expand);
568 }
570 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
574
575 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
576 setOperationAction(Op, MVT::f16, Legal);
577 }
578
579 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
580 I <= MVT::LAST_FP_VALUETYPE;
581 ++I) {
583 if (isTypeLegal(VT) && VT != MVT::f16) {
584 // We can use FI for FRINT.
586
587 // We can use the extended form of FI for other rounding operations.
588 if (Subtarget.hasFPExtension()) {
595 }
596
597 // No special instructions for these.
603
604 // Special treatment.
606
607 // Handle constrained floating-point operations.
616 if (Subtarget.hasFPExtension()) {
623 }
624
625 // Extension from f16 needs libcall.
628 }
629 }
630
631 // Handle floating-point vector types.
632 if (Subtarget.hasVector()) {
633 // Scalar-to-vector conversion is just a subreg.
637
638 // Some insertions and extractions can be done directly but others
639 // need to go via integers.
646
647 // These operations have direct equivalents.
648 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
649 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
650 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
651 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
652 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
653 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
654 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
655 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
656 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
659 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
663
664 // Handle constrained floating-point operations.
678
683 if (Subtarget.hasVectorEnhancements1()) {
686 }
687 }
688
689 // The vector enhancements facility 1 has instructions for these.
690 if (Subtarget.hasVectorEnhancements1()) {
691 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
692 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
693 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
694 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
695 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
696 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
697 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
698 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
699 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
702 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
706
707 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
716 }
717
718 // Handle constrained floating-point operations.
732 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
733 MVT::v4f32, MVT::v2f64 }) {
740 }
741 }
742
743 // We only have fused f128 multiply-addition on vector registers.
744 if (!Subtarget.hasVectorEnhancements1()) {
747 }
748
749 // We don't have a copysign instruction on vector registers.
750 if (Subtarget.hasVectorEnhancements1())
752
753 // Needed so that we don't try to implement f128 constant loads using
754 // a load-and-extend of a f80 constant (in cases where the constant
755 // would fit in an f80).
756 for (MVT VT : MVT::fp_valuetypes())
757 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
758
759 // We don't have extending load instruction on vector registers.
760 if (Subtarget.hasVectorEnhancements1()) {
761 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
762 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
763 }
764
765 // Floating-point truncation and stores need to be done separately.
766 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
767 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
768 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
769
770 // We have 64-bit FPR<->GPR moves, but need special handling for
771 // 32-bit forms.
772 if (!Subtarget.hasVector()) {
775 }
776
777 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
778 // structure, but VAEND is a no-op.
782
783 if (Subtarget.isTargetzOS()) {
784 // Handle address space casts between mixed sized pointers.
787 }
788
790
791 // Codes for which we want to perform some z-specific combinations.
795 ISD::LOAD,
808 ISD::SRL,
809 ISD::SRA,
810 ISD::MUL,
811 ISD::SDIV,
812 ISD::UDIV,
813 ISD::SREM,
814 ISD::UREM,
817
818 // Handle intrinsics.
821
822 // We're not using SJLJ for exception handling, but they're implemented
823 // solely to support use of __builtin_setjmp / __builtin_longjmp.
826
827 // We want to use MVC in preference to even a single load/store pair.
828 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
830
831 // Same with memmove.
832 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
834
835 // The main memset sequence is a byte store followed by an MVC.
836 // Two STC or MV..I stores win over that, but the kind of fused stores
837 // generated by target-independent code don't when the byte value is
838 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
839 // than "STC;MVC". Handle the choice in target-specific code instead.
840 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
842
843 // Default to having -disable-strictnode-mutation on
844 IsStrictFPEnabled = true;
845}
846
848 return Subtarget.hasSoftFloat();
849}
850
853 // Widen subvectors to the full width rather than promoting integer
854 // elements. This is better because:
855 //
856 // (a) it means that we can handle the ABI for passing and returning
857 // sub-128 vectors without having to handle them as legal types.
858 //
859 // (b) we don't have instructions to extend on load and truncate on store,
860 // so promoting the integers is less efficient.
861 //
862 // (c) there are no multiplication instructions for the widest integer
863 // type (v2i64).
864
865 // Expand (narrow) f16 vectors during type legalization to avoid
866 // operations for all elements as with expansion after widening. Without
867 // vector support, v2i64 is only legal as a GR128 pair, so do not widen or
868 // promote to it.
869 if (!Subtarget.hasVector() || VT.getScalarType() == MVT::f16)
872 if (VT.getScalarSizeInBits() % 8 == 0)
873 return TypeWidenVector;
875}
876
878 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
879 unsigned &NumIntermediates, MVT &RegisterVT) const {
880 // Pass fp16 vectors in VR(s).
881 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
882 IntermediateVT = RegisterVT = MVT::v8f16;
883 return NumIntermediates =
885 }
887 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
888 // Without vector support, v2i64 is a GR128 pair, which is never used to pass
889 // values. Pass the elements individually.
890 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector()) {
891 IntermediateVT = RegisterVT = MVT::i64;
892 NumIntermediates *= 2;
893 NumRegs *= 2;
894 }
895 return NumRegs;
896}
897
900 EVT VT) const {
901 // 128-bit single-element vector types are passed like other vectors,
902 // not like their element type.
903 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
904 VT.getVectorNumElements() == 1)
905 return MVT::v16i8;
906 // Pass fp16 vectors in VR(s).
907 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
908 return MVT::v8f16;
909 MVT RegisterVT =
911 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
912 return MVT::i64;
913 return RegisterVT;
914}
915
918 // Pass fp16 vectors in VR(s).
919 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
921 unsigned NumRegs =
923 MVT RegisterVT =
925 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
926 return NumRegs * 2;
927 return NumRegs;
928}
929
931 LLVMContext &, EVT VT) const {
932 if (!VT.isVector())
933 return MVT::i32;
935}
936
938 const MachineFunction &MF, EVT VT) const {
939 if (useSoftFloat())
940 return false;
941
942 VT = VT.getScalarType();
943
944 if (!VT.isSimple())
945 return false;
946
947 switch (VT.getSimpleVT().SimpleTy) {
948 case MVT::f32:
949 case MVT::f64:
950 return true;
951 case MVT::f128:
952 return Subtarget.hasVectorEnhancements1();
953 default:
954 break;
955 }
956
957 return false;
958}
959
960// Return true if the constant can be generated with a vector instruction,
961// such as VGM, VGMB or VREPI.
964 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
965 if (!Subtarget.hasVector() ||
966 (isFP128 && !Subtarget.hasVectorEnhancements1()))
967 return false;
968
969 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
970 // preferred way of creating all-zero and all-one vectors so give it
971 // priority over other methods below.
972 unsigned Mask = 0;
973 unsigned I = 0;
974 for (; I < SystemZ::VectorBytes; ++I) {
975 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
976 if (Byte == 0xff)
977 Mask |= 1ULL << I;
978 else if (Byte != 0)
979 break;
980 }
981 if (I == SystemZ::VectorBytes) {
982 Opcode = SystemZISD::BYTE_MASK;
983 OpVals.push_back(Mask);
985 return true;
986 }
987
988 if (SplatBitSize > 64)
989 return false;
990
991 auto TryValue = [&](uint64_t Value) -> bool {
992 // Try VECTOR REPLICATE IMMEDIATE
993 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
994 if (isInt<16>(SignedValue)) {
995 OpVals.push_back(((unsigned) SignedValue));
996 Opcode = SystemZISD::REPLICATE;
998 SystemZ::VectorBits / SplatBitSize);
999 return true;
1000 }
1001 // Try VECTOR GENERATE MASK
1002 unsigned Start, End;
1003 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
1004 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
1005 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
1006 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
1007 OpVals.push_back(Start - (64 - SplatBitSize));
1008 OpVals.push_back(End - (64 - SplatBitSize));
1009 Opcode = SystemZISD::ROTATE_MASK;
1011 SystemZ::VectorBits / SplatBitSize);
1012 return true;
1013 }
1014 return false;
1015 };
1016
1017 // First try assuming that any undefined bits above the highest set bit
1018 // and below the lowest set bit are 1s. This increases the likelihood of
1019 // being able to use a sign-extended element value in VECTOR REPLICATE
1020 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
1021 uint64_t SplatBitsZ = SplatBits.getZExtValue();
1022 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
1023 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
1024 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
1025 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
1026 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
1027 if (TryValue(SplatBitsZ | Upper | Lower))
1028 return true;
1029
1030 // Now try assuming that any undefined bits between the first and
1031 // last defined set bits are set. This increases the chances of
1032 // using a non-wraparound mask.
1033 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
1034 return TryValue(SplatBitsZ | Middle);
1035}
1036
1038 if (IntImm.isSingleWord()) {
1039 IntBits = APInt(128, IntImm.getZExtValue());
1040 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
1041 } else
1042 IntBits = IntImm;
1043 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
1044
1045 // Find the smallest splat.
1046 SplatBits = IntImm;
1047 unsigned Width = SplatBits.getBitWidth();
1048 while (Width > 8) {
1049 unsigned HalfSize = Width / 2;
1050 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
1051 APInt LowValue = SplatBits.trunc(HalfSize);
1052
1053 // If the two halves do not match, stop here.
1054 if (HighValue != LowValue || 8 > HalfSize)
1055 break;
1056
1057 SplatBits = HighValue;
1058 Width = HalfSize;
1059 }
1060 SplatUndef = 0;
1061 SplatBitSize = Width;
1062}
1063
1065 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1066 bool HasAnyUndefs;
1067
1068 // Get IntBits by finding the 128 bit splat.
1069 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1070 true);
1071
1072 // Get SplatBits by finding the 8 bit or greater splat.
1073 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1074 true);
1075}
1076
1079 bool ForCodeSize) const {
1080 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1081 if (Imm.isZero() || Imm.isNegZero())
1082 return FPImmAction::Legal;
1083
1087}
1088
1091 MachineBasicBlock *MBB) const {
1092 DebugLoc DL = MI.getDebugLoc();
1093 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1094 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1095
1096 MachineFunction *MF = MBB->getParent();
1098
1099 const BasicBlock *BB = MBB->getBasicBlock();
1100 MachineFunction::iterator I = ++MBB->getIterator();
1101
1102 Register DstReg = MI.getOperand(0).getReg();
1103 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1104 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1105 (void)TRI;
1106 Register MainDstReg = MRI.createVirtualRegister(RC);
1107 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1108
1109 MVT PVT = getPointerTy(MF->getDataLayout());
1110 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1111 // For v = setjmp(buf), we generate.
1112 // Algorithm:
1113 //
1114 // ---------
1115 // | thisMBB |
1116 // ---------
1117 // |
1118 // ------------------------
1119 // | |
1120 // ---------- ---------------
1121 // | mainMBB | | restoreMBB |
1122 // | v = 0 | | v = 1 |
1123 // ---------- ---------------
1124 // | |
1125 // -------------------------
1126 // |
1127 // -----------------------------
1128 // | sinkMBB |
1129 // | phi(v_mainMBB,v_restoreMBB) |
1130 // -----------------------------
1131 // thisMBB:
1132 // buf[FPOffset] = Frame Pointer if hasFP.
1133 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1134 // buf[BCOffset] = Backchain value if building with -mbackchain.
1135 // buf[SPOffset] = Stack Pointer.
1136 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1137 // SjLjSetup restoreMBB
1138 // mainMBB:
1139 // v_main = 0
1140 // sinkMBB:
1141 // v = phi(v_main, v_restore)
1142 // restoreMBB:
1143 // v_restore = 1
1144
1145 MachineBasicBlock *ThisMBB = MBB;
1146 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1147 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1148 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1149
1150 MF->insert(I, MainMBB);
1151 MF->insert(I, SinkMBB);
1152 MF->push_back(RestoreMBB);
1153 RestoreMBB->setMachineBlockAddressTaken();
1154
1156
1157 // Transfer the remainder of BB and its successor edges to sinkMBB.
1158 SinkMBB->splice(SinkMBB->begin(), MBB,
1159 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1161
1162 // thisMBB:
1163 const int64_t FPOffset = 0; // Slot 1.
1164 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1165 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1166 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1167
1168 // Buf address.
1169 Register BufReg = MI.getOperand(1).getReg();
1170
1171 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1172 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1173
1174 // Prepare IP for longjmp.
1175 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1176 .addMBB(RestoreMBB);
1177 // Store IP for return from jmp, slot 2, offset = 1.
1178 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1179 .addReg(LabelReg)
1180 .addReg(BufReg)
1181 .addImm(LabelOffset)
1182 .addReg(0);
1183
1184 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1185 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1186 if (HasFP) {
1187 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1188 .addReg(SpecialRegs->getFramePointerRegister())
1189 .addReg(BufReg)
1190 .addImm(FPOffset)
1191 .addReg(0);
1192 }
1193
1194 // Store SP.
1195 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1196 .addReg(SpecialRegs->getStackPointerRegister())
1197 .addReg(BufReg)
1198 .addImm(SPOffset)
1199 .addReg(0);
1200
1201 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1202 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1203 if (BackChain) {
1204 Register BCReg = MRI.createVirtualRegister(PtrRC);
1205 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1206 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1207 .addReg(SpecialRegs->getStackPointerRegister())
1208 .addImm(TFL->getBackchainOffset(*MF))
1209 .addReg(0);
1210
1211 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1212 .addReg(BCReg)
1213 .addReg(BufReg)
1214 .addImm(BCOffset)
1215 .addReg(0);
1216 }
1217
1218 // Setup.
1219 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1220 .addMBB(RestoreMBB);
1221
1222 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1223 MIB.addRegMask(RegInfo->getNoPreservedMask());
1224
1225 ThisMBB->addSuccessor(MainMBB);
1226 ThisMBB->addSuccessor(RestoreMBB);
1227
1228 // mainMBB:
1229 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1230 MainMBB->addSuccessor(SinkMBB);
1231
1232 // sinkMBB:
1233 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1234 .addReg(MainDstReg)
1235 .addMBB(MainMBB)
1236 .addReg(RestoreDstReg)
1237 .addMBB(RestoreMBB);
1238
1239 // restoreMBB.
1240 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1241 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1242 RestoreMBB->addSuccessor(SinkMBB);
1243
1244 MI.eraseFromParent();
1245
1246 return SinkMBB;
1247}
1248
1251 MachineBasicBlock *MBB) const {
1252
1253 DebugLoc DL = MI.getDebugLoc();
1254 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1255
1256 MachineFunction *MF = MBB->getParent();
1258
1259 MVT PVT = getPointerTy(MF->getDataLayout());
1260 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1261 Register BufReg = MI.getOperand(0).getReg();
1262 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1263 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1264
1265 Register Tmp = MRI.createVirtualRegister(RC);
1266 Register BCReg = MRI.createVirtualRegister(RC);
1267
1269
1270 const int64_t FPOffset = 0;
1271 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1272 const int64_t BCOffset = 2 * PVT.getStoreSize();
1273 const int64_t SPOffset = 3 * PVT.getStoreSize();
1274 const int64_t LPOffset = 4 * PVT.getStoreSize();
1275
1276 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1277 .addReg(BufReg)
1278 .addImm(LabelOffset)
1279 .addReg(0);
1280
1281 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1282 SpecialRegs->getFramePointerRegister())
1283 .addReg(BufReg)
1284 .addImm(FPOffset)
1285 .addReg(0);
1286
1287 // We are restoring R13 even though we never stored in setjmp from llvm,
1288 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1289 // gcc setjmp and llvm longjmp.
1290 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1291 .addReg(BufReg)
1292 .addImm(LPOffset)
1293 .addReg(0);
1294
1295 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1296 if (BackChain) {
1297 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1298 .addReg(BufReg)
1299 .addImm(BCOffset)
1300 .addReg(0);
1301 }
1302
1303 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1304 SpecialRegs->getStackPointerRegister())
1305 .addReg(BufReg)
1306 .addImm(SPOffset)
1307 .addReg(0);
1308
1309 if (BackChain) {
1310 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1311 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1312 .addReg(BCReg)
1313 .addReg(SpecialRegs->getStackPointerRegister())
1314 .addImm(TFL->getBackchainOffset(*MF))
1315 .addReg(0);
1316 }
1317
1318 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1319
1320 MI.eraseFromParent();
1321 return MBB;
1322}
1323
1325 const MachineFunction &MF) const {
1326 // Without vector support, a v2i64 store would just be split again.
1327 return MemVT != MVT::v2i64 || Subtarget.hasVector();
1328}
1329
1331 EVT VecVT) const {
1332 // Without vector support, a v2i64 is just a pair of GPRs.
1333 return !Subtarget.hasVector();
1334}
1335
1336/// Returns true if stack probing through inline assembly is requested.
1338 // If the function specifically requests inline stack probes, emit them.
1339 if (MF.getFunction().hasFnAttribute("probe-stack"))
1340 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1341 "inline-asm";
1342 return false;
1343}
1344
1349
1354
1357 const AtomicRMWInst *RMW) const {
1358 // Don't expand subword operations as they require special treatment.
1359 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1361
1362 // Don't expand if there is a target instruction available.
1363 if (Subtarget.hasInterlockedAccess1() &&
1364 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1371
1373}
1374
1376 // We can use CGFI or CLGFI.
1377 return isInt<32>(Imm) || isUInt<32>(Imm);
1378}
1379
1381 // We can use ALGFI or SLGFI.
1382 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1383}
1384
1386 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1387 // Unaligned accesses should never be slower than the expanded version.
1388 // We check specifically for aligned accesses in the few cases where
1389 // they are required.
1390 if (Fast)
1391 *Fast = 1;
1392 return true;
1393}
1394
1396 EVT VT = Y.getValueType();
1397
1398 // We can use NC(G)RK for types in GPRs ...
1399 if (VT == MVT::i32 || VT == MVT::i64)
1400 return Subtarget.hasMiscellaneousExtensions3();
1401
1402 // ... or VNC for types in VRs.
1403 if (VT.isVector() || VT == MVT::i128)
1404 return Subtarget.hasVector();
1405
1406 return false;
1407}
1408
1409// Information about the addressing mode for a memory access.
1411 // True if a long displacement is supported.
1413
1414 // True if use of index register is supported.
1416
1417 AddressingMode(bool LongDispl, bool IdxReg) :
1418 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1419};
1420
1421// Return the desired addressing mode for a Load which has only one use (in
1422// the same block) which is a Store.
1424 Type *Ty) {
1425 // With vector support a Load->Store combination may be combined to either
1426 // an MVC or vector operations and it seems to work best to allow the
1427 // vector addressing mode.
1428 if (HasVector)
1429 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1430
1431 // Otherwise only the MVC case is special.
1432 bool MVC = Ty->isIntegerTy(8);
1433 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1434}
1435
1436// Return the addressing mode which seems most desirable given an LLVM
1437// Instruction pointer.
1438static AddressingMode
1441 switch (II->getIntrinsicID()) {
1442 default: break;
1443 case Intrinsic::memset:
1444 case Intrinsic::memmove:
1445 case Intrinsic::memcpy:
1446 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1447 }
1448 }
1449
1450 if (isa<LoadInst>(I) && I->hasOneUse()) {
1451 auto *SingleUser = *I->user_begin();
1452 if (SingleUser->getParent() == I->getParent()) {
1453 if (isa<ICmpInst>(SingleUser)) {
1454 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1455 if (C->getBitWidth() <= 64 &&
1456 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1457 // Comparison of memory with 16 bit signed / unsigned immediate
1458 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1459 } else if (isa<StoreInst>(SingleUser))
1460 // Load->Store
1461 return getLoadStoreAddrMode(HasVector, I->getType());
1462 }
1463 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1464 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1465 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1466 // Load->Store
1467 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1468 }
1469
1470 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1471
1472 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1473 // dependencies (LDE only supports small offsets).
1474 // * Utilize the vector registers to hold floating point
1475 // values (vector load / store instructions only support small
1476 // offsets).
1477
1478 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1479 I->getOperand(0)->getType());
1480 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1481 bool IsVectorAccess = MemAccessTy->isVectorTy();
1482
1483 // A store of an extracted vector element will be combined into a VSTE type
1484 // instruction.
1485 if (!IsVectorAccess && isa<StoreInst>(I)) {
1486 Value *DataOp = I->getOperand(0);
1487 if (isa<ExtractElementInst>(DataOp))
1488 IsVectorAccess = true;
1489 }
1490
1491 // A load which gets inserted into a vector element will be combined into a
1492 // VLE type instruction.
1493 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1494 User *LoadUser = *I->user_begin();
1495 if (isa<InsertElementInst>(LoadUser))
1496 IsVectorAccess = true;
1497 }
1498
1499 if (IsFPAccess || IsVectorAccess)
1500 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1501 }
1502
1503 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1504}
1505
1507 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1508 // Punt on globals for now, although they can be used in limited
1509 // RELATIVE LONG cases.
1510 if (AM.BaseGV)
1511 return false;
1512
1513 // Require a 20-bit signed offset.
1514 if (!isInt<20>(AM.BaseOffs))
1515 return false;
1516
1517 bool RequireD12 =
1518 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1519 AddressingMode SupportedAM(!RequireD12, true);
1520 if (I != nullptr)
1521 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1522
1523 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1524 return false;
1525
1526 if (!SupportedAM.IndexReg)
1527 // No indexing allowed.
1528 return AM.Scale == 0;
1529 else
1530 // Indexing is OK but no scale factor can be applied.
1531 return AM.Scale == 0 || AM.Scale == 1;
1532}
1533
1535 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1536 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1537 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1538
1539 assert(Limit != ~0U &&
1540 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1541
1542 if (Op.isZeroMemset())
1543 return false; // Memset zero: Use XC.
1544
1545 const int MVCFastLen = 16;
1546 // Use MVC up to 16 bytes for memcpy. Small memset uses STC/MVI for first
1547 // byte.
1548 if (Op.isMemcpy() && Op.size() <= MVCFastLen)
1549 return false;
1550 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1551 return false;
1552
1553 // Avoid unaligned VL/VST:s.
1554 if ((Op.size() >= 16 && !Op.isAligned(Align(8))) ||
1555 (Op.size() >= 25 && Op.size() <= 31))
1556 return false;
1557
1559 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1560}
1561
1563 LLVMContext &Context, const MemOp &Op,
1564 const AttributeList &FuncAttributes) const {
1565 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1566}
1567
1568bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1569 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1570 return false;
1571 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1572 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1573 return FromBits > ToBits;
1574}
1575
1577 if (!FromVT.isInteger() || !ToVT.isInteger())
1578 return false;
1579 unsigned FromBits = FromVT.getFixedSizeInBits();
1580 unsigned ToBits = ToVT.getFixedSizeInBits();
1581 return FromBits > ToBits;
1582}
1583
1585 unsigned Opc = N->getOpcode();
1586 if ((Opc == ISD::SINT_TO_FP || Opc == ISD::UINT_TO_FP) && VT.isVector() &&
1587 VT.getScalarSizeInBits() < N->getValueType(0).getScalarSizeInBits())
1588 return false;
1590}
1591
1592//===----------------------------------------------------------------------===//
1593// Inline asm support
1594//===----------------------------------------------------------------------===//
1595
1598 if (Constraint.size() == 1) {
1599 switch (Constraint[0]) {
1600 case 'a': // Address register
1601 case 'd': // Data register (equivalent to 'r')
1602 case 'f': // Floating-point register
1603 case 'h': // High-part register
1604 case 'r': // General-purpose register
1605 case 'v': // Vector register
1606 return C_RegisterClass;
1607
1608 case 'Q': // Memory with base and unsigned 12-bit displacement
1609 case 'R': // Likewise, plus an index
1610 case 'S': // Memory with base and signed 20-bit displacement
1611 case 'T': // Likewise, plus an index
1612 case 'm': // Equivalent to 'T'.
1613 return C_Memory;
1614
1615 case 'I': // Unsigned 8-bit constant
1616 case 'J': // Unsigned 12-bit constant
1617 case 'K': // Signed 16-bit constant
1618 case 'L': // Signed 20-bit displacement (on all targets we support)
1619 case 'M': // 0x7fffffff
1620 return C_Immediate;
1621
1622 default:
1623 break;
1624 }
1625 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1626 switch (Constraint[1]) {
1627 case 'Q': // Address with base and unsigned 12-bit displacement
1628 case 'R': // Likewise, plus an index
1629 case 'S': // Address with base and signed 20-bit displacement
1630 case 'T': // Likewise, plus an index
1631 return C_Address;
1632
1633 default:
1634 break;
1635 }
1636 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1637 if (StringRef("{@cc}").compare(Constraint) == 0)
1638 return C_Other;
1639 }
1640 return TargetLowering::getConstraintType(Constraint);
1641}
1642
1645 AsmOperandInfo &Info, const char *Constraint) const {
1647 Value *CallOperandVal = Info.CallOperandVal;
1648 // If we don't have a value, we can't do a match,
1649 // but allow it at the lowest weight.
1650 if (!CallOperandVal)
1651 return CW_Default;
1652 Type *type = CallOperandVal->getType();
1653 // Look at the constraint type.
1654 switch (*Constraint) {
1655 default:
1656 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1657 break;
1658
1659 case 'a': // Address register
1660 case 'd': // Data register (equivalent to 'r')
1661 case 'h': // High-part register
1662 case 'r': // General-purpose register
1663 Weight =
1664 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1665 break;
1666
1667 case 'f': // Floating-point register
1668 if (!useSoftFloat())
1669 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1670 break;
1671
1672 case 'v': // Vector register
1673 if (Subtarget.hasVector())
1674 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1675 : CW_Default;
1676 break;
1677
1678 case 'I': // Unsigned 8-bit constant
1679 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1680 if (isUInt<8>(C->getZExtValue()))
1681 Weight = CW_Constant;
1682 break;
1683
1684 case 'J': // Unsigned 12-bit constant
1685 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1686 if (isUInt<12>(C->getZExtValue()))
1687 Weight = CW_Constant;
1688 break;
1689
1690 case 'K': // Signed 16-bit constant
1691 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1692 if (isInt<16>(C->getSExtValue()))
1693 Weight = CW_Constant;
1694 break;
1695
1696 case 'L': // Signed 20-bit displacement (on all targets we support)
1697 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1698 if (isInt<20>(C->getSExtValue()))
1699 Weight = CW_Constant;
1700 break;
1701
1702 case 'M': // 0x7fffffff
1703 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1704 if (C->getZExtValue() == 0x7fffffff)
1705 Weight = CW_Constant;
1706 break;
1707 }
1708 return Weight;
1709}
1710
1711// Parse a "{tNNN}" register constraint for which the register type "t"
1712// has already been verified. MC is the class associated with "t" and
1713// Map maps 0-based register numbers to LLVM register numbers.
1714static std::pair<unsigned, const TargetRegisterClass *>
1716 const unsigned *Map, unsigned Size) {
1717 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1718 if (isdigit(Constraint[2])) {
1719 unsigned Index;
1720 bool Failed =
1721 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1722 if (!Failed && Index < Size && Map[Index])
1723 return std::make_pair(Map[Index], RC);
1724 }
1725 return std::make_pair(0U, nullptr);
1726}
1727
1728std::pair<unsigned, const TargetRegisterClass *>
1730 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1731 if (Constraint.size() == 1) {
1732 // GCC Constraint Letters
1733 switch (Constraint[0]) {
1734 default: break;
1735 case 'd': // Data register (equivalent to 'r')
1736 case 'r': // General-purpose register
1737 // MVT::Other has no size, e.g. an aggregate operand that could not be
1738 // converted to an integer type.
1739 if (VT == MVT::Other)
1740 break;
1741 if (VT.getSizeInBits() == 64)
1742 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1743 else if (VT.getSizeInBits() == 128)
1744 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1745 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1746
1747 case 'a': // Address register
1748 if (VT == MVT::i64)
1749 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1750 else if (VT == MVT::i128)
1751 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1752 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1753
1754 case 'h': // High-part register (an LLVM extension)
1755 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1756
1757 case 'f': // Floating-point register
1758 if (!useSoftFloat()) {
1759 if (VT == MVT::Other)
1760 break;
1761 if (VT.getSizeInBits() == 16)
1762 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1763 else if (VT.getSizeInBits() == 64)
1764 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1765 else if (VT.getSizeInBits() == 128)
1766 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1767 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1768 }
1769 break;
1770
1771 case 'v': // Vector register
1772 if (Subtarget.hasVector()) {
1773 if (VT == MVT::Other)
1774 break;
1775 if (VT.getSizeInBits() == 16)
1776 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1777 if (VT.getSizeInBits() == 32)
1778 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1779 if (VT.getSizeInBits() == 64)
1780 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1781 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1782 }
1783 break;
1784 }
1785 }
1786 if (Constraint.starts_with("{")) {
1787
1788 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1789 // to check the size on.
1790 auto getVTSizeInBits = [&VT]() {
1791 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1792 };
1793
1794 // We need to override the default register parsing for GPRs and FPRs
1795 // because the interpretation depends on VT. The internal names of
1796 // the registers are also different from the external names
1797 // (F0D and F0S instead of F0, etc.).
1798 if (Constraint[1] == 'r') {
1799 if (getVTSizeInBits() == 32)
1800 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1802 if (getVTSizeInBits() == 128)
1803 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1805 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1807 }
1808 if (Constraint[1] == 'f') {
1809 if (useSoftFloat())
1810 return std::make_pair(
1811 0u, static_cast<const TargetRegisterClass *>(nullptr));
1812 if (getVTSizeInBits() == 16)
1813 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1815 if (getVTSizeInBits() == 32)
1816 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1818 if (getVTSizeInBits() == 128)
1819 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1821 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1823 }
1824 if (Constraint[1] == 'v') {
1825 if (!Subtarget.hasVector())
1826 return std::make_pair(
1827 0u, static_cast<const TargetRegisterClass *>(nullptr));
1828 if (getVTSizeInBits() == 16)
1829 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1831 if (getVTSizeInBits() == 32)
1832 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1834 if (getVTSizeInBits() == 64)
1835 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1837 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1839 }
1840 if (Constraint[1] == '@') {
1841 if (StringRef("{@cc}").compare(Constraint) == 0)
1842 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1843 }
1844 }
1845 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1846}
1847
1848// FIXME? Maybe this could be a TableGen attribute on some registers and
1849// this table could be generated automatically from RegInfo.
1852 const MachineFunction &MF) const {
1853 Register Reg =
1855 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1856 : SystemZ::NoRegister)
1857 .Case("r15",
1858 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1859 .Default(Register());
1860
1861 return Reg;
1862}
1863
1865 ExceptionHandling EH, const Constant *PersonalityFn) const {
1866 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1867}
1868
1870 ExceptionHandling EH, const Constant *PersonalityFn) const {
1871 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1872}
1873
1874// Convert condition code in CCReg to an i32 value.
1876 SDLoc DL(CCReg);
1877 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1878 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1879 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1880}
1881
1882// Lower @cc targets via setcc.
1884 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1885 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1886 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1887 return SDValue();
1888
1889 // Check that return type is valid.
1890 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1891 OpInfo.ConstraintVT.getSizeInBits() < 8)
1892 report_fatal_error("Glue output operand is of invalid type");
1893
1894 if (Glue.getNode()) {
1895 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1896 Chain = Glue.getValue(1);
1897 } else
1898 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1899 return getCCResult(DAG, Glue);
1900}
1901
1903 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1904 SelectionDAG &DAG) const {
1905 // Only support length 1 constraints for now.
1906 if (Constraint.size() == 1) {
1907 switch (Constraint[0]) {
1908 case 'I': // Unsigned 8-bit constant
1909 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1910 if (isUInt<8>(C->getZExtValue()))
1911 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1912 Op.getValueType()));
1913 return;
1914
1915 case 'J': // Unsigned 12-bit constant
1916 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1917 if (isUInt<12>(C->getZExtValue()))
1918 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1919 Op.getValueType()));
1920 return;
1921
1922 case 'K': // Signed 16-bit constant
1923 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1924 if (isInt<16>(C->getSExtValue()))
1925 Ops.push_back(DAG.getSignedTargetConstant(
1926 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1927 return;
1928
1929 case 'L': // Signed 20-bit displacement (on all targets we support)
1930 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1931 if (isInt<20>(C->getSExtValue()))
1932 Ops.push_back(DAG.getSignedTargetConstant(
1933 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1934 return;
1935
1936 case 'M': // 0x7fffffff
1937 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1938 if (C->getZExtValue() == 0x7fffffff)
1939 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1940 Op.getValueType()));
1941 return;
1942 }
1943 }
1945}
1946
1947//===----------------------------------------------------------------------===//
1948// Calling conventions
1949//===----------------------------------------------------------------------===//
1950
1951#define GET_CALLING_CONV_IMPL
1952#include "SystemZGenCallingConv.inc"
1953
1955 CallingConv::ID) const {
1956 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1957 SystemZ::R14D, 0 };
1958 return ScratchRegs;
1959}
1960
1962 Type *ToType) const {
1963 return isTruncateFree(FromType, ToType);
1964}
1965
1967 return CI->isTailCall();
1968}
1969
1970// Value is a value that has been passed to us in the location described by VA
1971// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1972// any loads onto Chain.
1974 CCValAssign &VA, SDValue Chain,
1975 SDValue Value) {
1976 // If the argument has been promoted from a smaller type, insert an
1977 // assertion to capture this.
1978 if (VA.getLocInfo() == CCValAssign::SExt)
1980 DAG.getValueType(VA.getValVT()));
1981 else if (VA.getLocInfo() == CCValAssign::ZExt)
1983 DAG.getValueType(VA.getValVT()));
1984
1985 if (VA.isExtInLoc())
1986 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1987 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1988 // If this is a short vector argument loaded from the stack,
1989 // extend from i64 to full vector size and then bitcast.
1990 assert(VA.getLocVT() == MVT::i64);
1991 assert(VA.getValVT().isVector());
1992 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1993 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1994 } else
1995 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1996 return Value;
1997}
1998
1999// Value is a value of type VA.getValVT() that we need to copy into
2000// the location described by VA. Return a copy of Value converted to
2001// VA.getValVT(). The caller is responsible for handling indirect values.
2003 CCValAssign &VA, SDValue Value) {
2004 switch (VA.getLocInfo()) {
2005 case CCValAssign::SExt:
2006 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
2007 case CCValAssign::ZExt:
2008 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
2009 case CCValAssign::AExt:
2010 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
2011 case CCValAssign::BCvt: {
2012 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
2013 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
2014 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
2015 // For an f32 vararg we need to first promote it to an f64 and then
2016 // bitcast it to an i64.
2017 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
2018 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
2019 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
2020 ? MVT::v2i64
2021 : VA.getLocVT();
2022 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
2023 // For ELF, this is a short vector argument to be stored to the stack,
2024 // bitcast to v2i64 and then extract first element.
2025 if (BitCastToType == MVT::v2i64)
2026 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
2027 DAG.getConstant(0, DL, MVT::i32));
2028 return Value;
2029 }
2030 case CCValAssign::Full:
2031 return Value;
2032 default:
2033 llvm_unreachable("Unhandled getLocInfo()");
2034 }
2035}
2036
2038 SDLoc DL(In);
2039 SDValue Lo, Hi;
2040 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2041 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
2042 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
2043 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
2044 DAG.getConstant(64, DL, MVT::i32)));
2045 } else {
2046 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
2047 }
2048
2049 return DAG.getNode(SystemZISD::PAIR128, DL, MVT::v2i64, Hi, Lo);
2050}
2051
2053 SDLoc DL(In);
2054 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
2055 DL, MVT::i64, In);
2056 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
2057 DL, MVT::i64, In);
2058
2059 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2060 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
2061 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
2062 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
2063 DAG.getConstant(64, DL, MVT::i32));
2064 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
2065 } else {
2066 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
2067 }
2068}
2069
2071 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2072 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2073 EVT ValueVT = Val.getValueType();
2074 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2075 // Inline assembly operand.
2076 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
2077 return true;
2078 }
2079
2080 return false;
2081}
2082
2084 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2085 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2086 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2087 // Inline assembly operand.
2088 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2089 return DAG.getBitcast(ValueVT, Res);
2090 }
2091
2092 return SDValue();
2093}
2094
2095// The first part of a split stack argument is at index I in Args (and
2096// ArgLocs). Return the type of a part and the number of them by reference.
2097template <class ArgTy>
2099 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2100 MVT &PartVT, unsigned &NumParts) {
2101 if (!Args[I].Flags.isSplit())
2102 return false;
2103 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2104 "ArgLocs havoc.");
2105 PartVT = ArgLocs[I].getValVT();
2106 NumParts = 1;
2107 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2108 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2109 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2110 ++NumParts;
2111 if (Args[PartIdx].Flags.isSplitEnd())
2112 break;
2113 }
2114 return true;
2115}
2116
2117// Return the virtual register holding the incoming "ADA" special register (R5)
2118// of an XPLINK function, creating it on first use. LowerFormalArguments is not
2119// called for naked functions, but those still get R5 on entry and may use it to
2120// address globals and functions.
2122 SystemZMachineFunctionInfo *FuncInfo =
2124 Register ADAvReg = FuncInfo->getADAVirtualRegister();
2125 if (ADAvReg)
2126 return ADAvReg;
2127
2129 ADAvReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2130 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2132 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2133 FuncInfo->setADAVirtualRegister(ADAvReg);
2134 return ADAvReg;
2135}
2136
2137// Passing or returning vector types or i128 in XPLINK64 is only supported if
2138// the vector facility is available. Report an error otherwise.
2139template <typename ArgT>
2141 SelectionDAG &DAG,
2142 const SmallVectorImpl<ArgT> &Args) {
2143 if (!Subtarget.isTargetXPLINK64() || Subtarget.hasVector())
2144 return;
2145 if (any_of(Args, [](const ArgT &Arg) {
2146 return Arg.ArgVT.isVector() || Arg.ArgVT == MVT::i128;
2147 }))
2150 "vector and i128 types without vector facility are not yet supported "
2151 "in XPLINK64"));
2152}
2153
2155 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2156 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2157 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2158 diagnoseXPLINK64VectorWithoutVF(Subtarget, DAG, Ins);
2160 MachineFrameInfo &MFI = MF.getFrameInfo();
2162 SystemZMachineFunctionInfo *FuncInfo =
2164 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2165 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2166
2167 // Assign locations to all of the incoming arguments.
2169 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2170 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2171 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2172
2173 unsigned NumFixedGPRs = 0;
2174 unsigned NumFixedFPRs = 0;
2175 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2176 SDValue ArgValue;
2177 CCValAssign &VA = ArgLocs[I];
2178 EVT LocVT = VA.getLocVT();
2179 if (VA.isRegLoc()) {
2180 // Arguments passed in registers
2181 const TargetRegisterClass *RC;
2182 switch (LocVT.getSimpleVT().SimpleTy) {
2183 default:
2184 // Integers smaller than i64 should be promoted to i64.
2185 llvm_unreachable("Unexpected argument type");
2186 case MVT::i32:
2187 NumFixedGPRs += 1;
2188 RC = &SystemZ::GR32BitRegClass;
2189 break;
2190 case MVT::i64:
2191 NumFixedGPRs += 1;
2192 RC = &SystemZ::GR64BitRegClass;
2193 break;
2194 case MVT::f16:
2195 NumFixedFPRs += 1;
2196 RC = &SystemZ::FP16BitRegClass;
2197 break;
2198 case MVT::f32:
2199 NumFixedFPRs += 1;
2200 RC = &SystemZ::FP32BitRegClass;
2201 break;
2202 case MVT::f64:
2203 NumFixedFPRs += 1;
2204 RC = &SystemZ::FP64BitRegClass;
2205 break;
2206 case MVT::f128:
2207 NumFixedFPRs += 2;
2208 RC = &SystemZ::FP128BitRegClass;
2209 break;
2210 case MVT::v16i8:
2211 case MVT::v8i16:
2212 case MVT::v4i32:
2213 case MVT::v2i64:
2214 case MVT::v8f16:
2215 case MVT::v4f32:
2216 case MVT::v2f64:
2217 RC = &SystemZ::VR128BitRegClass;
2218 break;
2219 }
2220
2221 Register VReg = MRI.createVirtualRegister(RC);
2222 MRI.addLiveIn(VA.getLocReg(), VReg);
2223 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2224 } else {
2225 assert(VA.isMemLoc() && "Argument not register or memory");
2226
2227 // Create the frame index object for this incoming parameter.
2228 // FIXME: Pre-include call frame size in the offset, should not
2229 // need to manually add it here.
2230 int64_t ArgSPOffset = VA.getLocMemOffset();
2231 if (Subtarget.isTargetXPLINK64()) {
2232 auto &XPRegs =
2233 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2234 ArgSPOffset += XPRegs.getCallFrameSize();
2235 }
2236 int FI =
2237 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2238
2239 // Create the SelectionDAG nodes corresponding to a load
2240 // from this parameter. Unpromoted ints and floats are
2241 // passed as right-justified 8-byte values.
2242 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2243 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2244 VA.getLocVT() == MVT::f16) {
2245 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2246 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2247 DAG.getIntPtrConstant(SlotOffs, DL));
2248 }
2249 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2251 }
2252
2253 // Convert the value of the argument register into the value that's
2254 // being passed.
2255 if (VA.getLocInfo() == CCValAssign::Indirect) {
2256 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2258 // If the original argument was split (e.g. i128), we need
2259 // to load all parts of it here (using the same address).
2260 MVT PartVT;
2261 unsigned NumParts;
2262 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2263 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2264 ++I;
2265 CCValAssign &PartVA = ArgLocs[I];
2266 unsigned PartOffset = Ins[I].PartOffset;
2267 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2268 DAG.getIntPtrConstant(PartOffset, DL));
2269 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2271 assert(PartOffset && "Offset should be non-zero.");
2272 }
2273 }
2274 } else if (Subtarget.isTargetXPLINK64() &&
2275 (VA.getLocInfo() == CCValAssign::SExt ||
2276 VA.getLocInfo() == CCValAssign::ZExt) &&
2277 Ins[I].ArgVT.isSimple()) {
2278 // Some prior z/OS compilers do not always perform the extension of
2279 // short integer arguments or pointers. To accommodate those, do not
2280 // rely on that extension by avoiding any AssertSext/AssertZext nodes by
2281 // directly truncating ArgValue to the original argument type.
2282 MVT OrigVT = Ins[I].ArgVT.getSimpleVT();
2283 InVals.push_back(DAG.getNode(ISD::TRUNCATE, DL, OrigVT, ArgValue));
2284 } else
2285 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2286 }
2287
2288 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2289 // Save the number of non-varargs registers for later use by va_start, etc.
2290 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2291 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2292
2293 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2294 Subtarget.getSpecialRegisters());
2295
2296 // Likewise the address (in the form of a frame index) of where the
2297 // first stack vararg would be. The 1-byte size here is arbitrary.
2298 // FIXME: Pre-include call frame size in the offset, should not
2299 // need to manually add it here.
2300 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2301 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2302 FuncInfo->setVarArgsFrameIndex(FI);
2303 }
2304
2305 if (IsVarArg && Subtarget.isTargetELF()) {
2306 // Save the number of non-varargs registers for later use by va_start, etc.
2307 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2308 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2309
2310 // Likewise the address (in the form of a frame index) of where the
2311 // first stack vararg would be. The 1-byte size here is arbitrary.
2312 int64_t VarArgsOffset = CCInfo.getStackSize();
2313 FuncInfo->setVarArgsFrameIndex(
2314 MFI.CreateFixedObject(1, VarArgsOffset, true));
2315
2316 // ...and a similar frame index for the caller-allocated save area
2317 // that will be used to store the incoming registers.
2318 int64_t RegSaveOffset =
2319 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2320 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2321 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2322
2323 // Store the FPR varargs in the reserved frame slots. (We store the
2324 // GPRs as part of the prologue.)
2325 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2327 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2328 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2329 int FI =
2331 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2333 &SystemZ::FP64BitRegClass);
2334 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2335 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2337 }
2338 // Join the stores, which are independent of one another.
2339 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2340 ArrayRef(&MemOps[NumFixedFPRs],
2341 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2342 }
2343 }
2344
2345 return Chain;
2346}
2347
2348static bool canUseSiblingCall(const CCState &ArgCCInfo,
2351 // Punt if there are any indirect or stack arguments, or if the call
2352 // needs the callee-saved argument register R6, or if the call uses
2353 // the callee-saved register arguments SwiftSelf and SwiftError.
2354 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2355 CCValAssign &VA = ArgLocs[I];
2357 return false;
2358 if (!VA.isRegLoc())
2359 return false;
2360 Register Reg = VA.getLocReg();
2361 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2362 return false;
2363 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2364 return false;
2365 }
2366 return true;
2367}
2368
2370 unsigned Offset, bool LoadAdr = false) {
2374
2375 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2376 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2377
2378 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2379 if (!LoadAdr)
2380 Result = DAG.getLoad(
2381 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2383
2384 return Result;
2385}
2386
2387// ADA access using Global value
2388// Note: for functions, address of descriptor is returned
2390 EVT PtrVT) {
2391 unsigned ADAtype;
2392 bool LoadAddr = false;
2393 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2394 bool IsFunction =
2395 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2396 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2397
2398 if (IsFunction) {
2399 if (IsInternal) {
2401 LoadAddr = true;
2402 } else
2404 } else {
2406 }
2407 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2408
2409 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2410}
2411
2412static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2413 SDLoc &DL, SDValue &Chain) {
2414 unsigned ADADelta = 0; // ADA offset in desc.
2415 unsigned EPADelta = 8; // EPA offset in desc.
2418
2419 // XPLink calling convention.
2420 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2421 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2422 G->getGlobal()->hasPrivateLinkage());
2423 if (IsInternal) {
2425 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2426 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2427 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2428 return true;
2429 } else {
2431 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2432 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2433 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2434 }
2435 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2437 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2438 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2439 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2440 } else {
2441 // Function pointer case
2442 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2443 DAG.getConstant(ADADelta, DL, PtrVT));
2444 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2446 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2447 DAG.getConstant(EPADelta, DL, PtrVT));
2448 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2450 }
2451 return false;
2452}
2453
2454SDValue
2456 SmallVectorImpl<SDValue> &InVals) const {
2457 SelectionDAG &DAG = CLI.DAG;
2458 SDLoc &DL = CLI.DL;
2460 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2462 SDValue Chain = CLI.Chain;
2463 SDValue Callee = CLI.Callee;
2464 bool &IsTailCall = CLI.IsTailCall;
2465 CallingConv::ID CallConv = CLI.CallConv;
2466 bool IsVarArg = CLI.IsVarArg;
2468 EVT PtrVT = getPointerTy(MF.getDataLayout());
2469 LLVMContext &Ctx = *DAG.getContext();
2470 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2471
2472 diagnoseXPLINK64VectorWithoutVF(Subtarget, DAG, Outs);
2473 diagnoseXPLINK64VectorWithoutVF(Subtarget, DAG, Ins);
2474
2475 // FIXME: z/OS support to be added in later.
2476 if (Subtarget.isTargetXPLINK64()) {
2477 if (CLI.CB && CLI.CB->isMustTailCall())
2478 report_fatal_error("musttail call is not supported on XPLINK64");
2479 IsTailCall = false;
2480 }
2481
2482 // Integer args <=32 bits should have an extension attribute.
2483 verifyNarrowIntegerArgs_Call(CLI, Outs, &MF.getFunction(), Callee);
2484
2485 // Analyze the operands of the call, assigning locations to each operand.
2487 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2488 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2489
2490 // We don't support GuaranteedTailCallOpt, only automatically-detected
2491 // sibling calls.
2492 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2493 IsTailCall = false;
2494
2495 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
2496 report_fatal_error("failed to perform tail call elimination on a call "
2497 "site marked musttail");
2498
2499 // Get a count of how many bytes are to be pushed on the stack.
2500 unsigned NumBytes = ArgCCInfo.getStackSize();
2501
2502 // Mark the start of the call.
2503 if (!IsTailCall)
2504 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2505
2506 // Copy argument values to their designated locations.
2508 SmallVector<SDValue, 8> MemOpChains;
2509 SDValue StackPtr;
2510 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2511 CCValAssign &VA = ArgLocs[I];
2512 SDValue ArgValue = OutVals[I];
2513
2514 if (VA.getLocInfo() == CCValAssign::Indirect) {
2515 // Store the argument in a stack slot and pass its address.
2516 EVT SlotVT;
2517 MVT PartVT;
2518 unsigned NumParts = 1;
2519 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2520 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2521 else
2522 SlotVT = Outs[I].VT;
2523 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2524 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2525
2526 MachinePointerInfo StackPtrInfo =
2528 MemOpChains.push_back(
2529 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2530 // If the original argument was split (e.g. i128), we need
2531 // to store all parts of it here (and pass just one address).
2532 assert(Outs[I].PartOffset == 0);
2533 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2534 ++I;
2535 SDValue PartValue = OutVals[I];
2536 unsigned PartOffset = Outs[I].PartOffset;
2537 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2538 DAG.getIntPtrConstant(PartOffset, DL));
2539 MemOpChains.push_back(
2540 DAG.getStore(Chain, DL, PartValue, Address,
2541 StackPtrInfo.getWithOffset(PartOffset)));
2542 assert(PartOffset && "Offset should be non-zero.");
2543 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2544 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2545 }
2546 ArgValue = SpillSlot;
2547 } else
2548 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2549
2550 if (VA.isRegLoc()) {
2551 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2552 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2553 // and low values.
2554 if (VA.getLocVT() == MVT::i128)
2555 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2556 // Queue up the argument copies and emit them at the end.
2557 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2558 } else {
2559 assert(VA.isMemLoc() && "Argument not register or memory");
2560
2561 // Work out the address of the stack slot. Unpromoted ints and
2562 // floats are passed as right-justified 8-byte values.
2563 if (!StackPtr.getNode())
2564 StackPtr = DAG.getCopyFromReg(Chain, DL,
2565 Regs->getStackPointerRegister(), PtrVT);
2566 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2567 VA.getLocMemOffset();
2568 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2569 Offset += 4;
2570 else if (VA.getLocVT() == MVT::f16)
2571 Offset += 6;
2572 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2574
2575 // Emit the store.
2576 MemOpChains.push_back(
2577 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2578
2579 // Although long doubles or vectors are passed through the stack when
2580 // they are vararg (non-fixed arguments), if a long double or vector
2581 // occupies the third and fourth slot of the argument list GPR3 should
2582 // still shadow the third slot of the argument list.
2583 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2584 SDValue ShadowArgValue =
2585 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2586 DAG.getIntPtrConstant(1, DL));
2587 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2588 }
2589 }
2590 }
2591
2592 // Join the stores, which are independent of one another.
2593 if (!MemOpChains.empty())
2594 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2595
2596 // Accept direct calls by converting symbolic call addresses to the
2597 // associated Target* opcodes. Force %r1 to be used for indirect
2598 // tail calls.
2599 SDValue Glue;
2600
2601 if (Subtarget.isTargetXPLINK64()) {
2602 SDValue ADA;
2603 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2604 if (!IsBRASL) {
2605 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2606 ->getAddressOfCalleeRegister();
2607 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2608 Glue = Chain.getValue(1);
2609 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2610 }
2611 RegsToPass.push_back(std::make_pair(
2612 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2613 } else {
2614 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2615 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2616 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2617 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2618 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2619 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2620 } else if (IsTailCall) {
2621 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2622 Glue = Chain.getValue(1);
2623 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2624 }
2625 }
2626
2627 // Build a sequence of copy-to-reg nodes, chained and glued together.
2628 for (const auto &[Reg, N] : RegsToPass) {
2629 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2630 Glue = Chain.getValue(1);
2631 }
2632
2633 // The first call operand is the chain and the second is the target address.
2635 Ops.push_back(Chain);
2636 Ops.push_back(Callee);
2637
2638 // Add argument registers to the end of the list so that they are
2639 // known live into the call.
2640 for (const auto &[Reg, N] : RegsToPass)
2641 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2642
2643 // Add a register mask operand representing the call-preserved registers.
2644 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2645 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2646 assert(Mask && "Missing call preserved mask for calling convention");
2647 Ops.push_back(DAG.getRegisterMask(Mask));
2648
2649 // Glue the call to the argument copies, if any.
2650 if (Glue.getNode())
2651 Ops.push_back(Glue);
2652
2653 // Emit the call.
2654 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2655 if (IsTailCall) {
2656 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2657 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2658 return Ret;
2659 }
2660 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2661 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2662 Glue = Chain.getValue(1);
2663
2664 // Mark the end of the call, which is glued to the call itself.
2665 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2666 Glue = Chain.getValue(1);
2667
2668 // Assign locations to each value returned by this call.
2670 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2671 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2672
2673 // Copy all of the result registers out of their specified physreg.
2674 for (CCValAssign &VA : RetLocs) {
2675 // Copy the value out, gluing the copy to the end of the call sequence.
2676 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2677 VA.getLocVT(), Glue);
2678 Chain = RetValue.getValue(1);
2679 Glue = RetValue.getValue(2);
2680
2681 // Convert the value of the return register into the value that's
2682 // being returned.
2683 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2684 }
2685
2686 return Chain;
2687}
2688
2689// Generate a call taking the given operands as arguments and returning a
2690// result of type RetVT.
2692 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2693 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2694 bool DoesNotReturn, bool IsReturnValueUsed) const {
2696 Args.reserve(Ops.size());
2697
2698 for (SDValue Op : Ops) {
2700 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2701 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2702 Entry.IsZExt = !Entry.IsSExt;
2703 Args.push_back(Entry);
2704 }
2705
2706 SDValue Callee =
2707 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2708
2709 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2711 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2712 CLI.setDebugLoc(DL)
2713 .setChain(Chain)
2714 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2715 .setNoReturn(DoesNotReturn)
2716 .setDiscardResult(!IsReturnValueUsed)
2717 .setSExtResult(SignExtend)
2718 .setZExtResult(!SignExtend);
2719 return LowerCallTo(CLI);
2720}
2721
2723 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2725 const Type *RetTy) const {
2726 // Special case that we cannot easily detect in RetCC_SystemZ since
2727 // i128 may not be a legal type.
2728 for (auto &Out : Outs)
2729 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2730 return false;
2731
2733 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2734 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2735}
2736
2737SDValue
2739 bool IsVarArg,
2741 const SmallVectorImpl<SDValue> &OutVals,
2742 const SDLoc &DL, SelectionDAG &DAG) const {
2744
2745 diagnoseXPLINK64VectorWithoutVF(Subtarget, DAG, Outs);
2746
2747 // Integer args <=32 bits should have an extension attribute.
2748 verifyNarrowIntegerArgs_Ret(CallConv, Outs, &MF.getFunction());
2749
2750 // Assign locations to each returned value.
2752 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2753 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2754
2755 // Quick exit for void returns
2756 if (RetLocs.empty())
2757 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2758
2759 if (CallConv == CallingConv::GHC)
2760 report_fatal_error("GHC functions return void only");
2761
2762 // Copy the result values into the output registers.
2763 SDValue Glue;
2765 RetOps.push_back(Chain);
2766 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2767 CCValAssign &VA = RetLocs[I];
2768 SDValue RetValue = OutVals[I];
2769
2770 // Make the return register live on exit.
2771 assert(VA.isRegLoc() && "Can only return in registers!");
2772
2773 // Promote the value as required.
2774 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2775
2776 // Chain and glue the copies together.
2777 Register Reg = VA.getLocReg();
2778 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2779 Glue = Chain.getValue(1);
2780 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2781 }
2782
2783 // Update chain and glue.
2784 RetOps[0] = Chain;
2785 if (Glue.getNode())
2786 RetOps.push_back(Glue);
2787
2788 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2789}
2790
2791// Return true if Op is an intrinsic node with chain that returns the CC value
2792// as its only (other) argument. Provide the associated SystemZISD opcode and
2793// the mask of valid CC values if so.
2794static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2795 unsigned &CCValid) {
2796 unsigned Id = Op.getConstantOperandVal(1);
2797 switch (Id) {
2798 case Intrinsic::s390_tbegin:
2799 Opcode = SystemZISD::TBEGIN;
2800 CCValid = SystemZ::CCMASK_TBEGIN;
2801 return true;
2802
2803 case Intrinsic::s390_tbegin_nofloat:
2804 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2805 CCValid = SystemZ::CCMASK_TBEGIN;
2806 return true;
2807
2808 case Intrinsic::s390_tend:
2809 Opcode = SystemZISD::TEND;
2810 CCValid = SystemZ::CCMASK_TEND;
2811 return true;
2812
2813 default:
2814 return false;
2815 }
2816}
2817
2818// Return true if Op is an intrinsic node without chain that returns the
2819// CC value as its final argument. Provide the associated SystemZISD
2820// opcode and the mask of valid CC values if so.
2821static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2822 unsigned Id = Op.getConstantOperandVal(0);
2823 switch (Id) {
2824 case Intrinsic::s390_vpkshs:
2825 case Intrinsic::s390_vpksfs:
2826 case Intrinsic::s390_vpksgs:
2827 Opcode = SystemZISD::PACKS_CC;
2828 CCValid = SystemZ::CCMASK_VCMP;
2829 return true;
2830
2831 case Intrinsic::s390_vpklshs:
2832 case Intrinsic::s390_vpklsfs:
2833 case Intrinsic::s390_vpklsgs:
2834 Opcode = SystemZISD::PACKLS_CC;
2835 CCValid = SystemZ::CCMASK_VCMP;
2836 return true;
2837
2838 case Intrinsic::s390_vceqbs:
2839 case Intrinsic::s390_vceqhs:
2840 case Intrinsic::s390_vceqfs:
2841 case Intrinsic::s390_vceqgs:
2842 case Intrinsic::s390_vceqqs:
2843 Opcode = SystemZISD::VICMPES;
2844 CCValid = SystemZ::CCMASK_VCMP;
2845 return true;
2846
2847 case Intrinsic::s390_vchbs:
2848 case Intrinsic::s390_vchhs:
2849 case Intrinsic::s390_vchfs:
2850 case Intrinsic::s390_vchgs:
2851 case Intrinsic::s390_vchqs:
2852 Opcode = SystemZISD::VICMPHS;
2853 CCValid = SystemZ::CCMASK_VCMP;
2854 return true;
2855
2856 case Intrinsic::s390_vchlbs:
2857 case Intrinsic::s390_vchlhs:
2858 case Intrinsic::s390_vchlfs:
2859 case Intrinsic::s390_vchlgs:
2860 case Intrinsic::s390_vchlqs:
2861 Opcode = SystemZISD::VICMPHLS;
2862 CCValid = SystemZ::CCMASK_VCMP;
2863 return true;
2864
2865 case Intrinsic::s390_vtm:
2866 Opcode = SystemZISD::VTM;
2867 CCValid = SystemZ::CCMASK_VCMP;
2868 return true;
2869
2870 case Intrinsic::s390_vfaebs:
2871 case Intrinsic::s390_vfaehs:
2872 case Intrinsic::s390_vfaefs:
2873 Opcode = SystemZISD::VFAE_CC;
2874 CCValid = SystemZ::CCMASK_ANY;
2875 return true;
2876
2877 case Intrinsic::s390_vfaezbs:
2878 case Intrinsic::s390_vfaezhs:
2879 case Intrinsic::s390_vfaezfs:
2880 Opcode = SystemZISD::VFAEZ_CC;
2881 CCValid = SystemZ::CCMASK_ANY;
2882 return true;
2883
2884 case Intrinsic::s390_vfeebs:
2885 case Intrinsic::s390_vfeehs:
2886 case Intrinsic::s390_vfeefs:
2887 Opcode = SystemZISD::VFEE_CC;
2888 CCValid = SystemZ::CCMASK_ANY;
2889 return true;
2890
2891 case Intrinsic::s390_vfeezbs:
2892 case Intrinsic::s390_vfeezhs:
2893 case Intrinsic::s390_vfeezfs:
2894 Opcode = SystemZISD::VFEEZ_CC;
2895 CCValid = SystemZ::CCMASK_ANY;
2896 return true;
2897
2898 case Intrinsic::s390_vfenebs:
2899 case Intrinsic::s390_vfenehs:
2900 case Intrinsic::s390_vfenefs:
2901 Opcode = SystemZISD::VFENE_CC;
2902 CCValid = SystemZ::CCMASK_ANY;
2903 return true;
2904
2905 case Intrinsic::s390_vfenezbs:
2906 case Intrinsic::s390_vfenezhs:
2907 case Intrinsic::s390_vfenezfs:
2908 Opcode = SystemZISD::VFENEZ_CC;
2909 CCValid = SystemZ::CCMASK_ANY;
2910 return true;
2911
2912 case Intrinsic::s390_vistrbs:
2913 case Intrinsic::s390_vistrhs:
2914 case Intrinsic::s390_vistrfs:
2915 Opcode = SystemZISD::VISTR_CC;
2917 return true;
2918
2919 case Intrinsic::s390_vstrcbs:
2920 case Intrinsic::s390_vstrchs:
2921 case Intrinsic::s390_vstrcfs:
2922 Opcode = SystemZISD::VSTRC_CC;
2923 CCValid = SystemZ::CCMASK_ANY;
2924 return true;
2925
2926 case Intrinsic::s390_vstrczbs:
2927 case Intrinsic::s390_vstrczhs:
2928 case Intrinsic::s390_vstrczfs:
2929 Opcode = SystemZISD::VSTRCZ_CC;
2930 CCValid = SystemZ::CCMASK_ANY;
2931 return true;
2932
2933 case Intrinsic::s390_vstrsb:
2934 case Intrinsic::s390_vstrsh:
2935 case Intrinsic::s390_vstrsf:
2936 Opcode = SystemZISD::VSTRS_CC;
2937 CCValid = SystemZ::CCMASK_ANY;
2938 return true;
2939
2940 case Intrinsic::s390_vstrszb:
2941 case Intrinsic::s390_vstrszh:
2942 case Intrinsic::s390_vstrszf:
2943 Opcode = SystemZISD::VSTRSZ_CC;
2944 CCValid = SystemZ::CCMASK_ANY;
2945 return true;
2946
2947 case Intrinsic::s390_vfcedbs:
2948 case Intrinsic::s390_vfcesbs:
2949 Opcode = SystemZISD::VFCMPES;
2950 CCValid = SystemZ::CCMASK_VCMP;
2951 return true;
2952
2953 case Intrinsic::s390_vfchdbs:
2954 case Intrinsic::s390_vfchsbs:
2955 Opcode = SystemZISD::VFCMPHS;
2956 CCValid = SystemZ::CCMASK_VCMP;
2957 return true;
2958
2959 case Intrinsic::s390_vfchedbs:
2960 case Intrinsic::s390_vfchesbs:
2961 Opcode = SystemZISD::VFCMPHES;
2962 CCValid = SystemZ::CCMASK_VCMP;
2963 return true;
2964
2965 case Intrinsic::s390_vftcidb:
2966 case Intrinsic::s390_vftcisb:
2967 Opcode = SystemZISD::VFTCI;
2968 CCValid = SystemZ::CCMASK_VCMP;
2969 return true;
2970
2971 case Intrinsic::s390_tdc:
2972 Opcode = SystemZISD::TDC;
2973 CCValid = SystemZ::CCMASK_TDC;
2974 return true;
2975
2976 default:
2977 return false;
2978 }
2979}
2980
2981// Emit an intrinsic with chain and an explicit CC register result.
2983 unsigned Opcode) {
2984 // Copy all operands except the intrinsic ID.
2985 unsigned NumOps = Op.getNumOperands();
2987 Ops.reserve(NumOps - 1);
2988 Ops.push_back(Op.getOperand(0));
2989 for (unsigned I = 2; I < NumOps; ++I)
2990 Ops.push_back(Op.getOperand(I));
2991
2992 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2993 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2994 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2995 SDValue OldChain = SDValue(Op.getNode(), 1);
2996 SDValue NewChain = SDValue(Intr.getNode(), 1);
2997 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2998 return Intr.getNode();
2999}
3000
3001// Emit an intrinsic with an explicit CC register result.
3003 unsigned Opcode) {
3004 // Copy all operands except the intrinsic ID.
3005 SDLoc DL(Op);
3006 unsigned NumOps = Op.getNumOperands();
3008 Ops.reserve(NumOps - 1);
3009 for (unsigned I = 1; I < NumOps; ++I) {
3010 SDValue CurrOper = Op.getOperand(I);
3011 if (CurrOper.getValueType() == MVT::f16) {
3012 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
3013 "Unhandled intrinsic with f16 operand.");
3014 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
3015 }
3016 Ops.push_back(CurrOper);
3017 }
3018
3019 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
3020 return Intr.getNode();
3021}
3022
3023// CC is a comparison that will be implemented using an integer or
3024// floating-point comparison. Return the condition code mask for
3025// a branch on true. In the integer case, CCMASK_CMP_UO is set for
3026// unsigned comparisons and clear for signed ones. In the floating-point
3027// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
3029#define CONV(X) \
3030 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
3031 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
3032 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
3033
3034 switch (CC) {
3035 default:
3036 llvm_unreachable("Invalid integer condition!");
3037
3038 CONV(EQ);
3039 CONV(NE);
3040 CONV(GT);
3041 CONV(GE);
3042 CONV(LT);
3043 CONV(LE);
3044
3045 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
3047 }
3048#undef CONV
3049}
3050
3051// If C can be converted to a comparison against zero, adjust the operands
3052// as necessary.
3053static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3054 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3055 return;
3056
3057 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
3058 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3059 return;
3060
3061 int64_t Value = ConstOp1->getSExtValue();
3062 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
3063 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
3064 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
3065 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
3066 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3067 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
3068 }
3069}
3070
3071// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
3072// adjust the operands as necessary.
3073static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
3074 Comparison &C) {
3075 // For us to make any changes, it must a comparison between a single-use
3076 // load and a constant.
3077 if (!C.Op0.hasOneUse() ||
3078 C.Op0.getOpcode() != ISD::LOAD ||
3079 C.Op1.getOpcode() != ISD::Constant)
3080 return;
3081
3082 // We must have an 8- or 16-bit load.
3083 auto *Load = cast<LoadSDNode>(C.Op0);
3084 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
3085 if ((NumBits != 8 && NumBits != 16) ||
3086 NumBits != Load->getMemoryVT().getStoreSizeInBits())
3087 return;
3088
3089 // The load must be an extending one and the constant must be within the
3090 // range of the unextended value.
3091 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
3092 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3093 return;
3094 uint64_t Value = ConstOp1->getZExtValue();
3095 uint64_t Mask = (1 << NumBits) - 1;
3096 if (Load->getExtensionType() == ISD::SEXTLOAD) {
3097 // Make sure that ConstOp1 is in range of C.Op0.
3098 int64_t SignedValue = ConstOp1->getSExtValue();
3099 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
3100 return;
3101 if (C.ICmpType != SystemZICMP::SignedOnly) {
3102 // Unsigned comparison between two sign-extended values is equivalent
3103 // to unsigned comparison between two zero-extended values.
3104 Value &= Mask;
3105 } else if (NumBits == 8) {
3106 // Try to treat the comparison as unsigned, so that we can use CLI.
3107 // Adjust CCMask and Value as necessary.
3108 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
3109 // Test whether the high bit of the byte is set.
3110 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
3111 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
3112 // Test whether the high bit of the byte is clear.
3113 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
3114 else
3115 // No instruction exists for this combination.
3116 return;
3117 C.ICmpType = SystemZICMP::UnsignedOnly;
3118 }
3119 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
3120 if (Value > Mask)
3121 return;
3122 // If the constant is in range, we can use any comparison.
3123 C.ICmpType = SystemZICMP::Any;
3124 } else
3125 return;
3126
3127 // Make sure that the first operand is an i32 of the right extension type.
3128 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
3131 if (C.Op0.getValueType() != MVT::i32 ||
3132 Load->getExtensionType() != ExtType) {
3133 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
3134 Load->getBasePtr(), Load->getPointerInfo(),
3135 Load->getMemoryVT(), Load->getAlign(),
3136 Load->getMemOperand()->getFlags());
3137 // Update the chain uses.
3138 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3139 }
3140
3141 // Make sure that the second operand is an i32 with the right value.
3142 if (C.Op1.getValueType() != MVT::i32 ||
3143 Value != ConstOp1->getZExtValue())
3144 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3145}
3146
3147// Return true if Op is either an unextended load, or a load suitable
3148// for integer register-memory comparisons of type ICmpType.
3149static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3150 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3151 if (Load) {
3152 // There are no instructions to compare a register with a memory byte.
3153 if (Load->getMemoryVT() == MVT::i8)
3154 return false;
3155 // Otherwise decide on extension type.
3156 switch (Load->getExtensionType()) {
3157 case ISD::NON_EXTLOAD:
3158 return true;
3159 case ISD::SEXTLOAD:
3160 return ICmpType != SystemZICMP::UnsignedOnly;
3161 case ISD::ZEXTLOAD:
3162 return ICmpType != SystemZICMP::SignedOnly;
3163 default:
3164 break;
3165 }
3166 }
3167 return false;
3168}
3169
3170// Return true if it is better to swap the operands of C.
3171static bool shouldSwapCmpOperands(const Comparison &C) {
3172 // If one side of the compare is a load of the stackguard reference value,
3173 // then that load should be Op1.
3174 if (C.Op0.isMachineOpcode() &&
3175 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3176 return true;
3177
3178 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3179 if (C.Op0.getValueType() == MVT::i128)
3180 return false;
3181 if (C.Op0.getValueType() == MVT::f128)
3182 return false;
3183
3184 // Always keep a floating-point constant second, since comparisons with
3185 // zero can use LOAD TEST and comparisons with other constants make a
3186 // natural memory operand.
3187 if (isa<ConstantFPSDNode>(C.Op1))
3188 return false;
3189
3190 // Never swap comparisons with zero since there are many ways to optimize
3191 // those later.
3192 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3193 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3194 return false;
3195
3196 // Also keep natural memory operands second if the loaded value is
3197 // only used here. Several comparisons have memory forms.
3198 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3199 return false;
3200
3201 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3202 // In that case we generally prefer the memory to be second.
3203 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3204 // The only exceptions are when the second operand is a constant and
3205 // we can use things like CHHSI.
3206 if (!ConstOp1)
3207 return true;
3208 // The unsigned memory-immediate instructions can handle 16-bit
3209 // unsigned integers.
3210 if (C.ICmpType != SystemZICMP::SignedOnly &&
3211 isUInt<16>(ConstOp1->getZExtValue()))
3212 return false;
3213 // The signed memory-immediate instructions can handle 16-bit
3214 // signed integers.
3215 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3216 isInt<16>(ConstOp1->getSExtValue()))
3217 return false;
3218 return true;
3219 }
3220
3221 // Try to promote the use of CGFR and CLGFR.
3222 unsigned Opcode0 = C.Op0.getOpcode();
3223 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3224 return true;
3225 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3226 return true;
3227 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3228 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3229 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3230 return true;
3231
3232 return false;
3233}
3234
3235// Check whether C tests for equality between X and Y and whether X - Y
3236// or Y - X is also computed. In that case it's better to compare the
3237// result of the subtraction against zero.
3239 Comparison &C) {
3240 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3241 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3242 for (SDNode *N : C.Op0->users()) {
3243 if (N->getOpcode() == ISD::SUB &&
3244 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3245 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3246 // Disable the nsw and nuw flags: the backend needs to handle
3247 // overflow as well during comparison elimination.
3248 N->dropFlags(SDNodeFlags::NoWrap);
3249 C.Op0 = SDValue(N, 0);
3250 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3251 return;
3252 }
3253 }
3254 }
3255}
3256
3257// Check whether C compares a floating-point value with zero and if that
3258// floating-point value is also negated. In this case we can use the
3259// negation to set CC, so avoiding separate LOAD AND TEST and
3260// LOAD (NEGATIVE/COMPLEMENT) instructions.
3261static void adjustForFNeg(Comparison &C) {
3262 // This optimization is invalid for strict comparisons, since FNEG
3263 // does not raise any exceptions.
3264 if (C.Chain)
3265 return;
3266 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3267 if (C1 && C1->isZero()) {
3268 for (SDNode *N : C.Op0->users()) {
3269 if (N->getOpcode() == ISD::FNEG) {
3270 C.Op0 = SDValue(N, 0);
3271 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3272 return;
3273 }
3274 }
3275 }
3276}
3277
3278// Check whether C compares (shl X, 32) with 0 and whether X is
3279// also sign-extended. In that case it is better to test the result
3280// of the sign extension using LTGFR.
3281//
3282// This case is important because InstCombine transforms a comparison
3283// with (sext (trunc X)) into a comparison with (shl X, 32).
3284static void adjustForLTGFR(Comparison &C) {
3285 // Check for a comparison between (shl X, 32) and 0.
3286 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3287 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3288 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3289 if (C1 && C1->getZExtValue() == 32) {
3290 SDValue ShlOp0 = C.Op0.getOperand(0);
3291 // See whether X has any SIGN_EXTEND_INREG uses.
3292 for (SDNode *N : ShlOp0->users()) {
3293 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3294 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3295 C.Op0 = SDValue(N, 0);
3296 return;
3297 }
3298 }
3299 }
3300 }
3301}
3302
3303// If C compares the truncation of an extending load, try to compare
3304// the untruncated value instead. This exposes more opportunities to
3305// reuse CC.
3306static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3307 Comparison &C) {
3308 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3309 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3310 C.Op1.getOpcode() == ISD::Constant &&
3311 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3312 C.Op1->getAsZExtVal() == 0) {
3313 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3314 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3315 C.Op0.getValueSizeInBits().getFixedValue()) {
3316 unsigned Type = L->getExtensionType();
3317 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3318 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3319 C.Op0 = C.Op0.getOperand(0);
3320 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3321 }
3322 }
3323 }
3324}
3325
3326// Adjust if a given Compare is a check of the stack guard against a stack
3327// guard instance on the stack. Specifically, this checks if:
3328// - The operands are a load of the stack guard, and a load from a stack slot
3329// - The original opcode is ICMP
3330// - ICMPType is compatible with unsigned comparison.
3332 Comparison &C) {
3333
3334 // Opcode must be ICMP.
3335 if (C.Opcode != SystemZISD::ICMP)
3336 return;
3337 // ICmpType must be Unsigned or Any.
3338 if (C.ICmpType == SystemZICMP::SignedOnly)
3339 return;
3340 // Op0 must be FrameIndex Load.
3341 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3342 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3343 return;
3344 // Op1 must be LOAD_STACK_GUARD.
3345 if (!C.Op1.isMachineOpcode() ||
3346 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3347 return;
3348
3349 // At this point we are sure that this is a proper CMP_STACKGUARD
3350 // case, update the opcode to reflect this.
3351 C.Opcode = SystemZISD::CMP_STACKGUARD;
3352 C.Op1 = SDValue();
3353}
3354
3355// Return true if shift operation N has an in-range constant shift value.
3356// Store it in ShiftVal if so.
3357static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3358 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3359 if (!Shift)
3360 return false;
3361
3362 uint64_t Amount = Shift->getZExtValue();
3363 if (Amount >= N.getValueSizeInBits())
3364 return false;
3365
3366 ShiftVal = Amount;
3367 return true;
3368}
3369
3370// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3371// instruction and whether the CC value is descriptive enough to handle
3372// a comparison of type Opcode between the AND result and CmpVal.
3373// CCMask says which comparison result is being tested and BitSize is
3374// the number of bits in the operands. If TEST UNDER MASK can be used,
3375// return the corresponding CC mask, otherwise return 0.
3376static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3377 uint64_t Mask, uint64_t CmpVal,
3378 unsigned ICmpType) {
3379 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3380
3381 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3382 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3383 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3384 return 0;
3385
3386 // Work out the masks for the lowest and highest bits.
3388 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3389
3390 // Signed ordered comparisons are effectively unsigned if the sign
3391 // bit is dropped.
3392 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3393
3394 // Check for equality comparisons with 0, or the equivalent.
3395 if (CmpVal == 0) {
3396 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3398 if (CCMask == SystemZ::CCMASK_CMP_NE)
3400 }
3401 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3402 if (CCMask == SystemZ::CCMASK_CMP_LT)
3404 if (CCMask == SystemZ::CCMASK_CMP_GE)
3406 }
3407 if (EffectivelyUnsigned && CmpVal < Low) {
3408 if (CCMask == SystemZ::CCMASK_CMP_LE)
3410 if (CCMask == SystemZ::CCMASK_CMP_GT)
3412 }
3413
3414 // Check for equality comparisons with the mask, or the equivalent.
3415 if (CmpVal == Mask) {
3416 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3418 if (CCMask == SystemZ::CCMASK_CMP_NE)
3420 }
3421 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3422 if (CCMask == SystemZ::CCMASK_CMP_GT)
3424 if (CCMask == SystemZ::CCMASK_CMP_LE)
3426 }
3427 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3428 if (CCMask == SystemZ::CCMASK_CMP_GE)
3430 if (CCMask == SystemZ::CCMASK_CMP_LT)
3432 }
3433
3434 // Check for ordered comparisons with the top bit.
3435 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3436 if (CCMask == SystemZ::CCMASK_CMP_LE)
3438 if (CCMask == SystemZ::CCMASK_CMP_GT)
3440 }
3441 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3442 if (CCMask == SystemZ::CCMASK_CMP_LT)
3444 if (CCMask == SystemZ::CCMASK_CMP_GE)
3446 }
3447
3448 // If there are just two bits, we can do equality checks for Low and High
3449 // as well.
3450 if (Mask == Low + High) {
3451 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3453 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3455 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3457 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3459 }
3460
3461 // Looks like we've exhausted our options.
3462 return 0;
3463}
3464
3465// See whether C can be implemented as a TEST UNDER MASK instruction.
3466// Update the arguments with the TM version if so.
3468 Comparison &C) {
3469 // Use VECTOR TEST UNDER MASK for i128 operations.
3470 if (C.Op0.getValueType() == MVT::i128) {
3471 // We can use VTM for EQ/NE comparisons of x & y against 0.
3472 if (C.Op0.getOpcode() == ISD::AND &&
3473 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3474 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3475 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3476 if (Mask && Mask->getAPIntValue() == 0) {
3477 C.Opcode = SystemZISD::VTM;
3478 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3479 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3480 C.CCValid = SystemZ::CCMASK_VCMP;
3481 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3482 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3483 else
3484 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3485 }
3486 }
3487 return;
3488 }
3489
3490 // Check that we have a comparison with a constant.
3491 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3492 if (!ConstOp1)
3493 return;
3494 uint64_t CmpVal = ConstOp1->getZExtValue();
3495
3496 // Check whether the nonconstant input is an AND with a constant mask.
3497 Comparison NewC(C);
3498 uint64_t MaskVal;
3499 ConstantSDNode *Mask = nullptr;
3500 if (C.Op0.getOpcode() == ISD::AND) {
3501 NewC.Op0 = C.Op0.getOperand(0);
3502 NewC.Op1 = C.Op0.getOperand(1);
3503 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3504 if (!Mask)
3505 return;
3506 MaskVal = Mask->getZExtValue();
3507 } else {
3508 // There is no instruction to compare with a 64-bit immediate
3509 // so use TMHH instead if possible. We need an unsigned ordered
3510 // comparison with an i64 immediate.
3511 if (NewC.Op0.getValueType() != MVT::i64 ||
3512 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3513 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3514 NewC.ICmpType == SystemZICMP::SignedOnly)
3515 return;
3516 // Convert LE and GT comparisons into LT and GE.
3517 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3518 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3519 if (CmpVal == uint64_t(-1))
3520 return;
3521 CmpVal += 1;
3522 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3523 }
3524 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3525 // be masked off without changing the result.
3526 MaskVal = -(CmpVal & -CmpVal);
3527 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3528 }
3529 if (!MaskVal)
3530 return;
3531
3532 // Check whether the combination of mask, comparison value and comparison
3533 // type are suitable.
3534 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3535 unsigned NewCCMask, ShiftVal;
3536 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3537 NewC.Op0.getOpcode() == ISD::SHL &&
3538 isSimpleShift(NewC.Op0, ShiftVal) &&
3539 (MaskVal >> ShiftVal != 0) &&
3540 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3541 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3542 MaskVal >> ShiftVal,
3543 CmpVal >> ShiftVal,
3544 SystemZICMP::Any))) {
3545 NewC.Op0 = NewC.Op0.getOperand(0);
3546 MaskVal >>= ShiftVal;
3547 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3548 NewC.Op0.getOpcode() == ISD::SRL &&
3549 isSimpleShift(NewC.Op0, ShiftVal) &&
3550 (MaskVal << ShiftVal != 0) &&
3551 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3552 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3553 MaskVal << ShiftVal,
3554 CmpVal << ShiftVal,
3556 NewC.Op0 = NewC.Op0.getOperand(0);
3557 MaskVal <<= ShiftVal;
3558 } else {
3559 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3560 NewC.ICmpType);
3561 if (!NewCCMask)
3562 return;
3563 }
3564
3565 // Go ahead and make the change.
3566 C.Opcode = SystemZISD::TM;
3567 C.Op0 = NewC.Op0;
3568 if (Mask && Mask->getZExtValue() == MaskVal)
3569 C.Op1 = SDValue(Mask, 0);
3570 else
3571 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3572 C.CCValid = SystemZ::CCMASK_TM;
3573 C.CCMask = NewCCMask;
3574}
3575
3576// Implement i128 comparison in vector registers.
3577static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3578 Comparison &C) {
3579 if (C.Opcode != SystemZISD::ICMP)
3580 return;
3581 if (C.Op0.getValueType() != MVT::i128)
3582 return;
3583
3584 // Recognize vector comparison reductions.
3585 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3586 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3587 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3588 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3589 bool CmpNull = isNullConstant(C.Op1);
3590 SDValue Src = peekThroughBitcasts(C.Op0);
3591 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3592 Src = Src.getOperand(0);
3593 CmpNull = !CmpNull;
3594 }
3595 unsigned Opcode = 0;
3596 if (Src.hasOneUse()) {
3597 switch (Src.getOpcode()) {
3598 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3599 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3600 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3601 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3602 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3603 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3604 default: break;
3605 }
3606 }
3607 if (Opcode) {
3608 C.Opcode = Opcode;
3609 C.Op0 = Src->getOperand(0);
3610 C.Op1 = Src->getOperand(1);
3611 C.CCValid = SystemZ::CCMASK_VCMP;
3613 if (!CmpEq)
3614 C.CCMask ^= C.CCValid;
3615 return;
3616 }
3617 }
3618
3619 // Everything below here is not useful if we have native i128 compares.
3620 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3621 return;
3622
3623 // (In-)Equality comparisons can be implemented via VCEQGS.
3624 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3625 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3626 C.Opcode = SystemZISD::VICMPES;
3627 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3628 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3629 C.CCValid = SystemZ::CCMASK_VCMP;
3630 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3631 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3632 else
3633 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3634 return;
3635 }
3636
3637 // Normalize other comparisons to GT.
3638 bool Swap = false, Invert = false;
3639 switch (C.CCMask) {
3640 case SystemZ::CCMASK_CMP_GT: break;
3641 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3642 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3643 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3644 default: llvm_unreachable("Invalid integer condition!");
3645 }
3646 if (Swap)
3647 std::swap(C.Op0, C.Op1);
3648
3649 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3650 C.Opcode = SystemZISD::UCMP128HI;
3651 else
3652 C.Opcode = SystemZISD::SCMP128HI;
3653 C.CCValid = SystemZ::CCMASK_ANY;
3654 C.CCMask = SystemZ::CCMASK_1;
3655
3656 if (Invert)
3657 C.CCMask ^= C.CCValid;
3658}
3659
3660// See whether the comparison argument contains a redundant AND
3661// and remove it if so. This sometimes happens due to the generic
3662// BRCOND expansion.
3664 Comparison &C) {
3665 if (C.Op0.getOpcode() != ISD::AND)
3666 return;
3667 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3668 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3669 return;
3670 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3671 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3672 return;
3673
3674 C.Op0 = C.Op0.getOperand(0);
3675}
3676
3677// Return a Comparison that tests the condition-code result of intrinsic
3678// node Call against constant integer CC using comparison code Cond.
3679// Opcode is the opcode of the SystemZISD operation for the intrinsic
3680// and CCValid is the set of possible condition-code results.
3681static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3682 SDValue Call, unsigned CCValid, uint64_t CC,
3684 Comparison C(Call, SDValue(), SDValue());
3685 C.Opcode = Opcode;
3686 C.CCValid = CCValid;
3687 if (Cond == ISD::SETEQ)
3688 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3689 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3690 else if (Cond == ISD::SETNE)
3691 // ...and the inverse of that.
3692 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3693 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3694 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3695 // always true for CC>3.
3696 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3697 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3698 // ...and the inverse of that.
3699 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3700 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3701 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3702 // always true for CC>3.
3703 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3704 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3705 // ...and the inverse of that.
3706 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3707 else
3708 llvm_unreachable("Unexpected integer comparison type");
3709 C.CCMask &= CCValid;
3710 return C;
3711}
3712
3713// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3714static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3715 ISD::CondCode Cond, const SDLoc &DL,
3716 SDValue Chain = SDValue(),
3717 bool IsSignaling = false) {
3718 if (CmpOp1.getOpcode() == ISD::Constant) {
3719 assert(!Chain);
3720 unsigned Opcode, CCValid;
3721 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3722 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3723 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3724 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3725 CmpOp1->getAsZExtVal(), Cond);
3726 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3727 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3728 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3729 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3730 CmpOp1->getAsZExtVal(), Cond);
3731 }
3732 Comparison C(CmpOp0, CmpOp1, Chain);
3733 C.CCMask = CCMaskForCondCode(Cond);
3734 if (C.Op0.getValueType().isFloatingPoint()) {
3735 C.CCValid = SystemZ::CCMASK_FCMP;
3736 if (!C.Chain)
3737 C.Opcode = SystemZISD::FCMP;
3738 else if (!IsSignaling)
3739 C.Opcode = SystemZISD::STRICT_FCMP;
3740 else
3741 C.Opcode = SystemZISD::STRICT_FCMPS;
3743 } else {
3744 assert(!C.Chain);
3745 C.CCValid = SystemZ::CCMASK_ICMP;
3746 C.Opcode = SystemZISD::ICMP;
3747 // Choose the type of comparison. Equality and inequality tests can
3748 // use either signed or unsigned comparisons. The choice also doesn't
3749 // matter if both sign bits are known to be clear. In those cases we
3750 // want to give the main isel code the freedom to choose whichever
3751 // form fits best.
3752 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3753 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3754 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3755 C.ICmpType = SystemZICMP::Any;
3756 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3757 C.ICmpType = SystemZICMP::UnsignedOnly;
3758 else
3759 C.ICmpType = SystemZICMP::SignedOnly;
3760 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3761 adjustForRedundantAnd(DAG, DL, C);
3762 adjustZeroCmp(DAG, DL, C);
3763 adjustSubwordCmp(DAG, DL, C);
3764 adjustForSubtraction(DAG, DL, C);
3766 adjustICmpTruncate(DAG, DL, C);
3767 }
3768
3769 if (shouldSwapCmpOperands(C)) {
3770 std::swap(C.Op0, C.Op1);
3771 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3772 }
3773
3775 adjustICmp128(DAG, DL, C);
3777 return C;
3778}
3779
3780// Emit the comparison instruction described by C.
3781static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3782 if (!C.Op1.getNode()) {
3783 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3784 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3785 SDNode *Node;
3786 switch (C.Op0.getOpcode()) {
3788 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3789 return SDValue(Node, 0);
3791 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3792 return SDValue(Node, Node->getNumValues() - 1);
3793 default:
3794 llvm_unreachable("Invalid comparison operands");
3795 }
3796 }
3797 if (C.Opcode == SystemZISD::ICMP)
3798 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3799 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3800 if (C.Opcode == SystemZISD::TM) {
3801 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3803 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3804 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3805 }
3806 if (C.Opcode == SystemZISD::VICMPES ||
3807 C.Opcode == SystemZISD::VICMPHS ||
3808 C.Opcode == SystemZISD::VICMPHLS ||
3809 C.Opcode == SystemZISD::VFCMPES ||
3810 C.Opcode == SystemZISD::VFCMPHS ||
3811 C.Opcode == SystemZISD::VFCMPHES) {
3812 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3813 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3814 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3815 return SDValue(Val.getNode(), 1);
3816 }
3817 if (C.Chain) {
3818 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3819 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3820 }
3821 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3822}
3823
3824// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3825// 64 bits. Extend is the extension type to use. Store the high part
3826// in Hi and the low part in Lo.
3827static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3828 SDValue Op0, SDValue Op1, SDValue &Hi,
3829 SDValue &Lo) {
3830 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3831 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3832 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3833 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3834 DAG.getConstant(32, DL, MVT::i64));
3835 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3836 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3837}
3838
3839// Lower a binary operation that produces two VT results, one in each
3840// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3841// and Opcode performs the GR128 operation. Store the even register result
3842// in Even and the odd register result in Odd.
3843static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3844 unsigned Opcode, SDValue Op0, SDValue Op1,
3845 SDValue &Even, SDValue &Odd) {
3846 SDValue Result = DAG.getNode(Opcode, DL, MVT::v2i64, Op0, Op1);
3847 bool Is32Bit = is32Bit(VT);
3848 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3849 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3850}
3851
3852// Return an i32 value that is 1 if the CC value produced by CCReg is
3853// in the mask CCMask and 0 otherwise. CC is known to have a value
3854// in CCValid, so other values can be ignored.
3855static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3856 unsigned CCValid, unsigned CCMask) {
3857 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3858 DAG.getConstant(0, DL, MVT::i32),
3859 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3860 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3861 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3862}
3863
3864// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3865// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3866// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3867// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3868// floating-point comparisons.
3871 switch (CC) {
3872 case ISD::SETOEQ:
3873 case ISD::SETEQ:
3874 switch (Mode) {
3875 case CmpMode::Int: return SystemZISD::VICMPE;
3876 case CmpMode::FP: return SystemZISD::VFCMPE;
3877 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3878 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3879 }
3880 llvm_unreachable("Bad mode");
3881
3882 case ISD::SETOGE:
3883 case ISD::SETGE:
3884 switch (Mode) {
3885 case CmpMode::Int: return 0;
3886 case CmpMode::FP: return SystemZISD::VFCMPHE;
3887 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3888 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3889 }
3890 llvm_unreachable("Bad mode");
3891
3892 case ISD::SETOGT:
3893 case ISD::SETGT:
3894 switch (Mode) {
3895 case CmpMode::Int: return SystemZISD::VICMPH;
3896 case CmpMode::FP: return SystemZISD::VFCMPH;
3897 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3898 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3899 }
3900 llvm_unreachable("Bad mode");
3901
3902 case ISD::SETUGT:
3903 switch (Mode) {
3904 case CmpMode::Int: return SystemZISD::VICMPHL;
3905 case CmpMode::FP: return 0;
3906 case CmpMode::StrictFP: return 0;
3907 case CmpMode::SignalingFP: return 0;
3908 }
3909 llvm_unreachable("Bad mode");
3910
3911 default:
3912 return 0;
3913 }
3914}
3915
3916// Return the SystemZISD vector comparison operation for CC or its inverse,
3917// or 0 if neither can be done directly. Indicate in Invert whether the
3918// result is for the inverse of CC. Mode is as above.
3920 bool &Invert) {
3921 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3922 Invert = false;
3923 return Opcode;
3924 }
3925
3926 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3927 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3928 Invert = true;
3929 return Opcode;
3930 }
3931
3932 return 0;
3933}
3934
3935// Return a v2f64 that contains the extended form of elements Start and Start+1
3936// of v4f32 value Op. If Chain is nonnull, return the strict form.
3937static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3938 SDValue Op, SDValue Chain) {
3939 int Mask[] = { Start, -1, Start + 1, -1 };
3940 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3941 if (Chain) {
3942 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3943 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3944 }
3945 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3946}
3947
3948// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3949// producing a result of type VT. If Chain is nonnull, return the strict form.
3950SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3951 const SDLoc &DL, EVT VT,
3952 SDValue CmpOp0,
3953 SDValue CmpOp1,
3954 SDValue Chain) const {
3955 // There is no hardware support for v4f32 (unless we have the vector
3956 // enhancements facility 1), so extend the vector into two v2f64s
3957 // and compare those.
3958 if (CmpOp0.getValueType() == MVT::v4f32 &&
3959 !Subtarget.hasVectorEnhancements1()) {
3960 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3961 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3962 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3963 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3964 if (Chain) {
3965 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3966 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3967 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3968 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3969 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3970 H1.getValue(1), L1.getValue(1),
3971 HRes.getValue(1), LRes.getValue(1) };
3972 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3973 SDValue Ops[2] = { Res, NewChain };
3974 return DAG.getMergeValues(Ops, DL);
3975 }
3976 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3977 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3978 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3979 }
3980 if (Chain) {
3981 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3982 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3983 }
3984 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3985}
3986
3987// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3988// an integer mask of type VT. If Chain is nonnull, we have a strict
3989// floating-point comparison. If in addition IsSignaling is true, we have
3990// a strict signaling floating-point comparison.
3991SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3992 const SDLoc &DL, EVT VT,
3994 SDValue CmpOp0,
3995 SDValue CmpOp1,
3996 SDValue Chain,
3997 bool IsSignaling) const {
3998 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3999 assert (!Chain || IsFP);
4000 assert (!IsSignaling || Chain);
4001 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
4002 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
4003 bool Invert = false;
4004 SDValue Cmp;
4005 switch (CC) {
4006 // Handle tests for order using (or (ogt y x) (oge x y)).
4007 case ISD::SETUO:
4008 Invert = true;
4009 [[fallthrough]];
4010 case ISD::SETO: {
4011 assert(IsFP && "Unexpected integer comparison");
4012 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
4013 DL, VT, CmpOp1, CmpOp0, Chain);
4014 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
4015 DL, VT, CmpOp0, CmpOp1, Chain);
4016 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
4017 if (Chain)
4018 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4019 LT.getValue(1), GE.getValue(1));
4020 break;
4021 }
4022
4023 // Handle <> tests using (or (ogt y x) (ogt x y)).
4024 case ISD::SETUEQ:
4025 Invert = true;
4026 [[fallthrough]];
4027 case ISD::SETONE: {
4028 assert(IsFP && "Unexpected integer comparison");
4029 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
4030 DL, VT, CmpOp1, CmpOp0, Chain);
4031 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
4032 DL, VT, CmpOp0, CmpOp1, Chain);
4033 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
4034 if (Chain)
4035 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4036 LT.getValue(1), GT.getValue(1));
4037 break;
4038 }
4039
4040 // Otherwise a single comparison is enough. It doesn't really
4041 // matter whether we try the inversion or the swap first, since
4042 // there are no cases where both work.
4043 default:
4044 // Optimize sign-bit comparisons to signed compares.
4045 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
4047 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4048 APInt Mask;
4049 if (CmpOp0.getOpcode() == ISD::AND &&
4050 ISD::isConstantSplatVector(CmpOp0.getOperand(1), Mask) &&
4051 Mask == APInt::getSignMask(EltSize)) {
4053 CmpOp0 = CmpOp0.getOperand(0);
4054 }
4055 }
4056 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4057 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
4058 else {
4060 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4061 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
4062 else
4063 llvm_unreachable("Unhandled comparison");
4064 }
4065 if (Chain)
4066 Chain = Cmp.getValue(1);
4067 break;
4068 }
4069 if (Invert) {
4070 SDValue Mask =
4071 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
4072 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
4073 }
4074 if (Chain && Chain.getNode() != Cmp.getNode()) {
4075 SDValue Ops[2] = { Cmp, Chain };
4076 Cmp = DAG.getMergeValues(Ops, DL);
4077 }
4078 return Cmp;
4079}
4080
4081SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
4082 SelectionDAG &DAG) const {
4083 SDValue CmpOp0 = Op.getOperand(0);
4084 SDValue CmpOp1 = Op.getOperand(1);
4085 ISD::CondCode CC = Op.getOperandCondCode(2);
4086 SDLoc DL(Op);
4087 EVT VT = Op.getValueType();
4088 if (VT.isVector())
4089 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
4090
4091 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4092 SDValue CCReg = emitCmp(DAG, DL, C);
4093 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4094}
4095
4096SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
4097 SelectionDAG &DAG,
4098 bool IsSignaling) const {
4099 SDValue Chain = Op.getOperand(0);
4100 SDValue CmpOp0 = Op.getOperand(1);
4101 SDValue CmpOp1 = Op.getOperand(2);
4102 ISD::CondCode CC = Op.getOperandCondCode(3);
4103 SDLoc DL(Op);
4104 EVT VT = Op.getNode()->getValueType(0);
4105 if (VT.isVector()) {
4106 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
4107 Chain, IsSignaling);
4108 return Res.getValue(Op.getResNo());
4109 }
4110
4111 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
4112 SDValue CCReg = emitCmp(DAG, DL, C);
4113 CCReg->setFlags(Op->getFlags());
4114 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4115 SDValue Ops[2] = { Result, CCReg.getValue(1) };
4116 return DAG.getMergeValues(Ops, DL);
4117}
4118
4119SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4120 ISD::CondCode CC = Op.getOperandCondCode(1);
4121 SDValue CmpOp0 = Op.getOperand(2);
4122 SDValue CmpOp1 = Op.getOperand(3);
4123 SDValue Dest = Op.getOperand(4);
4124 SDLoc DL(Op);
4125
4126 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4127 SDValue CCReg = emitCmp(DAG, DL, C);
4128 return DAG.getNode(
4129 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
4130 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4131 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
4132}
4133
4134// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
4135// allowing Pos and Neg to be wider than CmpOp.
4136static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4137 return (Neg.getOpcode() == ISD::SUB &&
4138 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4139 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4140 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4141 Pos.getOperand(0) == CmpOp)));
4142}
4143
4144// Return the absolute or negative absolute of Op; IsNegative decides which.
4146 bool IsNegative) {
4147 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4148 if (IsNegative)
4149 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4150 DAG.getConstant(0, DL, Op.getValueType()), Op);
4151 return Op;
4152}
4153
4155 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4156 EVT VT = MVT::i128;
4157 unsigned Op;
4158
4159 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4160 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4161 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4162 std::swap(TrueOp, FalseOp);
4163 C.CCMask ^= C.CCValid;
4164 }
4165 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4166 std::swap(C.Op0, C.Op1);
4167 C.CCMask = SystemZ::CCMASK_CMP_GT;
4168 }
4169 switch (C.CCMask) {
4171 Op = SystemZISD::VICMPE;
4172 break;
4174 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4175 Op = SystemZISD::VICMPHL;
4176 else
4177 Op = SystemZISD::VICMPH;
4178 break;
4179 default:
4180 llvm_unreachable("Unhandled comparison");
4181 break;
4182 }
4183
4184 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4185 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4186 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4187 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4188}
4189
4190SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4191 SelectionDAG &DAG) const {
4192 SDValue CmpOp0 = Op.getOperand(0);
4193 SDValue CmpOp1 = Op.getOperand(1);
4194 SDValue TrueOp = Op.getOperand(2);
4195 SDValue FalseOp = Op.getOperand(3);
4196 ISD::CondCode CC = Op.getOperandCondCode(4);
4197 SDLoc DL(Op);
4198
4199 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4200 // legalizer, as it will be handled according to the type of the resulting
4201 // value. Extend them here if needed.
4202 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4203 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4204 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4205 }
4206
4207 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4208
4209 // Check for absolute and negative-absolute selections, including those
4210 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4211 // This check supplements the one in DAGCombiner.
4212 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4213 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4214 C.Op1.getOpcode() == ISD::Constant &&
4215 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4216 C.Op1->getAsZExtVal() == 0) {
4217 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4218 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4219 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4220 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4221 }
4222
4223 if (Subtarget.hasVectorEnhancements3() &&
4224 C.Opcode == SystemZISD::ICMP &&
4225 C.Op0.getValueType() == MVT::i128 &&
4226 TrueOp.getValueType() == MVT::i128) {
4227 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4228 }
4229
4230 SDValue CCReg = emitCmp(DAG, DL, C);
4231 SDValue Ops[] = {TrueOp, FalseOp,
4232 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4233 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4234
4235 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4236}
4237
4238SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4239 SelectionDAG &DAG) const {
4240 SDLoc DL(Node);
4241 const GlobalValue *GV = Node->getGlobal();
4242 int64_t Offset = Node->getOffset();
4243 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4245
4247 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4248 if (isInt<32>(Offset)) {
4249 // Assign anchors at 1<<12 byte boundaries.
4250 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4251 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4252 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4253
4254 // The offset can be folded into the address if it is aligned to a
4255 // halfword.
4256 Offset -= Anchor;
4257 if (Offset != 0 && (Offset & 1) == 0) {
4258 SDValue Full =
4259 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4260 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4261 Offset = 0;
4262 }
4263 } else {
4264 // Conservatively load a constant offset greater than 32 bits into a
4265 // register below.
4266 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4267 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4268 }
4269 } else if (Subtarget.isTargetELF()) {
4270 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4271 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4272 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4274 } else if (Subtarget.isTargetzOS()) {
4275 Result = getADAEntry(DAG, GV, DL, PtrVT);
4276 } else
4277 llvm_unreachable("Unexpected Subtarget");
4278
4279 // If there was a non-zero offset that we didn't fold, create an explicit
4280 // addition for it.
4281 if (Offset != 0)
4282 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4283 DAG.getSignedConstant(Offset, DL, PtrVT));
4284
4285 return Result;
4286}
4287
4288SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4289 SelectionDAG &DAG,
4290 unsigned Opcode,
4291 SDValue GOTOffset) const {
4292 SDLoc DL(Node);
4293 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4294 SDValue Chain = DAG.getEntryNode();
4295 SDValue Glue;
4296
4299 report_fatal_error("In GHC calling convention TLS is not supported");
4300
4301 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4302 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4303 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4304 Glue = Chain.getValue(1);
4305 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4306 Glue = Chain.getValue(1);
4307
4308 // The first call operand is the chain and the second is the TLS symbol.
4310 Ops.push_back(Chain);
4311 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4312 Node->getValueType(0),
4313 0, 0));
4314
4315 // Add argument registers to the end of the list so that they are
4316 // known live into the call.
4317 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4318 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4319
4320 // Add a register mask operand representing the call-preserved registers.
4321 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4322 const uint32_t *Mask =
4323 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4324 assert(Mask && "Missing call preserved mask for calling convention");
4325 Ops.push_back(DAG.getRegisterMask(Mask));
4326
4327 // Glue the call to the argument copies.
4328 Ops.push_back(Glue);
4329
4330 // Emit the call.
4331 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4332 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4333 Glue = Chain.getValue(1);
4334
4335 // Copy the return value from %r2.
4336 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4337}
4338
4339SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4340 SelectionDAG &DAG) const {
4341 SDValue Chain = DAG.getEntryNode();
4342 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4343
4344 // The high part of the thread pointer is in access register 0.
4345 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4346 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4347
4348 // The low part of the thread pointer is in access register 1.
4349 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4350 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4351
4352 // Merge them into a single 64-bit address.
4353 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4354 DAG.getConstant(32, DL, PtrVT));
4355 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4356}
4357
4358SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4359 SelectionDAG &DAG) const {
4360 if (DAG.getTarget().useEmulatedTLS())
4361 return LowerToTLSEmulatedModel(Node, DAG);
4362 SDLoc DL(Node);
4363 const GlobalValue *GV = Node->getGlobal();
4364 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4365 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4366
4369 report_fatal_error("In GHC calling convention TLS is not supported");
4370
4371 SDValue TP = lowerThreadPointer(DL, DAG);
4372
4373 // Get the offset of GA from the thread pointer, based on the TLS model.
4375 switch (model) {
4377 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4378 SystemZConstantPoolValue *CPV =
4380
4381 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4382 Offset = DAG.getLoad(
4383 PtrVT, DL, DAG.getEntryNode(), Offset,
4385
4386 // Call __tls_get_offset to retrieve the offset.
4387 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4388 break;
4389 }
4390
4392 // Load the GOT offset of the module ID.
4393 SystemZConstantPoolValue *CPV =
4395
4396 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4397 Offset = DAG.getLoad(
4398 PtrVT, DL, DAG.getEntryNode(), Offset,
4400
4401 // Call __tls_get_offset to retrieve the module base offset.
4402 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4403
4404 // Note: The SystemZLDCleanupPass will remove redundant computations
4405 // of the module base offset. Count total number of local-dynamic
4406 // accesses to trigger execution of that pass.
4407 SystemZMachineFunctionInfo* MFI =
4408 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4410
4411 // Add the per-symbol offset.
4413
4414 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4415 DTPOffset = DAG.getLoad(
4416 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4418
4419 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4420 break;
4421 }
4422
4423 case TLSModel::InitialExec: {
4424 // Load the offset from the GOT.
4425 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4427 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4428 Offset =
4429 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4431 break;
4432 }
4433
4434 case TLSModel::LocalExec: {
4435 // Force the offset into the constant pool and load it from there.
4436 SystemZConstantPoolValue *CPV =
4438
4439 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4440 Offset = DAG.getLoad(
4441 PtrVT, DL, DAG.getEntryNode(), Offset,
4443 break;
4444 }
4445 }
4446
4447 // Add the base and offset together.
4448 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4449}
4450
4451SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4452 SelectionDAG &DAG) const {
4453 SDLoc DL(Node);
4454 const BlockAddress *BA = Node->getBlockAddress();
4455 int64_t Offset = Node->getOffset();
4456 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4457
4458 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4459 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4460 return Result;
4461}
4462
4463SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4464 SelectionDAG &DAG) const {
4465 SDLoc DL(JT);
4466 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4467 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4468
4469 // Use LARL to load the address of the table.
4470 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4471}
4472
4473SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4474 SelectionDAG &DAG) const {
4475 SDLoc DL(CP);
4476 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4477
4480 Result =
4481 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4482 else
4483 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4484 CP->getOffset());
4485
4486 // Use LARL to load the address of the constant pool entry.
4487 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4488}
4489
4490SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4491 SelectionDAG &DAG) const {
4492 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4494 MachineFrameInfo &MFI = MF.getFrameInfo();
4495 MFI.setFrameAddressIsTaken(true);
4496
4497 SDLoc DL(Op);
4498 unsigned Depth = Op.getConstantOperandVal(0);
4499 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4500
4501 // By definition, the frame address is the address of the back chain. (In
4502 // the case of packed stack without backchain, return the address where the
4503 // backchain would have been stored. This will either be an unused space or
4504 // contain a saved register).
4505 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4506 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4507
4508 if (Depth > 0) {
4509 // FIXME The frontend should detect this case.
4510 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4511 report_fatal_error("Unsupported stack frame traversal count");
4512
4513 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4514 while (Depth--) {
4515 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4516 MachinePointerInfo());
4517 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4518 }
4519 }
4520
4521 return BackChain;
4522}
4523
4524SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4525 SelectionDAG &DAG) const {
4527 MachineFrameInfo &MFI = MF.getFrameInfo();
4528 MFI.setReturnAddressIsTaken(true);
4529
4530 SDLoc DL(Op);
4531 unsigned Depth = Op.getConstantOperandVal(0);
4532 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4533
4534 if (Depth > 0) {
4535 // FIXME The frontend should detect this case.
4536 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4537 report_fatal_error("Unsupported stack frame traversal count");
4538
4539 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4540 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4541 int Offset = TFL->getReturnAddressOffset(MF);
4542 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4543 DAG.getSignedConstant(Offset, DL, PtrVT));
4544 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4545 MachinePointerInfo());
4546 }
4547
4548 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4549 // implicit live-in.
4550 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4552 &SystemZ::GR64BitRegClass);
4553 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4554}
4555
4556SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4557 SelectionDAG &DAG) const {
4558 SDLoc DL(Op);
4559 SDValue In = Op.getOperand(0);
4560 EVT InVT = In.getValueType();
4561 EVT ResVT = Op.getValueType();
4562
4563 // Convert loads directly. This is normally done by DAGCombiner,
4564 // but we need this case for bitcasts that are created during lowering
4565 // and which are then lowered themselves.
4566 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4567 if (ISD::isNormalLoad(LoadN)) {
4568 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4569 LoadN->getBasePtr(), LoadN->getMemOperand());
4570 // Update the chain uses.
4571 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4572 return NewLoad;
4573 }
4574
4575 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4576 SDValue In64;
4577 if (Subtarget.hasHighWord()) {
4578 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4579 MVT::i64);
4580 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4581 MVT::i64, SDValue(U64, 0), In);
4582 } else {
4583 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4584 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4585 DAG.getConstant(32, DL, MVT::i64));
4586 }
4587 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4588 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4589 DL, MVT::f32, Out64);
4590 }
4591 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4592 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4593 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4594 MVT::f64, SDValue(U64, 0), In);
4595 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4596 if (Subtarget.hasHighWord())
4597 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4598 MVT::i32, Out64);
4599 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4600 DAG.getConstant(32, DL, MVT::i64));
4601 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4602 }
4603 llvm_unreachable("Unexpected bitcast combination");
4604}
4605
4606SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4607 SelectionDAG &DAG) const {
4608
4609 if (Subtarget.isTargetXPLINK64())
4610 return lowerVASTART_XPLINK(Op, DAG);
4611 else
4612 return lowerVASTART_ELF(Op, DAG);
4613}
4614
4615SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4616 SelectionDAG &DAG) const {
4618 SystemZMachineFunctionInfo *FuncInfo =
4619 MF.getInfo<SystemZMachineFunctionInfo>();
4620
4621 SDLoc DL(Op);
4622
4623 // vastart just stores the address of the VarArgsFrameIndex slot into the
4624 // memory location argument.
4625 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4626 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4627 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4628 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4629 MachinePointerInfo(SV));
4630}
4631
4632SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4633 SelectionDAG &DAG) const {
4635 SystemZMachineFunctionInfo *FuncInfo =
4636 MF.getInfo<SystemZMachineFunctionInfo>();
4637 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4638
4639 SDValue Chain = Op.getOperand(0);
4640 SDValue Addr = Op.getOperand(1);
4641 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4642 SDLoc DL(Op);
4643
4644 // The initial values of each field.
4645 const unsigned NumFields = 4;
4646 SDValue Fields[NumFields] = {
4647 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4648 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4649 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4650 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4651 };
4652
4653 // Store each field into its respective slot.
4654 SDValue MemOps[NumFields];
4655 unsigned Offset = 0;
4656 for (unsigned I = 0; I < NumFields; ++I) {
4657 SDValue FieldAddr = Addr;
4658 if (Offset != 0)
4659 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4661 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4662 MachinePointerInfo(SV, Offset));
4663 Offset += 8;
4664 }
4665 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4666}
4667
4668SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4669 SelectionDAG &DAG) const {
4670 SDValue Chain = Op.getOperand(0);
4671 SDValue DstPtr = Op.getOperand(1);
4672 SDValue SrcPtr = Op.getOperand(2);
4673 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4674 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4675 SDLoc DL(Op);
4676
4677 uint32_t Sz =
4678 Subtarget.isTargetXPLINK64() ? DAG.getDataLayout().getPointerSize(0) : 32;
4679 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4680 Align(8), Align(8), /*isVolatile*/ false,
4681 /*AlwaysInline*/ false,
4682 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4683 MachinePointerInfo(SrcSV));
4684}
4685
4686SDValue
4687SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4688 SelectionDAG &DAG) const {
4689 if (Subtarget.isTargetXPLINK64())
4690 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4691 else
4692 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4693}
4694
4695SDValue
4696SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4697 SelectionDAG &DAG) const {
4698 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4700 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4701 SDValue Chain = Op.getOperand(0);
4702 SDValue Size = Op.getOperand(1);
4703 SDValue Align = Op.getOperand(2);
4704 SDLoc DL(Op);
4705
4706 // If user has set the no alignment function attribute, ignore
4707 // alloca alignments.
4708 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4709
4710 uint64_t StackAlign = TFI->getStackAlignment();
4711 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4712 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4713
4714 SDValue NeededSpace = Size;
4715
4716 // Add extra space for alignment if needed.
4717 EVT PtrVT = getPointerTy(MF.getDataLayout());
4718 if (ExtraAlignSpace)
4719 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4720 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4721
4722 bool IsSigned = false;
4723 bool DoesNotReturn = false;
4724 bool IsReturnValueUsed = false;
4725 EVT VT = Op.getValueType();
4726 SDValue AllocaCall =
4727 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4728 CallingConv::C, IsSigned, DL, DoesNotReturn,
4729 IsReturnValueUsed)
4730 .first;
4731
4732 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4733 // to end of call in order to ensure it isn't broken up from the call
4734 // sequence.
4735 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4736 Register SPReg = Regs.getStackPointerRegister();
4737 Chain = AllocaCall.getValue(1);
4738 SDValue Glue = AllocaCall.getValue(2);
4739 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4740 Chain = NewSPRegNode.getValue(1);
4741
4742 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4743 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4744 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4745
4746 // Dynamically realign if needed.
4747 if (ExtraAlignSpace) {
4748 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4749 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4750 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4751 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4752 }
4753
4754 SDValue Ops[2] = {Result, Chain};
4755 return DAG.getMergeValues(Ops, DL);
4756}
4757
4758SDValue
4759SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4760 SelectionDAG &DAG) const {
4761 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4763 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4764 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4765
4766 SDValue Chain = Op.getOperand(0);
4767 SDValue Size = Op.getOperand(1);
4768 SDValue Align = Op.getOperand(2);
4769 SDLoc DL(Op);
4770
4771 // If user has set the no alignment function attribute, ignore
4772 // alloca alignments.
4773 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4774
4775 uint64_t StackAlign = TFI->getStackAlignment();
4776 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4777 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4778
4780 SDValue NeededSpace = Size;
4781
4782 // Get a reference to the stack pointer.
4783 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4784
4785 // If we need a backchain, save it now.
4786 SDValue Backchain;
4787 if (StoreBackchain)
4788 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4789 MachinePointerInfo());
4790
4791 // Add extra space for alignment if needed.
4792 if (ExtraAlignSpace)
4793 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4794 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4795
4796 // Get the new stack pointer value.
4797 SDValue NewSP;
4798 if (hasInlineStackProbe(MF)) {
4799 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4800 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4801 Chain = NewSP.getValue(1);
4802 }
4803 else {
4804 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4805 // Copy the new stack pointer back.
4806 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4807 }
4808
4809 // The allocated data lives above the 160 bytes allocated for the standard
4810 // frame, plus any outgoing stack arguments. We don't know how much that
4811 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4812 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4813 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4814
4815 // Dynamically realign if needed.
4816 if (RequiredAlign > StackAlign) {
4817 Result =
4818 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4819 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4820 Result =
4821 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4822 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4823 }
4824
4825 if (StoreBackchain)
4826 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4827 MachinePointerInfo());
4828
4829 SDValue Ops[2] = { Result, Chain };
4830 return DAG.getMergeValues(Ops, DL);
4831}
4832
4833SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4834 SDValue Op, SelectionDAG &DAG) const {
4835 SDLoc DL(Op);
4836
4837 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4838}
4839
4840SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4841 SelectionDAG &DAG,
4842 unsigned Opcode) const {
4843 EVT VT = Op.getValueType();
4844 SDLoc DL(Op);
4845 SDValue Even, Odd;
4846
4847 // This custom expander is only used on z17 and later for 64-bit types.
4848 assert(!is32Bit(VT));
4849 assert(Subtarget.hasMiscellaneousExtensions2());
4850
4851 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4852 // the high result in the even register. Return the latter.
4853 lowerGR128Binary(DAG, DL, VT, Opcode,
4854 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4855 return Even;
4856}
4857
4858SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4859 SelectionDAG &DAG) const {
4860 EVT VT = Op.getValueType();
4861 SDLoc DL(Op);
4862 SDValue Ops[2];
4863 if (is32Bit(VT))
4864 // Just do a normal 64-bit multiplication and extract the results.
4865 // We define this so that it can be used for constant division.
4866 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4867 Op.getOperand(1), Ops[1], Ops[0]);
4868 else if (Subtarget.hasMiscellaneousExtensions2())
4869 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4870 // the high result in the even register. ISD::SMUL_LOHI is defined to
4871 // return the low half first, so the results are in reverse order.
4872 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4873 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4874 else {
4875 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4876 //
4877 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4878 //
4879 // but using the fact that the upper halves are either all zeros
4880 // or all ones:
4881 //
4882 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4883 //
4884 // and grouping the right terms together since they are quicker than the
4885 // multiplication:
4886 //
4887 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4888 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4889 SDValue LL = Op.getOperand(0);
4890 SDValue RL = Op.getOperand(1);
4891 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4892 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4893 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4894 // the high result in the even register. ISD::SMUL_LOHI is defined to
4895 // return the low half first, so the results are in reverse order.
4896 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4897 LL, RL, Ops[1], Ops[0]);
4898 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4899 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4900 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4901 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4902 }
4903 return DAG.getMergeValues(Ops, DL);
4904}
4905
4906SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4907 SelectionDAG &DAG) const {
4908 EVT VT = Op.getValueType();
4909 SDLoc DL(Op);
4910 SDValue Ops[2];
4911 if (is32Bit(VT))
4912 // Just do a normal 64-bit multiplication and extract the results.
4913 // We define this so that it can be used for constant division.
4914 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4915 Op.getOperand(1), Ops[1], Ops[0]);
4916 else
4917 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4918 // the high result in the even register. ISD::UMUL_LOHI is defined to
4919 // return the low half first, so the results are in reverse order.
4920 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4921 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4922 return DAG.getMergeValues(Ops, DL);
4923}
4924
4925SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4926 SelectionDAG &DAG) const {
4927 SDValue Op0 = Op.getOperand(0);
4928 SDValue Op1 = Op.getOperand(1);
4929 EVT VT = Op.getValueType();
4930 SDLoc DL(Op);
4931
4932 // We use DSGF for 32-bit division. This means the first operand must
4933 // always be 64-bit, and the second operand should be 32-bit whenever
4934 // that is possible, to improve performance.
4935 if (is32Bit(VT))
4936 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4937 else if (DAG.ComputeNumSignBits(Op1) > 32)
4938 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4939
4940 // DSG(F) returns the remainder in the even register and the
4941 // quotient in the odd register.
4942 SDValue Ops[2];
4943 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4944 return DAG.getMergeValues(Ops, DL);
4945}
4946
4947SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4948 SelectionDAG &DAG) const {
4949 EVT VT = Op.getValueType();
4950 SDLoc DL(Op);
4951
4952 // DL(G) returns the remainder in the even register and the
4953 // quotient in the odd register.
4954 SDValue Ops[2];
4955 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4956 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4957 return DAG.getMergeValues(Ops, DL);
4958}
4959
4960SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4961 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4962
4963 // Get the known-zero masks for each operand.
4964 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4965 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4966 DAG.computeKnownBits(Ops[1])};
4967
4968 // See if the upper 32 bits of one operand and the lower 32 bits of the
4969 // other are known zero. They are the low and high operands respectively.
4970 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4971 Known[1].Zero.getZExtValue() };
4972 unsigned High, Low;
4973 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4974 High = 1, Low = 0;
4975 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4976 High = 0, Low = 1;
4977 else
4978 return Op;
4979
4980 SDValue LowOp = Ops[Low];
4981 SDValue HighOp = Ops[High];
4982
4983 // If the high part is a constant, we're better off using IILH.
4984 if (HighOp.getOpcode() == ISD::Constant)
4985 return Op;
4986
4987 // If the low part is a constant that is outside the range of LHI,
4988 // then we're better off using IILF.
4989 if (LowOp.getOpcode() == ISD::Constant) {
4990 int64_t Value = int32_t(LowOp->getAsZExtVal());
4991 if (!isInt<16>(Value))
4992 return Op;
4993 }
4994
4995 // Check whether the high part is an AND that doesn't change the
4996 // high 32 bits and just masks out low bits. We can skip it if so.
4997 if (HighOp.getOpcode() == ISD::AND &&
4998 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4999 SDValue HighOp0 = HighOp.getOperand(0);
5001 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
5002 HighOp = HighOp0;
5003 }
5004
5005 // Take advantage of the fact that all GR32 operations only change the
5006 // low 32 bits by truncating Low to an i32 and inserting it directly
5007 // using a subreg. The interesting cases are those where the truncation
5008 // can be folded.
5009 SDLoc DL(Op);
5010 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
5011 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
5012 MVT::i64, HighOp, Low32);
5013}
5014
5015// Lower SADDO/SSUBO/SMULO/UADDO/USUBO nodes.
5016SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
5017 SelectionDAG &DAG) const {
5018 SDNode *N = Op.getNode();
5019 SDValue LHS = N->getOperand(0);
5020 SDValue RHS = N->getOperand(1);
5021 SDLoc DL(N);
5022
5023 if (N->getValueType(0) == MVT::i128) {
5024 unsigned BaseOp = 0;
5025 unsigned FlagOp = 0;
5026 bool IsBorrow = false;
5027 switch (Op.getOpcode()) {
5028 default: llvm_unreachable("Unknown instruction!");
5029 case ISD::UADDO:
5030 BaseOp = ISD::ADD;
5031 FlagOp = SystemZISD::VACC;
5032 break;
5033 case ISD::USUBO:
5034 BaseOp = ISD::SUB;
5035 FlagOp = SystemZISD::VSCBI;
5036 IsBorrow = true;
5037 break;
5038 }
5039 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
5040 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
5041 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5042 DAG.getValueType(MVT::i1));
5043 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5044 if (IsBorrow)
5045 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5046 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5047 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5048 }
5049
5050 unsigned BaseOp = 0;
5051 unsigned CCValid = 0;
5052 unsigned CCMask = 0;
5053
5054 switch (Op.getOpcode()) {
5055 default: llvm_unreachable("Unknown instruction!");
5056 case ISD::SADDO:
5057 BaseOp = SystemZISD::SADDO;
5058 CCValid = SystemZ::CCMASK_ARITH;
5060 break;
5061 case ISD::SSUBO:
5062 BaseOp = SystemZISD::SSUBO;
5063 CCValid = SystemZ::CCMASK_ARITH;
5065 break;
5066 case ISD::SMULO:
5067 BaseOp = SystemZISD::SMULO;
5068 CCValid = SystemZ::CCMASK_ARITH;
5070 break;
5071 case ISD::UADDO:
5072 BaseOp = SystemZISD::UADDO;
5073 CCValid = SystemZ::CCMASK_LOGICAL;
5075 break;
5076 case ISD::USUBO:
5077 BaseOp = SystemZISD::USUBO;
5078 CCValid = SystemZ::CCMASK_LOGICAL;
5080 break;
5081 }
5082
5083 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
5084 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
5085
5086 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5087 if (N->getValueType(1) == MVT::i1)
5088 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5089
5090 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5091}
5092
5093static bool isAddCarryChain(SDValue Carry) {
5094 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
5095 Carry->getValueType(0) != MVT::i128)
5096 Carry = Carry.getOperand(2);
5097 return Carry.getOpcode() == ISD::UADDO &&
5098 Carry->getValueType(0) != MVT::i128;
5099}
5100
5101static bool isSubBorrowChain(SDValue Carry) {
5102 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
5103 Carry->getValueType(0) != MVT::i128)
5104 Carry = Carry.getOperand(2);
5105 return Carry.getOpcode() == ISD::USUBO &&
5106 Carry->getValueType(0) != MVT::i128;
5107}
5108
5109// Lower UADDO_CARRY/USUBO_CARRY nodes.
5110SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
5111 SelectionDAG &DAG) const {
5112
5113 SDNode *N = Op.getNode();
5114 MVT VT = N->getSimpleValueType(0);
5115
5116 // Let legalize expand this if it isn't a legal type yet.
5117 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5118 return SDValue();
5119
5120 SDValue LHS = N->getOperand(0);
5121 SDValue RHS = N->getOperand(1);
5122 SDValue Carry = Op.getOperand(2);
5123 SDLoc DL(N);
5124
5125 if (VT == MVT::i128) {
5126 unsigned BaseOp = 0;
5127 unsigned FlagOp = 0;
5128 bool IsBorrow = false;
5129 switch (Op.getOpcode()) {
5130 default: llvm_unreachable("Unknown instruction!");
5131 case ISD::UADDO_CARRY:
5132 BaseOp = SystemZISD::VAC;
5133 FlagOp = SystemZISD::VACCC;
5134 break;
5135 case ISD::USUBO_CARRY:
5136 BaseOp = SystemZISD::VSBI;
5137 FlagOp = SystemZISD::VSBCBI;
5138 IsBorrow = true;
5139 break;
5140 }
5141 if (IsBorrow)
5142 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5143 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5144 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5145 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5146 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5147 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5148 DAG.getValueType(MVT::i1));
5149 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5150 if (IsBorrow)
5151 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5152 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5153 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5154 }
5155
5156 unsigned BaseOp = 0;
5157 unsigned CCValid = 0;
5158 unsigned CCMask = 0;
5159
5160 switch (Op.getOpcode()) {
5161 default: llvm_unreachable("Unknown instruction!");
5162 case ISD::UADDO_CARRY:
5163 if (!isAddCarryChain(Carry))
5164 return SDValue();
5165
5166 BaseOp = SystemZISD::ADDCARRY;
5167 CCValid = SystemZ::CCMASK_LOGICAL;
5169 break;
5170 case ISD::USUBO_CARRY:
5171 if (!isSubBorrowChain(Carry))
5172 return SDValue();
5173
5174 BaseOp = SystemZISD::SUBCARRY;
5175 CCValid = SystemZ::CCMASK_LOGICAL;
5177 break;
5178 }
5179
5180 // Set the condition code from the carry flag.
5181 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5182 DAG.getConstant(CCValid, DL, MVT::i32),
5183 DAG.getConstant(CCMask, DL, MVT::i32));
5184
5185 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5186 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5187
5188 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5189 if (N->getValueType(1) == MVT::i1)
5190 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5191
5192 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5193}
5194
5195SDValue SystemZTargetLowering::lowerPDEP(SDValue Op, SelectionDAG &DAG) const {
5196 SDLoc DL(Op);
5197 assert(Op.getValueType() == MVT::i64 && "Expected i64 PDEP");
5198 SDValue Val = Op.getOperand(0);
5199 SDValue Mask = Op.getOperand(1);
5200
5201 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
5202 unsigned PopCount = MaskC->getAPIntValue().popcount();
5203 if (PopCount == 0)
5204 return DAG.getConstant(0, DL, MVT::i64);
5205 if (PopCount == 64)
5206 return Val;
5207 SDValue ShiftedVal =
5208 DAG.getNode(ISD::SHL, DL, MVT::i64, Val,
5209 DAG.getConstant(64 - PopCount, DL, MVT::i64));
5210 return DAG.getNode(
5211 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5212 DAG.getTargetConstant(Intrinsic::s390_bdepg, DL, MVT::i32), ShiftedVal,
5213 Mask);
5214 }
5215
5216 SDValue PopCount = DAG.getNode(ISD::CTPOP, DL, MVT::i64, Mask);
5217 SDValue ShiftAmt = DAG.getNode(ISD::AND, DL, MVT::i64,
5218 DAG.getNegative(PopCount, DL, MVT::i64),
5219 DAG.getConstant(63, DL, MVT::i64));
5220 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, MVT::i64, Val, ShiftAmt);
5221 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5222 DAG.getTargetConstant(Intrinsic::s390_bdepg, DL, MVT::i32),
5223 ShiftedVal, Mask);
5224}
5225
5226SDValue SystemZTargetLowering::lowerPEXT(SDValue Op, SelectionDAG &DAG) const {
5227 SDLoc DL(Op);
5228 assert(Op.getValueType() == MVT::i64 && "Expected i64 PEXT");
5229 SDValue Val = Op.getOperand(0);
5230 SDValue Mask = Op.getOperand(1);
5231
5232 SDValue Bext = DAG.getNode(
5233 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5234 DAG.getTargetConstant(Intrinsic::s390_bextg, DL, MVT::i32), Val, Mask);
5235
5236 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
5237 unsigned PopCount = MaskC->getAPIntValue().popcount();
5238 if (PopCount == 0)
5239 return DAG.getConstant(0, DL, MVT::i64);
5240 if (PopCount == 64)
5241 return Val;
5242 return DAG.getNode(ISD::SRL, DL, MVT::i64, Bext,
5243 DAG.getConstant(64 - PopCount, DL, MVT::i64));
5244 }
5245
5246 SDValue PopCount = DAG.getNode(ISD::CTPOP, DL, MVT::i64, Mask);
5247 SDValue ShiftAmt = DAG.getNode(ISD::AND, DL, MVT::i64,
5248 DAG.getNegative(PopCount, DL, MVT::i64),
5249 DAG.getConstant(63, DL, MVT::i64));
5250 return DAG.getNode(ISD::SRL, DL, MVT::i64, Bext, ShiftAmt);
5251}
5252
5253SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5254 SelectionDAG &DAG) const {
5255 EVT VT = Op.getValueType();
5256 SDLoc DL(Op);
5257 Op = Op.getOperand(0);
5258
5259 if (VT.getScalarSizeInBits() == 128) {
5260 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5261 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5262 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5263 DAG.getConstant(0, DL, MVT::i64));
5264 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5265 return Op;
5266 }
5267
5268 // Handle vector types via VPOPCT.
5269 if (VT.isVector()) {
5270 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5271 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5272 switch (VT.getScalarSizeInBits()) {
5273 case 8:
5274 break;
5275 case 16: {
5276 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5277 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5278 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5279 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5280 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5281 break;
5282 }
5283 case 32: {
5284 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5285 DAG.getConstant(0, DL, MVT::i32));
5286 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5287 break;
5288 }
5289 case 64: {
5290 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5291 DAG.getConstant(0, DL, MVT::i32));
5292 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5293 Tmp = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, Tmp);
5294 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5295 break;
5296 }
5297 default:
5298 llvm_unreachable("Unexpected type");
5299 }
5300 return Op;
5301 }
5302
5303 // Get the known-zero mask for the operand.
5304 KnownBits Known = DAG.computeKnownBits(Op);
5305 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5306 if (NumSignificantBits == 0)
5307 return DAG.getConstant(0, DL, VT);
5308
5309 // Skip known-zero high parts of the operand.
5310 int64_t OrigBitSize = VT.getSizeInBits();
5311 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5312 BitSize = std::min(BitSize, OrigBitSize);
5313
5314 // The POPCNT instruction counts the number of bits in each byte.
5315 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5316 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5317 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5318
5319 // Add up per-byte counts in a binary tree. All bits of Op at
5320 // position larger than BitSize remain zero throughout.
5321 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5322 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5323 if (BitSize != OrigBitSize)
5324 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5325 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5326 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5327 }
5328
5329 // Extract overall result from high byte.
5330 if (BitSize > 8)
5331 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5332 DAG.getConstant(BitSize - 8, DL, VT));
5333
5334 return Op;
5335}
5336
5337SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5338 SelectionDAG &DAG) const {
5339 SDLoc DL(Op);
5340 AtomicOrdering FenceOrdering =
5341 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5342 SyncScope::ID FenceSSID =
5343 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5344
5345 // The only fence that needs an instruction is a sequentially-consistent
5346 // cross-thread fence.
5347 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5348 FenceSSID == SyncScope::System) {
5349 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5350 Op.getOperand(0)),
5351 0);
5352 }
5353
5354 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5355 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5356}
5357
5358SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5359 SelectionDAG &DAG) const {
5360 EVT RegVT = Op.getValueType();
5361 if (RegVT.getSizeInBits() == 128)
5362 return lowerATOMIC_LDST_I128(Op, DAG);
5363 return lowerLoadF16(Op, DAG);
5364}
5365
5366SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5367 SelectionDAG &DAG) const {
5368 auto *Node = cast<AtomicSDNode>(Op.getNode());
5369 if (Node->getMemoryVT().getSizeInBits() == 128)
5370 return lowerATOMIC_LDST_I128(Op, DAG);
5371 return lowerStoreF16(Op, DAG);
5372}
5373
5374SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5375 SelectionDAG &DAG) const {
5376 auto *Node = cast<AtomicSDNode>(Op.getNode());
5377 assert(
5378 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5379 "Only custom lowering i128 or f128.");
5380 // Use same code to handle both legal and non-legal i128 types.
5382 LowerOperationWrapper(Node, Results, DAG);
5383 return DAG.getMergeValues(Results, SDLoc(Op));
5384}
5385
5386// Prepare for a Compare And Swap for a subword operation. This needs to be
5387// done in memory with 4 bytes at natural alignment.
5389 SDValue &AlignedAddr, SDValue &BitShift,
5390 SDValue &NegBitShift) {
5391 EVT PtrVT = Addr.getValueType();
5392 EVT WideVT = MVT::i32;
5393
5394 // Get the address of the containing word.
5395 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5396 DAG.getSignedConstant(-4, DL, PtrVT));
5397
5398 // Get the number of bits that the word must be rotated left in order
5399 // to bring the field to the top bits of a GR32.
5400 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5401 DAG.getConstant(3, DL, PtrVT));
5402 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5403
5404 // Get the complementing shift amount, for rotating a field in the top
5405 // bits back to its proper position.
5406 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5407 DAG.getConstant(0, DL, WideVT), BitShift);
5408
5409}
5410
5411// N is an 8- or 16-bit ATOMIC_LOAD_* operation. Lower it into the fullword
5412// ATOMIC_LOADW_* operation.
5413void SystemZTargetLowering::lowerATOMIC_LOAD_OP(
5415 unsigned Opcode) const {
5416 auto *Node = cast<AtomicSDNode>(N);
5417
5418 EVT NarrowVT = Node->getMemoryVT();
5419 EVT WideVT = MVT::i32;
5420 int64_t BitSize = NarrowVT.getSizeInBits();
5421 SDValue ChainIn = Node->getChain();
5422 SDValue Addr = Node->getBasePtr();
5423 SDValue Src2 = Node->getVal();
5424 MachineMemOperand *MMO = Node->getMemOperand();
5425 SDLoc DL(Node);
5426
5427 // Convert atomic subtracts of constants into additions.
5428 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5429 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5430 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5431 Src2 = DAG.getConstant(-Const->getAPIntValue(), DL, Src2.getValueType());
5432 }
5433
5434 SDValue AlignedAddr, BitShift, NegBitShift;
5435 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5436
5437 // Extend the source operand to 32 bits and prepare it for the inner loop.
5438 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5439 // operations require the source to be shifted in advance. (This shift
5440 // can be folded if the source is constant.) For AND and NAND, the lower
5441 // bits must be set, while for other opcodes they should be left clear.
5442 Src2 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Src2);
5443 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5444 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5445 DAG.getConstant(32 - BitSize, DL, WideVT));
5446 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5447 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5448 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5449 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5450
5451 // Construct the ATOMIC_LOADW_* node.
5452 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5453 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5454 DAG.getConstant(BitSize, DL, WideVT) };
5455 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5456 NarrowVT, MMO);
5457
5458 // Rotate the result of the final CS so that the field is in the lower
5459 // bits of a GR32, then truncate it.
5460 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5461 DAG.getConstant(BitSize, DL, WideVT));
5462 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5463 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, Result));
5464 Results.push_back(AtomicOp.getValue(1));
5465}
5466
5467// Op is a 32- or 64-bit ATOMIC_LOAD_SUB operation. Convert it into an
5468// addition.
5469SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5470 SelectionDAG &DAG) const {
5471 auto *Node = cast<AtomicSDNode>(Op.getNode());
5472 EVT MemVT = Node->getMemoryVT();
5473 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5474 assert(Subtarget.hasInterlockedAccess1() &&
5475 "Should have been expanded by AtomicExpand pass.");
5476 SDValue Src2 = Node->getVal();
5477 SDLoc DL(Src2);
5478 SDValue NegSrc2 =
5479 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5480 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT, Node->getChain(),
5481 Node->getBasePtr(), NegSrc2, Node->getMemOperand());
5482}
5483
5484// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5485SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5486 SelectionDAG &DAG) const {
5487 auto *Node = cast<AtomicSDNode>(Op.getNode());
5488 SDValue ChainIn = Node->getOperand(0);
5489 SDValue Addr = Node->getOperand(1);
5490 SDValue CmpVal = Node->getOperand(2);
5491 SDValue SwapVal = Node->getOperand(3);
5492 MachineMemOperand *MMO = Node->getMemOperand();
5493 SDLoc DL(Node);
5494
5495 if (Node->getMemoryVT() == MVT::i128) {
5496 // Use same code to handle both legal and non-legal i128 types.
5498 LowerOperationWrapper(Node, Results, DAG);
5499 return DAG.getMergeValues(Results, DL);
5500 }
5501
5502 // We have native support for 32-bit and 64-bit compare and swap, but we
5503 // still need to expand extracting the "success" result from the CC.
5504 EVT NarrowVT = Node->getMemoryVT();
5505 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5506 if (NarrowVT == WideVT) {
5507 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5508 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5509 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5510 DL, Tys, Ops, NarrowVT, MMO);
5511 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5513
5514 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5515 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5516 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5517 return SDValue();
5518 }
5519
5520 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5521 // via a fullword ATOMIC_CMP_SWAPW operation.
5522 int64_t BitSize = NarrowVT.getSizeInBits();
5523
5524 SDValue AlignedAddr, BitShift, NegBitShift;
5525 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5526
5527 // Construct the ATOMIC_CMP_SWAPW node.
5528 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5529 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5530 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5531 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5532 VTList, Ops, NarrowVT, MMO);
5533 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5535
5536 // emitAtomicCmpSwapW() will zero extend the result (original value).
5537 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5538 DAG.getValueType(NarrowVT));
5539 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5540 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5541 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5542 return SDValue();
5543}
5544
5546SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5547 // Because of how we convert atomic_load and atomic_store to normal loads and
5548 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5549 // since DAGCombine hasn't been updated to account for atomic, but non
5550 // volatile loads. (See D57601)
5551 if (auto *SI = dyn_cast<StoreInst>(&I))
5552 if (SI->isAtomic())
5554 if (auto *LI = dyn_cast<LoadInst>(&I))
5555 if (LI->isAtomic())
5557 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5558 if (AI->isAtomic())
5560 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5561 if (AI->isAtomic())
5564}
5565
5566SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5567 SelectionDAG &DAG) const {
5569 auto *Regs = Subtarget.getSpecialRegisters();
5571 report_fatal_error("Variable-sized stack allocations are not supported "
5572 "in GHC calling convention");
5573 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5574 Regs->getStackPointerRegister(), Op.getValueType());
5575}
5576
5577SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5578 SelectionDAG &DAG) const {
5580 auto *Regs = Subtarget.getSpecialRegisters();
5581
5583 report_fatal_error("Variable-sized stack allocations are not supported "
5584 "in GHC calling convention");
5585
5586 SDValue Chain = Op.getOperand(0);
5587 SDValue NewSP = Op.getOperand(1);
5588 SDLoc DL(Op);
5589
5590 // XPLINK: @@ALCAXP (lowerDYNAMIC_STACKALLOC_XPLINK) moves the frame header
5591 // (register save area and reserved words at SP + bias) down with the stack
5592 // pointer, and calls made while the stack pointer is lowered place their
5593 // arguments over the old header. The current header must be copied back to
5594 // the restored stack pointer, otherwise the epilogue and the LE stack walk
5595 // use a clobbered header (abend U4083). No signal may be delivered while
5596 // the stack pointer is changed and the header is copied, so this is done in
5597 // a stub routine (emitted once per module by the AsmPrinter), which gets
5598 // the new stack pointer in R1 and is called with BASR 3,3.
5599 if (Subtarget.isTargetXPLINK64()) {
5600 SDValue Glue;
5601 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, NewSP, Glue);
5602 Glue = Chain.getValue(1);
5603 return DAG.getNode(SystemZISD::XPLINK_STACKRESTORE, DL, MVT::Other, Chain,
5604 Glue);
5605 }
5606
5607 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5608 SDValue Backchain;
5609 if (StoreBackchain) {
5610 SDValue OldSP = DAG.getCopyFromReg(
5611 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5612 Backchain =
5613 DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5614 MachinePointerInfo());
5615 }
5616
5617 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5618
5619 if (StoreBackchain)
5620 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5621 MachinePointerInfo());
5622
5623 return Chain;
5624}
5625
5626SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5627 SelectionDAG &DAG) const {
5628 bool IsData = Op.getConstantOperandVal(4);
5629 if (!IsData)
5630 // Just preserve the chain.
5631 return Op.getOperand(0);
5632
5633 SDLoc DL(Op);
5634 bool IsWrite = Op.getConstantOperandVal(2);
5635 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5636 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5637 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5638 Op.getOperand(1)};
5639 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5640 Node->getVTList(), Ops,
5641 Node->getMemoryVT(), Node->getMemOperand());
5642}
5643
5644SDValue
5645SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5646 SelectionDAG &DAG) const {
5647 unsigned Opcode, CCValid;
5648 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5649 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5650 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5651 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5652 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5653 return SDValue();
5654 }
5655
5656 return SDValue();
5657}
5658
5659SDValue
5660SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5661 SelectionDAG &DAG) const {
5662 unsigned Opcode, CCValid;
5663 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5664 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5665 if (Op->getNumValues() == 1)
5666 return getCCResult(DAG, SDValue(Node, 0));
5667 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5668 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5669 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5670 }
5671
5672 unsigned Id = Op.getConstantOperandVal(0);
5673 switch (Id) {
5674 case Intrinsic::thread_pointer:
5675 return lowerThreadPointer(SDLoc(Op), DAG);
5676
5677 case Intrinsic::s390_vpdi:
5678 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5679 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5680
5681 case Intrinsic::s390_vperm:
5682 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5683 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5684
5685 case Intrinsic::s390_vuphb:
5686 case Intrinsic::s390_vuphh:
5687 case Intrinsic::s390_vuphf:
5688 case Intrinsic::s390_vuphg:
5689 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5690 Op.getOperand(1));
5691
5692 case Intrinsic::s390_vuplhb:
5693 case Intrinsic::s390_vuplhh:
5694 case Intrinsic::s390_vuplhf:
5695 case Intrinsic::s390_vuplhg:
5696 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5697 Op.getOperand(1));
5698
5699 case Intrinsic::s390_vuplb:
5700 case Intrinsic::s390_vuplhw:
5701 case Intrinsic::s390_vuplf:
5702 case Intrinsic::s390_vuplg:
5703 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5704 Op.getOperand(1));
5705
5706 case Intrinsic::s390_vupllb:
5707 case Intrinsic::s390_vupllh:
5708 case Intrinsic::s390_vupllf:
5709 case Intrinsic::s390_vupllg:
5710 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5711 Op.getOperand(1));
5712
5713 case Intrinsic::s390_vsumb:
5714 case Intrinsic::s390_vsumh:
5715 case Intrinsic::s390_vsumgh:
5716 case Intrinsic::s390_vsumgf:
5717 case Intrinsic::s390_vsumqf:
5718 case Intrinsic::s390_vsumqg:
5719 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5720 Op.getOperand(1), Op.getOperand(2));
5721
5722 case Intrinsic::s390_vaq:
5723 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5724 Op.getOperand(1), Op.getOperand(2));
5725 case Intrinsic::s390_vaccb:
5726 case Intrinsic::s390_vacch:
5727 case Intrinsic::s390_vaccf:
5728 case Intrinsic::s390_vaccg:
5729 case Intrinsic::s390_vaccq:
5730 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5731 Op.getOperand(1), Op.getOperand(2));
5732 case Intrinsic::s390_vacq:
5733 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5734 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5735 case Intrinsic::s390_vacccq:
5736 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5737 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5738
5739 case Intrinsic::s390_vsq:
5740 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5741 Op.getOperand(1), Op.getOperand(2));
5742 case Intrinsic::s390_vscbib:
5743 case Intrinsic::s390_vscbih:
5744 case Intrinsic::s390_vscbif:
5745 case Intrinsic::s390_vscbig:
5746 case Intrinsic::s390_vscbiq:
5747 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5748 Op.getOperand(1), Op.getOperand(2));
5749 case Intrinsic::s390_vsbiq:
5750 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5751 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5752 case Intrinsic::s390_vsbcbiq:
5753 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5754 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5755
5756 case Intrinsic::s390_vmhb:
5757 case Intrinsic::s390_vmhh:
5758 case Intrinsic::s390_vmhf:
5759 case Intrinsic::s390_vmhg:
5760 case Intrinsic::s390_vmhq:
5761 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5762 Op.getOperand(1), Op.getOperand(2));
5763 case Intrinsic::s390_vmlhb:
5764 case Intrinsic::s390_vmlhh:
5765 case Intrinsic::s390_vmlhf:
5766 case Intrinsic::s390_vmlhg:
5767 case Intrinsic::s390_vmlhq:
5768 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5769 Op.getOperand(1), Op.getOperand(2));
5770
5771 case Intrinsic::s390_vavgb:
5772 case Intrinsic::s390_vavgh:
5773 case Intrinsic::s390_vavgf:
5774 case Intrinsic::s390_vavgg:
5775 case Intrinsic::s390_vavgq:
5776 return DAG.getNode(ISD::AVGCEILS, SDLoc(Op), Op.getValueType(),
5777 Op.getOperand(1), Op.getOperand(2));
5778 case Intrinsic::s390_vavglb:
5779 case Intrinsic::s390_vavglh:
5780 case Intrinsic::s390_vavglf:
5781 case Intrinsic::s390_vavglg:
5782 case Intrinsic::s390_vavglq:
5783 return DAG.getNode(ISD::AVGCEILU, SDLoc(Op), Op.getValueType(),
5784 Op.getOperand(1), Op.getOperand(2));
5785
5786 case Intrinsic::s390_vmahb:
5787 case Intrinsic::s390_vmahh:
5788 case Intrinsic::s390_vmahf:
5789 case Intrinsic::s390_vmahg:
5790 case Intrinsic::s390_vmahq:
5791 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5792 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5793 case Intrinsic::s390_vmalhb:
5794 case Intrinsic::s390_vmalhh:
5795 case Intrinsic::s390_vmalhf:
5796 case Intrinsic::s390_vmalhg:
5797 case Intrinsic::s390_vmalhq:
5798 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5799 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5800
5801 case Intrinsic::s390_vmeb:
5802 case Intrinsic::s390_vmeh:
5803 case Intrinsic::s390_vmef:
5804 case Intrinsic::s390_vmeg:
5805 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5806 Op.getOperand(1), Op.getOperand(2));
5807 case Intrinsic::s390_vmleb:
5808 case Intrinsic::s390_vmleh:
5809 case Intrinsic::s390_vmlef:
5810 case Intrinsic::s390_vmleg:
5811 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5812 Op.getOperand(1), Op.getOperand(2));
5813 case Intrinsic::s390_vmob:
5814 case Intrinsic::s390_vmoh:
5815 case Intrinsic::s390_vmof:
5816 case Intrinsic::s390_vmog:
5817 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5818 Op.getOperand(1), Op.getOperand(2));
5819 case Intrinsic::s390_vmlob:
5820 case Intrinsic::s390_vmloh:
5821 case Intrinsic::s390_vmlof:
5822 case Intrinsic::s390_vmlog:
5823 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5824 Op.getOperand(1), Op.getOperand(2));
5825
5826 case Intrinsic::s390_vmaeb:
5827 case Intrinsic::s390_vmaeh:
5828 case Intrinsic::s390_vmaef:
5829 case Intrinsic::s390_vmaeg:
5830 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5831 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5832 Op.getOperand(1), Op.getOperand(2)),
5833 Op.getOperand(3));
5834 case Intrinsic::s390_vmaleb:
5835 case Intrinsic::s390_vmaleh:
5836 case Intrinsic::s390_vmalef:
5837 case Intrinsic::s390_vmaleg:
5838 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5839 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5840 Op.getOperand(1), Op.getOperand(2)),
5841 Op.getOperand(3));
5842 case Intrinsic::s390_vmaob:
5843 case Intrinsic::s390_vmaoh:
5844 case Intrinsic::s390_vmaof:
5845 case Intrinsic::s390_vmaog:
5846 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5847 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5848 Op.getOperand(1), Op.getOperand(2)),
5849 Op.getOperand(3));
5850 case Intrinsic::s390_vmalob:
5851 case Intrinsic::s390_vmaloh:
5852 case Intrinsic::s390_vmalof:
5853 case Intrinsic::s390_vmalog:
5854 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5855 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5856 Op.getOperand(1), Op.getOperand(2)),
5857 Op.getOperand(3));
5858 }
5859
5860 return SDValue();
5861}
5862
5863namespace {
5864// Says that SystemZISD operation Opcode can be used to perform the equivalent
5865// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5866// Operand is the constant third operand, otherwise it is the number of
5867// bytes in each element of the result.
5868struct Permute {
5869 unsigned Opcode;
5870 unsigned Operand;
5871 unsigned char Bytes[SystemZ::VectorBytes];
5872};
5873}
5874
5875static const Permute PermuteForms[] = {
5876 // VMRHG
5877 { SystemZISD::MERGE_HIGH, 8,
5878 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5879 // VMRHF
5880 { SystemZISD::MERGE_HIGH, 4,
5881 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5882 // VMRHH
5883 { SystemZISD::MERGE_HIGH, 2,
5884 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5885 // VMRHB
5886 { SystemZISD::MERGE_HIGH, 1,
5887 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5888 // VMRLG
5889 { SystemZISD::MERGE_LOW, 8,
5890 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5891 // VMRLF
5892 { SystemZISD::MERGE_LOW, 4,
5893 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5894 // VMRLH
5895 { SystemZISD::MERGE_LOW, 2,
5896 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5897 // VMRLB
5898 { SystemZISD::MERGE_LOW, 1,
5899 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5900 // VPKG
5901 { SystemZISD::PACK, 4,
5902 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5903 // VPKF
5904 { SystemZISD::PACK, 2,
5905 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5906 // VPKH
5907 { SystemZISD::PACK, 1,
5908 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5909 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5910 { SystemZISD::PERMUTE_DWORDS, 4,
5911 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5912 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5913 { SystemZISD::PERMUTE_DWORDS, 1,
5914 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5915};
5916
5917// Called after matching a vector shuffle against a particular pattern.
5918// Both the original shuffle and the pattern have two vector operands.
5919// OpNos[0] is the operand of the original shuffle that should be used for
5920// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5921// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5922// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5923// for operands 0 and 1 of the pattern.
5924static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5925 if (OpNos[0] < 0) {
5926 if (OpNos[1] < 0)
5927 return false;
5928 OpNo0 = OpNo1 = OpNos[1];
5929 } else if (OpNos[1] < 0) {
5930 OpNo0 = OpNo1 = OpNos[0];
5931 } else {
5932 OpNo0 = OpNos[0];
5933 OpNo1 = OpNos[1];
5934 }
5935 return true;
5936}
5937
5938// Bytes is a VPERM-like permute vector, except that -1 is used for
5939// undefined bytes. Return true if the VPERM can be implemented using P.
5940// When returning true set OpNo0 to the VPERM operand that should be
5941// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5942//
5943// For example, if swapping the VPERM operands allows P to match, OpNo0
5944// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5945// operand, but rewriting it to use two duplicated operands allows it to
5946// match P, then OpNo0 and OpNo1 will be the same.
5947static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5948 unsigned &OpNo0, unsigned &OpNo1) {
5949 int OpNos[] = { -1, -1 };
5950 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5951 int Elt = Bytes[I];
5952 if (Elt >= 0) {
5953 // Make sure that the two permute vectors use the same suboperand
5954 // byte number. Only the operand numbers (the high bits) are
5955 // allowed to differ.
5956 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5957 return false;
5958 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5959 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5960 // Make sure that the operand mappings are consistent with previous
5961 // elements.
5962 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5963 return false;
5964 OpNos[ModelOpNo] = RealOpNo;
5965 }
5966 }
5967 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5968}
5969
5970// As above, but search for a matching permute.
5971static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5972 unsigned &OpNo0, unsigned &OpNo1) {
5973 for (auto &P : PermuteForms)
5974 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5975 return &P;
5976 return nullptr;
5977}
5978
5979// Bytes is a VPERM-like permute vector, except that -1 is used for
5980// undefined bytes. This permute is an operand of an outer permute.
5981// See whether redistributing the -1 bytes gives a shuffle that can be
5982// implemented using P. If so, set Transform to a VPERM-like permute vector
5983// that, when applied to the result of P, gives the original permute in Bytes.
5985 const Permute &P,
5986 SmallVectorImpl<int> &Transform) {
5987 unsigned To = 0;
5988 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5989 int Elt = Bytes[From];
5990 if (Elt < 0)
5991 // Byte number From of the result is undefined.
5992 Transform[From] = -1;
5993 else {
5994 while (P.Bytes[To] != Elt) {
5995 To += 1;
5996 if (To == SystemZ::VectorBytes)
5997 return false;
5998 }
5999 Transform[From] = To;
6000 }
6001 }
6002 return true;
6003}
6004
6005// As above, but search for a matching permute.
6006static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
6007 SmallVectorImpl<int> &Transform) {
6008 for (auto &P : PermuteForms)
6009 if (matchDoublePermute(Bytes, P, Transform))
6010 return &P;
6011 return nullptr;
6012}
6013
6014// Convert the mask of the given shuffle op into a byte-level mask,
6015// as if it had type vNi8.
6016static bool getVPermMask(SDValue ShuffleOp,
6017 SmallVectorImpl<int> &Bytes) {
6018 EVT VT = ShuffleOp.getValueType();
6019 unsigned NumElements = VT.getVectorNumElements();
6020 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6021
6022 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
6023 Bytes.resize(NumElements * BytesPerElement, -1);
6024 for (unsigned I = 0; I < NumElements; ++I) {
6025 int Index = VSN->getMaskElt(I);
6026 if (Index >= 0)
6027 for (unsigned J = 0; J < BytesPerElement; ++J)
6028 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
6029 }
6030 return true;
6031 }
6032 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
6033 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
6034 unsigned Index = ShuffleOp.getConstantOperandVal(1);
6035 Bytes.resize(NumElements * BytesPerElement, -1);
6036 for (unsigned I = 0; I < NumElements; ++I)
6037 for (unsigned J = 0; J < BytesPerElement; ++J)
6038 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
6039 return true;
6040 }
6041 return false;
6042}
6043
6044// Bytes is a VPERM-like permute vector, except that -1 is used for
6045// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
6046// the result come from a contiguous sequence of bytes from one input.
6047// Set Base to the selector for the first byte if so.
6048static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
6049 unsigned BytesPerElement, int &Base) {
6050 Base = -1;
6051 for (unsigned I = 0; I < BytesPerElement; ++I) {
6052 if (Bytes[Start + I] >= 0) {
6053 unsigned Elem = Bytes[Start + I];
6054 if (Base < 0) {
6055 Base = Elem - I;
6056 // Make sure the bytes would come from one input operand.
6057 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
6058 return false;
6059 } else if (unsigned(Base) != Elem - I)
6060 return false;
6061 }
6062 }
6063 return true;
6064}
6065
6066// Bytes is a VPERM-like permute vector, except that -1 is used for
6067// undefined bytes. Return true if it can be performed using VSLDB.
6068// When returning true, set StartIndex to the shift amount and OpNo0
6069// and OpNo1 to the VPERM operands that should be used as the first
6070// and second shift operand respectively.
6072 unsigned &StartIndex, unsigned &OpNo0,
6073 unsigned &OpNo1) {
6074 int OpNos[] = { -1, -1 };
6075 int Shift = -1;
6076 for (unsigned I = 0; I < 16; ++I) {
6077 int Index = Bytes[I];
6078 if (Index >= 0) {
6079 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
6080 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
6081 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
6082 if (Shift < 0)
6083 Shift = ExpectedShift;
6084 else if (Shift != ExpectedShift)
6085 return false;
6086 // Make sure that the operand mappings are consistent with previous
6087 // elements.
6088 if (OpNos[ModelOpNo] == 1 - RealOpNo)
6089 return false;
6090 OpNos[ModelOpNo] = RealOpNo;
6091 }
6092 }
6093 StartIndex = Shift;
6094 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
6095}
6096
6097// Create a node that performs P on operands Op0 and Op1, casting the
6098// operands to the appropriate type. The type of the result is determined by P.
6100 const Permute &P, SDValue Op0, SDValue Op1) {
6101 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
6102 // elements of a PACK are twice as wide as the outputs.
6103 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
6104 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
6105 P.Operand);
6106 // Cast both operands to the appropriate type.
6107 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
6108 SystemZ::VectorBytes / InBytes);
6109 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
6110 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
6111 SDValue Op;
6112 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
6113 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
6114 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
6115 } else if (P.Opcode == SystemZISD::PACK) {
6116 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
6117 SystemZ::VectorBytes / P.Operand);
6118 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
6119 } else {
6120 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
6121 }
6122 return Op;
6123}
6124
6125static bool isZeroVector(SDValue N) {
6126 if (N->getOpcode() == ISD::BITCAST)
6127 N = N->getOperand(0);
6128 if (N->getOpcode() == ISD::SPLAT_VECTOR)
6129 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
6130 return Op->getZExtValue() == 0;
6132}
6133
6134// Return the index of the zero/undef vector, or UINT32_MAX if not found.
6135static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
6136 for (unsigned I = 0; I < Num ; I++)
6137 if (isZeroVector(Ops[I]))
6138 return I;
6139 return UINT32_MAX;
6140}
6141
6142// Bytes is a VPERM-like permute vector, except that -1 is used for
6143// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
6144// VSLDB or VPERM.
6146 SDValue *Ops,
6147 const SmallVectorImpl<int> &Bytes) {
6148 for (unsigned I = 0; I < 2; ++I)
6149 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
6150
6151 // First see whether VSLDB can be used.
6152 unsigned StartIndex, OpNo0, OpNo1;
6153 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
6154 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
6155 Ops[OpNo1],
6156 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
6157
6158 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
6159 // eliminate a zero vector by reusing any zero index in the permute vector.
6160 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
6161 if (ZeroVecIdx != UINT32_MAX) {
6162 bool MaskFirst = true;
6163 int ZeroIdx = -1;
6164 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6165 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6166 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6167 if (OpNo == ZeroVecIdx && I == 0) {
6168 // If the first byte is zero, use mask as first operand.
6169 ZeroIdx = 0;
6170 break;
6171 }
6172 if (OpNo != ZeroVecIdx && Byte == 0) {
6173 // If mask contains a zero, use it by placing that vector first.
6174 ZeroIdx = I + SystemZ::VectorBytes;
6175 MaskFirst = false;
6176 break;
6177 }
6178 }
6179 if (ZeroIdx != -1) {
6180 SDValue IndexNodes[SystemZ::VectorBytes];
6181 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6182 if (Bytes[I] >= 0) {
6183 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6184 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6185 if (OpNo == ZeroVecIdx)
6186 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
6187 else {
6188 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
6189 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
6190 }
6191 } else
6192 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6193 }
6194 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6195 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
6196 if (MaskFirst)
6197 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
6198 Mask);
6199 else
6200 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
6201 Mask);
6202 }
6203 }
6204
6205 SDValue IndexNodes[SystemZ::VectorBytes];
6206 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6207 if (Bytes[I] >= 0)
6208 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
6209 else
6210 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6211 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6212 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
6213 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
6214}
6215
6216namespace {
6217// Describes a general N-operand vector shuffle.
6218struct GeneralShuffle {
6219 GeneralShuffle(EVT vt)
6220 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
6221 void addUndef();
6222 bool add(SDValue, unsigned);
6223 SDValue getNode(SelectionDAG &, const SDLoc &);
6224 void tryPrepareForUnpack();
6225 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6226 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6227
6228 // The operands of the shuffle.
6230
6231 // Index I is -1 if byte I of the result is undefined. Otherwise the
6232 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6233 // Bytes[I] / SystemZ::VectorBytes.
6235
6236 // The type of the shuffle result.
6237 EVT VT;
6238
6239 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6240 unsigned UnpackFromEltSize;
6241 // True if the final unpack uses the low half.
6242 bool UnpackLow;
6243};
6244} // namespace
6245
6246// Add an extra undefined element to the shuffle.
6247void GeneralShuffle::addUndef() {
6248 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6249 for (unsigned I = 0; I < BytesPerElement; ++I)
6250 Bytes.push_back(-1);
6251}
6252
6253// Add an extra element to the shuffle, taking it from element Elem of Op.
6254// A null Op indicates a vector input whose value will be calculated later;
6255// there is at most one such input per shuffle and it always has the same
6256// type as the result. Aborts and returns false if the source vector elements
6257// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6258// LLVM they become implicitly extended, but this is rare and not optimized.
6259bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6260 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6261
6262 // The source vector can have wider elements than the result,
6263 // either through an explicit TRUNCATE or because of type legalization.
6264 // We want the least significant part.
6265 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6266 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6267
6268 // Return false if the source elements are smaller than their destination
6269 // elements.
6270 if (FromBytesPerElement < BytesPerElement)
6271 return false;
6272
6273 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6274 (FromBytesPerElement - BytesPerElement));
6275
6276 // Look through things like shuffles and bitcasts.
6277 while (Op.getNode()) {
6278 if (Op.getOpcode() == ISD::BITCAST)
6279 Op = Op.getOperand(0);
6280 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6281 // See whether the bytes we need come from a contiguous part of one
6282 // operand.
6284 if (!getVPermMask(Op, OpBytes))
6285 break;
6286 int NewByte;
6287 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6288 break;
6289 if (NewByte < 0) {
6290 addUndef();
6291 return true;
6292 }
6293 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6294 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6295 } else if (Op.isUndef()) {
6296 addUndef();
6297 return true;
6298 } else
6299 break;
6300 }
6301
6302 // Make sure that the source of the extraction is in Ops.
6303 unsigned OpNo = 0;
6304 for (; OpNo < Ops.size(); ++OpNo)
6305 if (Ops[OpNo] == Op)
6306 break;
6307 if (OpNo == Ops.size())
6308 Ops.push_back(Op);
6309
6310 // Add the element to Bytes.
6311 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6312 for (unsigned I = 0; I < BytesPerElement; ++I)
6313 Bytes.push_back(Base + I);
6314
6315 return true;
6316}
6317
6318// Return SDNodes for the completed shuffle.
6319SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6320 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6321
6322 if (Ops.size() == 0)
6323 return DAG.getUNDEF(VT);
6324
6325 // Use a single unpack if possible as the last operation.
6326 tryPrepareForUnpack();
6327
6328 // Make sure that there are at least two shuffle operands.
6329 if (Ops.size() == 1)
6330 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6331
6332 // Create a tree of shuffles, deferring root node until after the loop.
6333 // Try to redistribute the undefined elements of non-root nodes so that
6334 // the non-root shuffles match something like a pack or merge, then adjust
6335 // the parent node's permute vector to compensate for the new order.
6336 // Among other things, this copes with vectors like <2 x i16> that were
6337 // padded with undefined elements during type legalization.
6338 //
6339 // In the best case this redistribution will lead to the whole tree
6340 // using packs and merges. It should rarely be a loss in other cases.
6341 unsigned Stride = 1;
6342 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6343 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6344 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6345
6346 // Create a mask for just these two operands.
6348 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6349 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6350 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6351 if (OpNo == I)
6352 NewBytes[J] = Byte;
6353 else if (OpNo == I + Stride)
6354 NewBytes[J] = SystemZ::VectorBytes + Byte;
6355 else
6356 NewBytes[J] = -1;
6357 }
6358 // See if it would be better to reorganize NewMask to avoid using VPERM.
6360 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6361 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6362 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6363 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6364 if (NewBytes[J] >= 0) {
6365 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6366 "Invalid double permute");
6367 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6368 } else
6369 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6370 }
6371 } else {
6372 // Just use NewBytes on the operands.
6373 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6374 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6375 if (NewBytes[J] >= 0)
6376 Bytes[J] = I * SystemZ::VectorBytes + J;
6377 }
6378 }
6379 }
6380
6381 // Now we just have 2 inputs. Put the second operand in Ops[1].
6382 if (Stride > 1) {
6383 Ops[1] = Ops[Stride];
6384 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6385 if (Bytes[I] >= int(SystemZ::VectorBytes))
6386 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6387 }
6388
6389 // Look for an instruction that can do the permute without resorting
6390 // to VPERM.
6391 unsigned OpNo0, OpNo1;
6392 SDValue Op;
6393 if (unpackWasPrepared() && Ops[1].isUndef())
6394 Op = Ops[0];
6395 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6396 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6397 else
6398 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6399
6400 Op = insertUnpackIfPrepared(DAG, DL, Op);
6401
6402 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6403}
6404
6405#ifndef NDEBUG
6406static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6407 dbgs() << Msg.c_str() << " { ";
6408 for (unsigned I = 0; I < Bytes.size(); I++)
6409 dbgs() << Bytes[I] << " ";
6410 dbgs() << "}\n";
6411}
6412#endif
6413
6414// If the Bytes vector matches an unpack operation, prepare to do the unpack
6415// after all else by removing the zero vector and the effect of the unpack on
6416// Bytes.
6417void GeneralShuffle::tryPrepareForUnpack() {
6418 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6419 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6420 return;
6421
6422 // Only do this if removing the zero vector reduces the depth, otherwise
6423 // the critical path will increase with the final unpack.
6424 if (Ops.size() > 2 &&
6425 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6426 return;
6427
6428 // Find an unpack that would allow removing the zero vector from Ops.
6429 UnpackFromEltSize = 1;
6430 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6431 bool MatchUnpack = true;
6433 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6434 unsigned ToEltSize = UnpackFromEltSize * 2;
6435 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6436 if (!IsZextByte)
6437 SrcBytes.push_back(Bytes[Elt]);
6438 if (Bytes[Elt] != -1) {
6439 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6440 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6441 MatchUnpack = false;
6442 break;
6443 }
6444 }
6445 }
6446 if (MatchUnpack) {
6447 if (Ops.size() == 2) {
6448 // Don't use unpack if a single source operand needs rearrangement.
6449 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6450 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6451 if (SrcBytes[i] == -1)
6452 continue;
6453 if (SrcBytes[i] % 16 != int(i))
6454 CanUseUnpackHigh = false;
6455 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6456 CanUseUnpackLow = false;
6457 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6458 UnpackFromEltSize = UINT_MAX;
6459 return;
6460 }
6461 }
6462 if (!CanUseUnpackHigh)
6463 UnpackLow = true;
6464 }
6465 break;
6466 }
6467 }
6468 if (UnpackFromEltSize > 4)
6469 return;
6470
6471 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6472 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6473 << ".\n";
6474 dumpBytes(Bytes, "Original Bytes vector:"););
6475
6476 // Apply the unpack in reverse to the Bytes array.
6477 unsigned B = 0;
6478 if (UnpackLow) {
6479 while (B < SystemZ::VectorBytes / 2)
6480 Bytes[B++] = -1;
6481 }
6482 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6483 Elt += UnpackFromEltSize;
6484 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6485 Bytes[B] = Bytes[Elt];
6486 }
6487 if (!UnpackLow) {
6488 while (B < SystemZ::VectorBytes)
6489 Bytes[B++] = -1;
6490 }
6491
6492 // Remove the zero vector from Ops
6493 Ops.erase(&Ops[ZeroVecOpNo]);
6494 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6495 if (Bytes[I] >= 0) {
6496 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6497 if (OpNo > ZeroVecOpNo)
6498 Bytes[I] -= SystemZ::VectorBytes;
6499 }
6500
6501 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6502 dbgs() << "\n";);
6503}
6504
6505SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6506 const SDLoc &DL,
6507 SDValue Op) {
6508 if (!unpackWasPrepared())
6509 return Op;
6510 unsigned InBits = UnpackFromEltSize * 8;
6511 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6512 SystemZ::VectorBits / InBits);
6513 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6514 unsigned OutBits = InBits * 2;
6515 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6516 SystemZ::VectorBits / OutBits);
6517 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6518 : SystemZISD::UNPACKL_HIGH,
6519 DL, OutVT, PackedOp);
6520}
6521
6522// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6524 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6525 if (!Op.getOperand(I).isUndef())
6526 return false;
6527 return true;
6528}
6529
6530// Return a vector of type VT that contains Value in the first element.
6531// The other elements don't matter.
6533 SDValue Value) {
6534 // If we have a constant, replicate it to all elements and let the
6535 // BUILD_VECTOR lowering take care of it.
6536 if (Value.getOpcode() == ISD::Constant ||
6537 Value.getOpcode() == ISD::ConstantFP) {
6539 return DAG.getBuildVector(VT, DL, Ops);
6540 }
6541 if (Value.isUndef())
6542 return DAG.getUNDEF(VT);
6543 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6544}
6545
6546// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6547// element 1. Used for cases in which replication is cheap.
6549 SDValue Op0, SDValue Op1) {
6550 if (Op0.isUndef()) {
6551 if (Op1.isUndef())
6552 return DAG.getUNDEF(VT);
6553 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6554 }
6555 if (Op1.isUndef())
6556 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6557 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6558 buildScalarToVector(DAG, DL, VT, Op0),
6559 buildScalarToVector(DAG, DL, VT, Op1));
6560}
6561
6562// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6563// vector for them.
6565 SDValue Op1) {
6566 if (Op0.isUndef() && Op1.isUndef())
6567 return DAG.getUNDEF(MVT::v2i64);
6568 // If one of the two inputs is undefined then replicate the other one,
6569 // in order to avoid using another register unnecessarily.
6570 if (Op0.isUndef())
6571 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6572 else if (Op1.isUndef())
6573 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6574 else {
6575 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6576 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6577 }
6578 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6579}
6580
6581// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6582// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6583// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6584// would benefit from this representation and return it if so.
6586 BuildVectorSDNode *BVN) {
6587 EVT VT = BVN->getValueType(0);
6588 unsigned NumElements = VT.getVectorNumElements();
6589
6590 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6591 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6592 // need a BUILD_VECTOR, add an additional placeholder operand for that
6593 // BUILD_VECTOR and store its operands in ResidueOps.
6594 GeneralShuffle GS(VT);
6596 bool FoundOne = false;
6597 for (unsigned I = 0; I < NumElements; ++I) {
6598 SDValue Op = BVN->getOperand(I);
6599 if (Op.getOpcode() == ISD::TRUNCATE)
6600 Op = Op.getOperand(0);
6601 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6602 Op.getOperand(1).getOpcode() == ISD::Constant) {
6603 unsigned Elem = Op.getConstantOperandVal(1);
6604 if (!GS.add(Op.getOperand(0), Elem))
6605 return SDValue();
6606 FoundOne = true;
6607 } else if (Op.isUndef()) {
6608 GS.addUndef();
6609 } else {
6610 if (!GS.add(SDValue(), ResidueOps.size()))
6611 return SDValue();
6612 ResidueOps.push_back(BVN->getOperand(I));
6613 }
6614 }
6615
6616 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6617 if (!FoundOne)
6618 return SDValue();
6619
6620 // Create the BUILD_VECTOR for the remaining elements, if any.
6621 if (!ResidueOps.empty()) {
6622 while (ResidueOps.size() < NumElements)
6623 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6624 for (auto &Op : GS.Ops) {
6625 if (!Op.getNode()) {
6626 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6627 break;
6628 }
6629 }
6630 }
6631 return GS.getNode(DAG, SDLoc(BVN));
6632}
6633
6634bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6635 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6636 return true;
6637 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6638 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6639 return true;
6640 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6641 return true;
6642 return false;
6643}
6644
6646 unsigned MergedBits, EVT VT, SDValue Op0,
6647 SDValue Op1) {
6648 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6649 SystemZ::VectorBits / MergedBits);
6650 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6651 "Handling full vectors only.");
6652 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6653 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6654 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6655 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6656}
6657
6659 EVT VT, SmallVectorImpl<SDValue> &Elems,
6660 unsigned Pos) {
6661 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6662 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6663 // Avoid unnecessary undefs by reusing the other operand.
6664 if (Op01.isUndef()) {
6665 if (Op23.isUndef())
6666 return Op01;
6667 Op01 = Op23;
6668 } else if (Op23.isUndef())
6669 Op23 = Op01;
6670 // Merging identical replications is a no-op.
6671 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6672 return Op01;
6673 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6674 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6675}
6676
6677// Combine GPR scalar values Elems into a vector of type VT.
6678SDValue
6679SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6680 SmallVectorImpl<SDValue> &Elems) const {
6681 // See whether there is a single replicated value.
6683 unsigned int NumElements = Elems.size();
6684 unsigned int Count = 0;
6685 for (auto Elem : Elems) {
6686 if (!Elem.isUndef()) {
6687 if (!Single.getNode())
6688 Single = Elem;
6689 else if (Elem != Single) {
6690 Single = SDValue();
6691 break;
6692 }
6693 Count += 1;
6694 }
6695 }
6696 // There are three cases here:
6697 //
6698 // - if the only defined element is a loaded one, the best sequence
6699 // is a replicating load.
6700 //
6701 // - otherwise, if the only defined element is an i64 value, we will
6702 // end up with the same VLVGP sequence regardless of whether we short-cut
6703 // for replication or fall through to the later code.
6704 //
6705 // - otherwise, if the only defined element is an i32 or smaller value,
6706 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6707 // This is only a win if the single defined element is used more than once.
6708 // In other cases we're better off using a single VLVGx.
6709 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6710 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6711
6712 // If all elements are loads, use VLREP/VLEs (below).
6713 bool AllLoads = true;
6714 for (auto Elem : Elems)
6715 if (!isVectorElementLoad(Elem)) {
6716 AllLoads = false;
6717 break;
6718 }
6719
6720 // The best way of building a v2i64 from two i64s is to use VLVGP.
6721 if (VT == MVT::v2i64 && !AllLoads)
6722 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6723
6724 // Use a 64-bit merge high to combine two doubles.
6725 if (VT == MVT::v2f64 && !AllLoads)
6726 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6727
6728 // Build v4f32 values directly from the FPRs:
6729 //
6730 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6731 // V V VMRHF
6732 // <ABxx> <CDxx>
6733 // V VMRHG
6734 // <ABCD>
6735 if (VT == MVT::v4f32 && !AllLoads)
6736 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6737
6738 // Same for v8f16.
6739 if (VT == MVT::v8f16 && !AllLoads) {
6740 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6741 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6742 // Avoid unnecessary undefs by reusing the other operand.
6743 if (Op0123.isUndef())
6744 Op0123 = Op4567;
6745 else if (Op4567.isUndef())
6746 Op4567 = Op0123;
6747 // Merging identical replications is a no-op.
6748 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6749 return Op0123;
6750 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6751 }
6752
6753 // Collect the constant terms.
6756
6757 unsigned NumConstants = 0;
6758 for (unsigned I = 0; I < NumElements; ++I) {
6759 SDValue Elem = Elems[I];
6760 if (Elem.getOpcode() == ISD::Constant ||
6761 Elem.getOpcode() == ISD::ConstantFP) {
6762 NumConstants += 1;
6763 Constants[I] = Elem;
6764 Done[I] = true;
6765 }
6766 }
6767 // If there was at least one constant, fill in the other elements of
6768 // Constants with undefs to get a full vector constant and use that
6769 // as the starting point.
6771 SDValue ReplicatedVal;
6772 if (NumConstants > 0) {
6773 for (unsigned I = 0; I < NumElements; ++I)
6774 if (!Constants[I].getNode())
6775 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6776 Result = DAG.getBuildVector(VT, DL, Constants);
6777 } else {
6778 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6779 // avoid a false dependency on any previous contents of the vector
6780 // register.
6781
6782 // Use a VLREP if at least one element is a load. Make sure to replicate
6783 // the load with the most elements having its value.
6784 std::map<const SDNode*, unsigned> UseCounts;
6785 SDNode *LoadMaxUses = nullptr;
6786 for (unsigned I = 0; I < NumElements; ++I)
6787 if (isVectorElementLoad(Elems[I])) {
6788 SDNode *Ld = Elems[I].getNode();
6789 unsigned Count = ++UseCounts[Ld];
6790 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6791 LoadMaxUses = Ld;
6792 }
6793 if (LoadMaxUses != nullptr) {
6794 ReplicatedVal = SDValue(LoadMaxUses, 0);
6795 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6796 } else {
6797 // Try to use VLVGP.
6798 unsigned I1 = NumElements / 2 - 1;
6799 unsigned I2 = NumElements - 1;
6800 bool Def1 = !Elems[I1].isUndef();
6801 bool Def2 = !Elems[I2].isUndef();
6802 if (Def1 || Def2) {
6803 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6804 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6805 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6806 joinDwords(DAG, DL, Elem1, Elem2));
6807 Done[I1] = true;
6808 Done[I2] = true;
6809 } else
6810 Result = DAG.getUNDEF(VT);
6811 }
6812 }
6813
6814 // Use VLVGx to insert the other elements.
6815 for (unsigned I = 0; I < NumElements; ++I)
6816 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6817 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6818 DAG.getConstant(I, DL, MVT::i32));
6819 return Result;
6820}
6821
6822SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6823 SelectionDAG &DAG) const {
6824 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6825 SDLoc DL(Op);
6826 EVT VT = Op.getValueType();
6827
6828 if (BVN->isConstant()) {
6829 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6830 return Op;
6831
6832 // Fall back to loading it from memory.
6833 return SDValue();
6834 }
6835
6836 // See if we should use shuffles to construct the vector from other vectors.
6837 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6838 return Res;
6839
6840 // Detect SCALAR_TO_VECTOR conversions.
6842 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6843
6844 // Otherwise use buildVector to build the vector up from GPRs.
6845 unsigned NumElements = Op.getNumOperands();
6847 for (unsigned I = 0; I < NumElements; ++I)
6848 Ops[I] = Op.getOperand(I);
6849 return buildVector(DAG, DL, VT, Ops);
6850}
6851
6852SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6853 SelectionDAG &DAG) const {
6854 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6855 SDLoc DL(Op);
6856 EVT VT = Op.getValueType();
6857 unsigned NumElements = VT.getVectorNumElements();
6858
6859 if (VSN->isSplat()) {
6860 SDValue Op0 = Op.getOperand(0);
6861 unsigned Index = VSN->getSplatIndex();
6862 assert(Index < VT.getVectorNumElements() &&
6863 "Splat index should be defined and in first operand");
6864 // See whether the value we're splatting is directly available as a scalar.
6865 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6867 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6868 // Otherwise keep it as a vector-to-vector operation.
6869 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6870 DAG.getTargetConstant(Index, DL, MVT::i32));
6871 }
6872
6873 GeneralShuffle GS(VT);
6874 for (unsigned I = 0; I < NumElements; ++I) {
6875 int Elt = VSN->getMaskElt(I);
6876 if (Elt < 0)
6877 GS.addUndef();
6878 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6879 unsigned(Elt) % NumElements))
6880 return SDValue();
6881 }
6882 return GS.getNode(DAG, SDLoc(VSN));
6883}
6884
6885SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6886 SelectionDAG &DAG) const {
6887 SDLoc DL(Op);
6888 // Just insert the scalar into element 0 of an undefined vector.
6889 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6890 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6891 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6892}
6893
6894// Shift the lower 2 bytes of Op to the left in order to insert into the
6895// upper 2 bytes of the FP register.
6897 assert(Op.getSimpleValueType() == MVT::i64 &&
6898 "Expexted to convert i64 to f16.");
6899 SDLoc DL(Op);
6900 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6901 DAG.getConstant(48, DL, MVT::i64));
6902 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6903 SDValue F16Val =
6904 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6905 return F16Val;
6906}
6907
6908// Extract Op into GPR and shift the 2 f16 bytes to the right.
6910 assert(Op.getSimpleValueType() == MVT::f16 &&
6911 "Expected to convert f16 to i64.");
6912 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6913 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6914 SDValue(U32, 0), Op);
6915 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6916 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6917 DAG.getConstant(48, DL, MVT::i32));
6918 return Shft;
6919}
6920
6922 auto *CIdx = dyn_cast<ConstantSDNode>(Idx);
6923 return CIdx && CIdx->getZExtValue() < VecVT.getVectorNumElements();
6924}
6925
6926SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6927 SelectionDAG &DAG) const {
6928 // Handle insertions of floating-point values.
6929 SDLoc DL(Op);
6930 SDValue Op0 = Op.getOperand(0);
6931 SDValue Op1 = Op.getOperand(1);
6932 SDValue Op2 = Op.getOperand(2);
6933 EVT VT = Op.getValueType();
6934
6935 // A constant index selects a GR128 subregister.
6936 if (!Subtarget.hasVector())
6937 return isInBoundsConstantVectorIndex(VT, Op2) ? Op : SDValue();
6938
6939 // Insertions into constant indices of a v2f64 can be done using VPDI.
6940 // However, if the inserted value is a bitcast or a constant then it's
6941 // better to use GPRs, as below.
6942 if (VT == MVT::v2f64 && Op1.getOpcode() != ISD::BITCAST &&
6943 Op1.getOpcode() != ISD::ConstantFP &&
6945 return Op;
6946
6947 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6948 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6949 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6950 SDValue IntOp1 =
6951 VT == MVT::v8f16
6952 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6953 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6954 SDValue Res =
6955 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6956 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6957 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6958}
6959
6960SDValue
6961SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6962 SelectionDAG &DAG) const {
6963 // Handle extractions of floating-point values.
6964 SDLoc DL(Op);
6965 SDValue Op0 = Op.getOperand(0);
6966 SDValue Op1 = Op.getOperand(1);
6967 EVT VT = Op.getValueType();
6968 EVT VecVT = Op0.getValueType();
6969
6970 // Extractions of constant indices can be done directly.
6971 if (isInBoundsConstantVectorIndex(VecVT, Op1))
6972 return Op;
6973
6974 if (!Subtarget.hasVector())
6975 return SDValue();
6976
6977 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6978 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6979 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6980 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6981 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6982 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6983 if (VT == MVT::f16)
6984 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6985 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6986}
6987
6988SDValue SystemZTargetLowering::
6989lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6990 SDValue PackedOp = Op.getOperand(0);
6991 EVT OutVT = Op.getValueType();
6992 EVT InVT = PackedOp.getValueType();
6993 unsigned ToBits = OutVT.getScalarSizeInBits();
6994 unsigned FromBits = InVT.getScalarSizeInBits();
6995 unsigned StartOffset = 0;
6996
6997 // If the input is a VECTOR_SHUFFLE, there are a number of important
6998 // cases where we can directly implement the sign-extension of the
6999 // original input lanes of the shuffle.
7000 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
7001 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
7002 ArrayRef<int> ShuffleMask = SVN->getMask();
7003 int OutNumElts = OutVT.getVectorNumElements();
7004
7005 // Recognize the special case where the sign-extension can be done
7006 // by the VSEG instruction. Handled via the default expander.
7007 if (ToBits == 64 && OutNumElts == 2) {
7008 int NumElem = ToBits / FromBits;
7009 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
7010 return SDValue();
7011 }
7012
7013 // Recognize the special case where we can fold the shuffle by
7014 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
7015 int StartOffsetCandidate = -1;
7016 for (int Elt = 0; Elt < OutNumElts; Elt++) {
7017 if (ShuffleMask[Elt] == -1)
7018 continue;
7019 if (ShuffleMask[Elt] % OutNumElts == Elt) {
7020 if (StartOffsetCandidate == -1)
7021 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
7022 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
7023 continue;
7024 }
7025 StartOffsetCandidate = -1;
7026 break;
7027 }
7028 if (StartOffsetCandidate != -1) {
7029 // The mask indexes the concatenation of both shuffle operands: an offset
7030 // past the first operand's lanes selects lanes of the second.
7031 unsigned InNumElts = InVT.getVectorNumElements();
7032 unsigned Offset = StartOffsetCandidate;
7033 unsigned OpNo = Offset >= InNumElts ? 1 : 0;
7034 StartOffset = Offset - OpNo * InNumElts;
7035 PackedOp = PackedOp.getOperand(OpNo);
7036 }
7037 }
7038
7039 do {
7040 FromBits *= 2;
7041 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
7042 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
7043 unsigned Opcode = SystemZISD::UNPACK_HIGH;
7044 if (StartOffset >= OutNumElts) {
7045 Opcode = SystemZISD::UNPACK_LOW;
7046 StartOffset -= OutNumElts;
7047 }
7048 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
7049 } while (FromBits != ToBits);
7050 return PackedOp;
7051}
7052
7053// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
7054SDValue SystemZTargetLowering::
7055lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
7056 SDValue PackedOp = Op.getOperand(0);
7057 SDLoc DL(Op);
7058 EVT OutVT = Op.getValueType();
7059 EVT InVT = PackedOp.getValueType();
7060 unsigned InNumElts = InVT.getVectorNumElements();
7061 unsigned OutNumElts = OutVT.getVectorNumElements();
7062 unsigned NumInPerOut = InNumElts / OutNumElts;
7063
7064 SDValue ZeroVec =
7065 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
7066
7067 SmallVector<int, 16> Mask(InNumElts);
7068 unsigned ZeroVecElt = InNumElts;
7069 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
7070 unsigned MaskElt = PackedElt * NumInPerOut;
7071 unsigned End = MaskElt + NumInPerOut - 1;
7072 for (; MaskElt < End; MaskElt++)
7073 Mask[MaskElt] = ZeroVecElt++;
7074 Mask[MaskElt] = PackedElt;
7075 }
7076 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
7077 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
7078}
7079
7080SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
7081 unsigned ByScalar) const {
7082 // Look for cases where a vector shift can use the *_BY_SCALAR form.
7083 SDValue Op0 = Op.getOperand(0);
7084 SDValue Op1 = Op.getOperand(1);
7085 SDLoc DL(Op);
7086 EVT VT = Op.getValueType();
7087 unsigned ElemBitSize = VT.getScalarSizeInBits();
7088
7089 // See whether the shift vector is a splat represented as BUILD_VECTOR.
7090 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
7091 APInt SplatBits, SplatUndef;
7092 unsigned SplatBitSize;
7093 bool HasAnyUndefs;
7094 // Check for constant splats. Use ElemBitSize as the minimum element
7095 // width and reject splats that need wider elements.
7096 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
7097 ElemBitSize, true) &&
7098 SplatBitSize == ElemBitSize) {
7099 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
7100 DL, MVT::i32);
7101 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7102 }
7103 // Check for variable splats.
7104 BitVector UndefElements;
7105 SDValue Splat = BVN->getSplatValue(&UndefElements);
7106 if (Splat) {
7107 // Since i32 is the smallest legal type, we either need a no-op
7108 // or a truncation.
7109 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
7110 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7111 }
7112 }
7113
7114 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
7115 // and the shift amount is directly available in a GPR.
7116 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
7117 if (VSN->isSplat()) {
7118 SDValue VSNOp0 = VSN->getOperand(0);
7119 unsigned Index = VSN->getSplatIndex();
7120 assert(Index < VT.getVectorNumElements() &&
7121 "Splat index should be defined and in first operand");
7122 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
7123 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
7124 // Since i32 is the smallest legal type, we either need a no-op
7125 // or a truncation.
7126 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
7127 VSNOp0.getOperand(Index));
7128 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7129 }
7130 }
7131 }
7132
7133 // Otherwise just treat the current form as legal.
7134 return Op;
7135}
7136
7137SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
7138 SDLoc DL(Op);
7139
7140 // i128 FSHL with a constant amount that is a multiple of 8 can be
7141 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7142 // facility, FSHL with a constant amount less than 8 can be implemented
7143 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
7144 // combination of the two.
7145 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7146 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7147 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7148 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7149 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7150 if (ShiftAmt > 120) {
7151 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
7152 // SHR_DOUBLE_BIT emits fewer instructions.
7153 SDValue Val =
7154 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7155 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7156 return DAG.getBitcast(MVT::i128, Val);
7157 }
7158 SmallVector<int, 16> Mask(16);
7159 for (unsigned Elt = 0; Elt < 16; Elt++)
7160 Mask[Elt] = (ShiftAmt >> 3) + Elt;
7161 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7162 if ((ShiftAmt & 7) == 0)
7163 return DAG.getBitcast(MVT::i128, Shuf1);
7164 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
7165 SDValue Val =
7166 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
7167 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7168 return DAG.getBitcast(MVT::i128, Val);
7169 }
7170 }
7171
7172 return SDValue();
7173}
7174
7175SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
7176 SDLoc DL(Op);
7177
7178 // i128 FSHR with a constant amount that is a multiple of 8 can be
7179 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7180 // facility, FSHR with a constant amount less than 8 can be implemented
7181 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
7182 // combination of the two.
7183 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7184 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7185 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7186 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7187 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7188 if (ShiftAmt > 120) {
7189 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
7190 // SHL_DOUBLE_BIT emits fewer instructions.
7191 SDValue Val =
7192 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7193 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7194 return DAG.getBitcast(MVT::i128, Val);
7195 }
7196 SmallVector<int, 16> Mask(16);
7197 for (unsigned Elt = 0; Elt < 16; Elt++)
7198 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
7199 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7200 if ((ShiftAmt & 7) == 0)
7201 return DAG.getBitcast(MVT::i128, Shuf1);
7202 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
7203 SDValue Val =
7204 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
7205 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7206 return DAG.getBitcast(MVT::i128, Val);
7207 }
7208 }
7209
7210 return SDValue();
7211}
7212
7214 SDLoc DL(Op);
7215 SDValue Src = Op.getOperand(0);
7216 MVT DstVT = Op.getSimpleValueType();
7217
7219 unsigned SrcAS = N->getSrcAddressSpace();
7220
7221 assert(SrcAS != N->getDestAddressSpace() &&
7222 "addrspacecast must be between different address spaces");
7223
7224 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
7225 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
7226 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
7227 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
7228 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7229 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7230 } else if (DstVT == MVT::i32) {
7231 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7232 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7233 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7234 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7235 } else {
7236 report_fatal_error("Bad address space in addrspacecast");
7237 }
7238 return Op;
7239}
7240
7241SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7242 SelectionDAG &DAG) const {
7243 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7244 if (In.getSimpleValueType() != MVT::f16)
7245 return Op; // Legal
7246 return SDValue(); // Let legalizer emit the libcall.
7247}
7248
7250 MVT VT, SDValue Arg, SDLoc DL,
7251 SDValue Chain, bool IsStrict) const {
7252 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7253 MakeLibCallOptions CallOptions;
7254 SDValue Result;
7255 std::tie(Result, Chain) =
7256 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7257 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7258}
7259
7260SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7261 SelectionDAG &DAG) const {
7262 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7263 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7264 bool IsStrict = Op->isStrictFPOpcode();
7265 SDLoc DL(Op);
7266 MVT VT = Op.getSimpleValueType();
7267 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7268 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7269 EVT InVT = InOp.getValueType();
7270
7271 // FP to unsigned is not directly supported on z10. Promoting an i32
7272 // result to (signed) i64 doesn't generate an inexact condition (fp
7273 // exception) for values that are outside the i32 range but in the i64
7274 // range, so use the default expansion.
7275 if (!Subtarget.hasFPExtension() && !IsSigned)
7276 // Expand i32/i64. F16 values will be recognized to fit and extended.
7277 return SDValue();
7278
7279 // Conversion from f16 is done via f32.
7280 if (InOp.getSimpleValueType() == MVT::f16) {
7282 LowerOperationWrapper(Op.getNode(), Results, DAG);
7283 return DAG.getMergeValues(Results, DL);
7284 }
7285
7286 if (VT == MVT::i128) {
7287 RTLIB::Libcall LC =
7288 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7289 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7290 }
7291
7292 return Op; // Legal
7293}
7294
7295SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7296 SelectionDAG &DAG) const {
7297 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7298 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7299 bool IsStrict = Op->isStrictFPOpcode();
7300 SDLoc DL(Op);
7301 MVT VT = Op.getSimpleValueType();
7302 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7303 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7304 EVT InVT = InOp.getValueType();
7305
7306 // Conversion to f16 is done via f32.
7307 if (VT == MVT::f16) {
7309 LowerOperationWrapper(Op.getNode(), Results, DAG);
7310 return DAG.getMergeValues(Results, DL);
7311 }
7312
7313 // Unsigned to fp is not directly supported on z10.
7314 if (!Subtarget.hasFPExtension() && !IsSigned)
7315 return SDValue(); // Expand i64.
7316
7317 if (InVT == MVT::i128) {
7318 RTLIB::Libcall LC =
7319 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7320 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7321 }
7322
7323 return Op; // Legal
7324}
7325
7326// Lower an f16 LOAD in case of no vector support.
7327SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7328 SelectionDAG &DAG) const {
7329 EVT RegVT = Op.getValueType();
7330 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7331 (void)RegVT;
7332
7333 // Load as integer.
7334 SDLoc DL(Op);
7335 SDValue NewLd;
7336 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7337 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7338 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7339 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7340 AtomicLd->getMemOperand());
7341 } else {
7342 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7343 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7344 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7345 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7346 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7347 }
7348 SDValue F16Val = convertToF16(NewLd, DAG);
7349 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7350}
7351
7352// Lower an f16 STORE in case of no vector support.
7353SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7354 SelectionDAG &DAG) const {
7355 SDLoc DL(Op);
7356 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7357
7358 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7359 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7360 Shft, AtomicSt->getBasePtr(),
7361 AtomicSt->getMemOperand());
7362
7363 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7364 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7365 St->getMemOperand());
7366}
7367
7368SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7369 SelectionDAG &DAG) const {
7370 SDLoc DL(Op);
7371 MVT ResultVT = Op.getSimpleValueType();
7372 SDValue Arg = Op.getOperand(0);
7373 unsigned Check = Op.getConstantOperandVal(1);
7374
7375 unsigned TDCMask = 0;
7376 if (Check & fcSNan)
7378 if (Check & fcQNan)
7380 if (Check & fcPosInf)
7382 if (Check & fcNegInf)
7384 if (Check & fcPosNormal)
7386 if (Check & fcNegNormal)
7388 if (Check & fcPosSubnormal)
7390 if (Check & fcNegSubnormal)
7392 if (Check & fcPosZero)
7393 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7394 if (Check & fcNegZero)
7395 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7396 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7397
7398 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7399 return getCCResult(DAG, Intr);
7400}
7401
7402SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7403 SelectionDAG &DAG) const {
7404 SDLoc DL(Op);
7405 SDValue Chain = Op.getOperand(0);
7406
7407 // STCKF only supports a memory operand, so we have to use a temporary.
7408 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7409 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7410 MachinePointerInfo MPI =
7412
7413 // Use STCFK to store the TOD clock into the temporary.
7414 SDValue StoreOps[] = {Chain, StackPtr};
7415 Chain = DAG.getMemIntrinsicNode(
7416 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7417 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7418
7419 // And read it back from there.
7420 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7421}
7422
7424 SelectionDAG &DAG) const {
7425 switch (Op.getOpcode()) {
7426 case ISD::FRAMEADDR:
7427 return lowerFRAMEADDR(Op, DAG);
7428 case ISD::RETURNADDR:
7429 return lowerRETURNADDR(Op, DAG);
7430 case ISD::BR_CC:
7431 return lowerBR_CC(Op, DAG);
7432 case ISD::SELECT_CC:
7433 return lowerSELECT_CC(Op, DAG);
7434 case ISD::SETCC:
7435 return lowerSETCC(Op, DAG);
7436 case ISD::STRICT_FSETCC:
7437 return lowerSTRICT_FSETCC(Op, DAG, false);
7439 return lowerSTRICT_FSETCC(Op, DAG, true);
7440 case ISD::GlobalAddress:
7441 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7443 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7444 case ISD::BlockAddress:
7445 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7446 case ISD::JumpTable:
7447 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7448 case ISD::ConstantPool:
7449 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7450 case ISD::BITCAST:
7451 return lowerBITCAST(Op, DAG);
7452 case ISD::VASTART:
7453 return lowerVASTART(Op, DAG);
7454 case ISD::VACOPY:
7455 return lowerVACOPY(Op, DAG);
7457 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7459 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7460 case ISD::MULHS:
7461 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7462 case ISD::MULHU:
7463 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7464 case ISD::SMUL_LOHI:
7465 return lowerSMUL_LOHI(Op, DAG);
7466 case ISD::UMUL_LOHI:
7467 return lowerUMUL_LOHI(Op, DAG);
7468 case ISD::SDIVREM:
7469 return lowerSDIVREM(Op, DAG);
7470 case ISD::UDIVREM:
7471 return lowerUDIVREM(Op, DAG);
7472 case ISD::SADDO:
7473 case ISD::SSUBO:
7474 case ISD::SMULO:
7475 case ISD::UADDO:
7476 case ISD::USUBO:
7477 return lowerXALUO(Op, DAG);
7478 case ISD::UADDO_CARRY:
7479 case ISD::USUBO_CARRY:
7480 return lowerUADDSUBO_CARRY(Op, DAG);
7481 case ISD::OR:
7482 return lowerOR(Op, DAG);
7483 case ISD::CTPOP:
7484 return lowerCTPOP(Op, DAG);
7485 case ISD::PDEP:
7486 return lowerPDEP(Op, DAG);
7487 case ISD::PEXT:
7488 return lowerPEXT(Op, DAG);
7489 case ISD::VECREDUCE_ADD:
7490 return lowerVECREDUCE_ADD(Op, DAG);
7491 case ISD::ATOMIC_FENCE:
7492 return lowerATOMIC_FENCE(Op, DAG);
7493 case ISD::ATOMIC_STORE:
7494 return lowerATOMIC_STORE(Op, DAG);
7495 case ISD::ATOMIC_LOAD:
7496 return lowerATOMIC_LOAD(Op, DAG);
7498 return lowerATOMIC_LOAD_SUB(Op, DAG);
7500 return lowerATOMIC_CMP_SWAP(Op, DAG);
7501 case ISD::STACKSAVE:
7502 return lowerSTACKSAVE(Op, DAG);
7503 case ISD::STACKRESTORE:
7504 return lowerSTACKRESTORE(Op, DAG);
7505 case ISD::PREFETCH:
7506 return lowerPREFETCH(Op, DAG);
7508 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7510 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7511 case ISD::BUILD_VECTOR:
7512 return lowerBUILD_VECTOR(Op, DAG);
7514 return lowerVECTOR_SHUFFLE(Op, DAG);
7516 return lowerSCALAR_TO_VECTOR(Op, DAG);
7518 return lowerINSERT_VECTOR_ELT(Op, DAG);
7520 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7522 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7524 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7525 case ISD::SHL:
7526 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7527 case ISD::SRL:
7528 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7529 case ISD::SRA:
7530 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7531 case ISD::ADDRSPACECAST:
7532 return lowerAddrSpaceCast(Op, DAG);
7533 case ISD::ROTL:
7534 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7535 case ISD::FSHL:
7536 return lowerFSHL(Op, DAG);
7537 case ISD::FSHR:
7538 return lowerFSHR(Op, DAG);
7539 case ISD::FP_EXTEND:
7541 return lowerFP_EXTEND(Op, DAG);
7542 case ISD::FP_TO_UINT:
7543 case ISD::FP_TO_SINT:
7546 return lower_FP_TO_INT(Op, DAG);
7547 case ISD::UINT_TO_FP:
7548 case ISD::SINT_TO_FP:
7551 return lower_INT_TO_FP(Op, DAG);
7552 case ISD::LOAD:
7553 return lowerLoadF16(Op, DAG);
7554 case ISD::STORE:
7555 return lowerStoreF16(Op, DAG);
7556 case ISD::IS_FPCLASS:
7557 return lowerIS_FPCLASS(Op, DAG);
7558 case ISD::GET_ROUNDING:
7559 return lowerGET_ROUNDING(Op, DAG);
7561 return lowerREADCYCLECOUNTER(Op, DAG);
7564 // These operations are legal on our platform, but we cannot actually
7565 // set the operation action to Legal as common code would treat this
7566 // as equivalent to Expand. Instead, we keep the operation action to
7567 // Custom and just leave them unchanged here.
7568 return Op;
7569
7570 default:
7571 llvm_unreachable("Unexpected node to lower");
7572 }
7573}
7574
7576 const SDLoc &SL) {
7577 // If i128 is legal, just use a normal bitcast.
7578 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7579 return DAG.getBitcast(MVT::f128, Src);
7580
7581 // Otherwise, f128 must live in FP128, so do a partwise move.
7583 &SystemZ::FP128BitRegClass);
7584
7585 SDValue Hi, Lo;
7586 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7587
7588 Hi = DAG.getBitcast(MVT::f64, Hi);
7589 Lo = DAG.getBitcast(MVT::f64, Lo);
7590
7591 SDNode *Pair = DAG.getMachineNode(
7592 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7593 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7594 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7595 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7596 return SDValue(Pair, 0);
7597}
7598
7600 const SDLoc &SL) {
7601 // If i128 is legal, just use a normal bitcast.
7602 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7603 return DAG.getBitcast(MVT::i128, Src);
7604
7605 // Otherwise, f128 must live in FP128, so do a partwise move.
7607 &SystemZ::FP128BitRegClass);
7608
7609 SDValue LoFP =
7610 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7611 SDValue HiFP =
7612 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7613 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7614 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7615
7616 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7617}
7618
7619// Lower operations with invalid operand or result types.
7620void
7623 SelectionDAG &DAG) const {
7624 switch (N->getOpcode()) {
7625 case ISD::ATOMIC_LOAD: {
7626 SDLoc DL(N);
7627 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7628 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7629 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7630 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7631 DL, Tys, Ops, MVT::i128, MMO);
7632
7633 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7634 if (N->getValueType(0) == MVT::f128)
7635 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7636 Results.push_back(Lowered);
7637 Results.push_back(Res.getValue(1));
7638 break;
7639 }
7640 case ISD::ATOMIC_STORE: {
7641 SDLoc DL(N);
7642 SDVTList Tys = DAG.getVTList(MVT::Other);
7643 SDValue Val = N->getOperand(1);
7644 if (Val.getValueType() == MVT::f128)
7645 Val = expandBitCastF128ToI128(DAG, Val, DL);
7646 Val = lowerI128ToGR128(DAG, Val);
7647
7648 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7649 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7650 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7651 DL, Tys, Ops, MVT::i128, MMO);
7652 // We have to enforce sequential consistency by performing a
7653 // serialization operation after the store.
7654 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7656 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7657 MVT::Other, Res), 0);
7658 Results.push_back(Res);
7659 break;
7660 }
7662 SDLoc DL(N);
7663 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
7664 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7665 lowerI128ToGR128(DAG, N->getOperand(2)),
7666 lowerI128ToGR128(DAG, N->getOperand(3)) };
7667 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7668 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7669 DL, Tys, Ops, MVT::i128, MMO);
7670 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7672 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7673 Results.push_back(lowerGR128ToI128(DAG, Res));
7674 Results.push_back(Success);
7675 Results.push_back(Res.getValue(2));
7676 break;
7677 }
7678 case ISD::BITCAST: {
7679 if (useSoftFloat())
7680 return;
7681 SDLoc DL(N);
7682 SDValue Src = N->getOperand(0);
7683 EVT SrcVT = Src.getValueType();
7684 EVT ResVT = N->getValueType(0);
7685 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7686 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7687 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7688 if (Subtarget.hasVector()) {
7689 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7690 Results.push_back(SDValue(
7691 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7692 } else {
7693 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7694 Results.push_back(convertToF16(In64, DAG));
7695 }
7696 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7697 SDValue ExtractedVal =
7698 Subtarget.hasVector()
7699 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7700 0)
7701 : convertFromF16(Src, DL, DAG);
7702 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7703 }
7704 break;
7705 }
7706 case ISD::UINT_TO_FP:
7707 case ISD::SINT_TO_FP:
7710 if (useSoftFloat())
7711 return;
7712 bool IsStrict = N->isStrictFPOpcode();
7713 SDLoc DL(N);
7714 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7715 EVT ResVT = N->getValueType(0);
7716 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7717 if (ResVT == MVT::f16) {
7718 if (!IsStrict) {
7719 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7720 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7721 } else {
7722 SDValue OpF32 =
7723 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7724 {Chain, InOp});
7725 SDValue F16Res;
7726 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7727 OpF32, OpF32.getValue(1), DL, MVT::f16);
7728 Results.push_back(F16Res);
7729 Results.push_back(Chain);
7730 }
7731 }
7732 break;
7733 }
7734 case ISD::FP_TO_UINT:
7735 case ISD::FP_TO_SINT:
7738 if (useSoftFloat())
7739 return;
7740 bool IsStrict = N->isStrictFPOpcode();
7741 SDLoc DL(N);
7742 EVT ResVT = N->getValueType(0);
7743 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7744 EVT InVT = InOp->getValueType(0);
7745 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7746 if (InVT == MVT::f16) {
7747 if (!IsStrict) {
7748 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7749 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7750 } else {
7751 SDValue InF32;
7752 std::tie(InF32, Chain) =
7753 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7754 SDValue OpF32 =
7755 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7756 {Chain, InF32});
7757 Results.push_back(OpF32);
7758 Results.push_back(OpF32.getValue(1));
7759 }
7760 }
7761 break;
7762 }
7763 case ISD::ATOMIC_SWAP:
7764 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_SWAPW);
7765 break;
7767 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7768 break;
7770 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_SUB);
7771 break;
7773 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_AND);
7774 break;
7776 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_OR);
7777 break;
7779 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7780 break;
7782 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7783 break;
7785 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7786 break;
7788 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7789 break;
7791 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7792 break;
7794 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7795 break;
7796 default:
7797 llvm_unreachable("Unexpected node to lower");
7798 }
7799}
7800
7801void
7807
7808// Return true if VT is a vector whose elements are a whole number of bytes
7809// in width. Also check for presence of vector support.
7810bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7811 if (!Subtarget.hasVector())
7812 return false;
7813
7814 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7815}
7816
7817// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7818// producing a result of type ResVT. Op is a possibly bitcast version
7819// of the input vector and Index is the index (based on type VecVT) that
7820// should be extracted. Return the new extraction if a simplification
7821// was possible or if Force is true.
7822SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7823 EVT VecVT, SDValue Op,
7824 unsigned Index,
7825 DAGCombinerInfo &DCI,
7826 bool Force) const {
7827 SelectionDAG &DAG = DCI.DAG;
7828
7829 // The number of bytes being extracted.
7830 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7831
7832 for (;;) {
7833 unsigned Opcode = Op.getOpcode();
7834 if (Opcode == ISD::BITCAST)
7835 // Look through bitcasts.
7836 Op = Op.getOperand(0);
7837 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7838 canTreatAsByteVector(Op.getValueType())) {
7839 // Get a VPERM-like permute mask and see whether the bytes covered
7840 // by the extracted element are a contiguous sequence from one
7841 // source operand.
7843 if (!getVPermMask(Op, Bytes))
7844 break;
7845 int First;
7846 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7847 BytesPerElement, First))
7848 break;
7849 if (First < 0)
7850 return DAG.getUNDEF(ResVT);
7851 // Make sure the contiguous sequence starts at a multiple of the
7852 // original element size.
7853 unsigned Byte = unsigned(First) % Bytes.size();
7854 if (Byte % BytesPerElement != 0)
7855 break;
7856 // We can get the extracted value directly from an input.
7857 Index = Byte / BytesPerElement;
7858 Op = Op.getOperand(unsigned(First) / Bytes.size());
7859 Force = true;
7860 } else if (Opcode == ISD::BUILD_VECTOR &&
7861 canTreatAsByteVector(Op.getValueType())) {
7862 // We can only optimize this case if the BUILD_VECTOR elements are
7863 // at least as wide as the extracted value.
7864 EVT OpVT = Op.getValueType();
7865 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7866 if (OpBytesPerElement < BytesPerElement)
7867 break;
7868 // Make sure that the least-significant bit of the extracted value
7869 // is the least significant bit of an input.
7870 unsigned End = (Index + 1) * BytesPerElement;
7871 if (End % OpBytesPerElement != 0)
7872 break;
7873 // We're extracting the low part of one operand of the BUILD_VECTOR.
7874 Op = Op.getOperand(End / OpBytesPerElement - 1);
7875 EVT ResIntVT = MVT::getIntegerVT(ResVT.getSizeInBits());
7876 if (!isTypeLegal(ResIntVT))
7877 break;
7878 if (!Op.getValueType().isInteger()) {
7879 EVT OpIntVT = MVT::getIntegerVT(Op.getValueSizeInBits());
7880 if (!isTypeLegal(OpIntVT))
7881 break;
7882 Op = DAG.getNode(ISD::BITCAST, DL, OpIntVT, Op);
7883 DCI.AddToWorklist(Op.getNode());
7884 }
7885 Op = DAG.getNode(ISD::TRUNCATE, DL, ResIntVT, Op);
7886 if (ResIntVT != ResVT) {
7887 DCI.AddToWorklist(Op.getNode());
7888 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7889 }
7890 return Op;
7891 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7893 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7894 canTreatAsByteVector(Op.getValueType()) &&
7895 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7896 // Make sure that only the unextended bits are significant.
7897 EVT ExtVT = Op.getValueType();
7898 EVT OpVT = Op.getOperand(0).getValueType();
7899 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7900 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7901 unsigned Byte = Index * BytesPerElement;
7902 unsigned SubByte = Byte % ExtBytesPerElement;
7903 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7904 if (SubByte < MinSubByte ||
7905 SubByte + BytesPerElement > ExtBytesPerElement)
7906 break;
7907 // Get the byte offset of the unextended element
7908 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7909 // ...then add the byte offset relative to that element.
7910 Byte += SubByte - MinSubByte;
7911 if (Byte % BytesPerElement != 0)
7912 break;
7913 Op = Op.getOperand(0);
7914 Index = Byte / BytesPerElement;
7915 Force = true;
7916 } else
7917 break;
7918 }
7919 if (Force) {
7920 if (Op.getValueType() != VecVT) {
7921 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7922 DCI.AddToWorklist(Op.getNode());
7923 }
7924 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7925 DAG.getConstant(Index, DL, MVT::i32));
7926 }
7927 return SDValue();
7928}
7929
7930// Optimize vector operations in scalar value Op on the basis that Op
7931// is truncated to TruncVT.
7932SDValue SystemZTargetLowering::combineTruncateExtract(
7933 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7934 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7935 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7936 // of type TruncVT.
7937 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7938 TruncVT.getSizeInBits() % 8 == 0) {
7939 SDValue Vec = Op.getOperand(0);
7940 EVT VecVT = Vec.getValueType();
7941 if (canTreatAsByteVector(VecVT)) {
7942 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7943 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7944 unsigned TruncBytes = TruncVT.getStoreSize();
7945 if (BytesPerElement % TruncBytes == 0) {
7946 // Calculate the value of Y' in the above description. We are
7947 // splitting the original elements into Scale equal-sized pieces
7948 // and for truncation purposes want the last (least-significant)
7949 // of these pieces for IndexN. This is easiest to do by calculating
7950 // the start index of the following element and then subtracting 1.
7951 unsigned Scale = BytesPerElement / TruncBytes;
7952 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7953
7954 // Defer the creation of the bitcast from X to combineExtract,
7955 // which might be able to optimize the extraction.
7956 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7957 MVT::getIntegerVT(TruncBytes * 8),
7958 VecVT.getStoreSize() / TruncBytes);
7959 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7960 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7961 }
7962 }
7963 }
7964 }
7965 return SDValue();
7966}
7967
7968SDValue SystemZTargetLowering::combineZERO_EXTEND(
7969 SDNode *N, DAGCombinerInfo &DCI) const {
7970 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7971 SelectionDAG &DAG = DCI.DAG;
7972 SDValue N0 = N->getOperand(0);
7973 EVT VT = N->getValueType(0);
7974 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7975 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7976 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7977 if (TrueOp && FalseOp) {
7978 SDLoc DL(N0);
7979 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7980 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7981 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7982 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7983 // If N0 has multiple uses, change other uses as well.
7984 if (!N0.hasOneUse()) {
7985 SDValue TruncSelect =
7986 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7987 DCI.CombineTo(N0.getNode(), TruncSelect);
7988 }
7989 return NewSelect;
7990 }
7991 }
7992 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7993 // of the result is smaller than the size of X and all the truncated bits
7994 // of X are already zero.
7995 if (N0.getOpcode() == ISD::XOR &&
7996 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7997 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7998 N0.getOperand(1).getOpcode() == ISD::Constant) {
7999 SDValue X = N0.getOperand(0).getOperand(0);
8000 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
8001 KnownBits Known = DAG.computeKnownBits(X);
8002 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
8003 N0.getValueSizeInBits(),
8004 VT.getSizeInBits());
8005 if (TruncatedBits.isSubsetOf(Known.Zero)) {
8006 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8007 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
8008 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
8009 X, DAG.getConstant(Mask, SDLoc(N0), VT));
8010 }
8011 }
8012 }
8013 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
8014 // and VECTOR ADD COMPUTE CARRY for i128:
8015 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
8016 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
8017 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
8018 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
8019 // For vector types, these patterns are recognized in the .td file.
8020 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
8021 N0.getOperand(0).getValueType() == VT) {
8022 SDValue Op0 = N0.getOperand(0);
8023 SDValue Op1 = N0.getOperand(1);
8024 const ISD::CondCode CC = N0.getOperandCondCode(2);
8025 switch (CC) {
8026 case ISD::SETULE:
8027 std::swap(Op0, Op1);
8028 [[fallthrough]];
8029 case ISD::SETUGE:
8030 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
8031 case ISD::SETUGT:
8032 std::swap(Op0, Op1);
8033 [[fallthrough]];
8034 case ISD::SETULT:
8035 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
8036 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
8037 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
8038 Op0->getOperand(1));
8039 break;
8040 default:
8041 break;
8042 }
8043 }
8044
8045 return SDValue();
8046}
8047
8048SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
8049 SDNode *N, DAGCombinerInfo &DCI) const {
8050 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
8051 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
8052 // into (select_cc LHS, RHS, -1, 0, COND)
8053 SelectionDAG &DAG = DCI.DAG;
8054 SDValue N0 = N->getOperand(0);
8055 EVT VT = N->getValueType(0);
8056 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8057 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
8058 N0 = N0.getOperand(0);
8059 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
8060 SDLoc DL(N0);
8061 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
8062 DAG.getAllOnesConstant(DL, VT),
8063 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
8064 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8065 }
8066 return SDValue();
8067}
8068
8069SDValue SystemZTargetLowering::combineSIGN_EXTEND(
8070 SDNode *N, DAGCombinerInfo &DCI) const {
8071 // Convert (sext (ashr (shl X, C1), C2)) to
8072 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
8073 // cheap as narrower ones.
8074 SelectionDAG &DAG = DCI.DAG;
8075 SDValue N0 = N->getOperand(0);
8076 EVT VT = N->getValueType(0);
8077 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
8078 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8079 SDValue Inner = N0.getOperand(0);
8080 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
8081 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
8082 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
8083 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
8084 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
8085 EVT ShiftVT = N0.getOperand(1).getValueType();
8086 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
8087 Inner.getOperand(0));
8088 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
8089 DAG.getConstant(NewShlAmt, SDLoc(Inner),
8090 ShiftVT));
8091 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
8092 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
8093 }
8094 }
8095 }
8096
8097 return SDValue();
8098}
8099
8100SDValue SystemZTargetLowering::combineMERGE(
8101 SDNode *N, DAGCombinerInfo &DCI) const {
8102 SelectionDAG &DAG = DCI.DAG;
8103 unsigned Opcode = N->getOpcode();
8104 SDValue Op0 = N->getOperand(0);
8105 SDValue Op1 = N->getOperand(1);
8106 if (Op0.getOpcode() == ISD::BITCAST)
8107 Op0 = Op0.getOperand(0);
8108 if (ISD::isBuildVectorAllZeros(Op0)) {
8109 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
8110 // for v4f32.
8111 if (Op1 == N->getOperand(0))
8112 return Op1;
8113 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
8114 EVT VT = Op1.getValueType();
8115 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
8116 if (ElemBytes <= 4) {
8117 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
8118 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
8119 EVT InVT = VT.changeVectorElementTypeToInteger();
8120 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
8121 SystemZ::VectorBytes / ElemBytes / 2);
8122 if (VT != InVT) {
8123 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
8124 DCI.AddToWorklist(Op1.getNode());
8125 }
8126 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
8127 DCI.AddToWorklist(Op.getNode());
8128 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8129 }
8130 }
8131 return SDValue();
8132}
8133
8134static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8135 SDNode *&HiPart) {
8136 LoPart = HiPart = nullptr;
8137
8138 // Scan through all users.
8139 for (SDUse &Use : LD->uses()) {
8140 // Skip the uses of the chain.
8141 if (Use.getResNo() != 0)
8142 continue;
8143
8144 // Verify every user is a TRUNCATE to i64 of the low or high half.
8145 SDNode *User = Use.getUser();
8146 bool IsLoPart = true;
8147 if (User->getOpcode() == ISD::SRL &&
8148 User->getOperand(1).getOpcode() == ISD::Constant &&
8149 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
8150 User = *User->user_begin();
8151 IsLoPart = false;
8152 }
8153 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
8154 return false;
8155
8156 if (IsLoPart) {
8157 if (LoPart)
8158 return false;
8159 LoPart = User;
8160 } else {
8161 if (HiPart)
8162 return false;
8163 HiPart = User;
8164 }
8165 }
8166 return true;
8167}
8168
8169static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8170 SDNode *&HiPart) {
8171 LoPart = HiPart = nullptr;
8172
8173 // Scan through all users.
8174 for (SDUse &Use : LD->uses()) {
8175 // Skip the uses of the chain.
8176 if (Use.getResNo() != 0)
8177 continue;
8178
8179 // Verify every user is an EXTRACT_SUBREG of the low or high half.
8180 SDNode *User = Use.getUser();
8181 if (!User->hasOneUse() || !User->isMachineOpcode() ||
8182 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
8183 return false;
8184
8185 switch (User->getConstantOperandVal(1)) {
8186 case SystemZ::subreg_l64:
8187 if (LoPart)
8188 return false;
8189 LoPart = User;
8190 break;
8191 case SystemZ::subreg_h64:
8192 if (HiPart)
8193 return false;
8194 HiPart = User;
8195 break;
8196 default:
8197 return false;
8198 }
8199 }
8200 return true;
8201}
8202
8203SDValue SystemZTargetLowering::combineLOAD(
8204 SDNode *N, DAGCombinerInfo &DCI) const {
8205 SelectionDAG &DAG = DCI.DAG;
8206 EVT LdVT = N->getValueType(0);
8207 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
8208 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
8209 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8210 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
8211 if (PtrVT != LoadNodeVT) {
8212 SDLoc DL(LN);
8213 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
8214 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
8215 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
8216 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
8217 LN->getMemOperand());
8218 }
8219 }
8220 }
8221 SDLoc DL(N);
8222
8223 // Replace a 128-bit load that is used solely to move its value into GPRs
8224 // by separate loads of both halves.
8225 LoadSDNode *LD = cast<LoadSDNode>(N);
8226 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
8227 SDNode *LoPart, *HiPart;
8228 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
8229 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
8230 // Rewrite each extraction as an independent load.
8231 SmallVector<SDValue, 2> ArgChains;
8232 if (HiPart) {
8233 SDValue EltLoad = DAG.getLoad(
8234 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
8235 LD->getPointerInfo(), LD->getBaseAlign(),
8236 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8237
8238 DCI.CombineTo(HiPart, EltLoad, true);
8239 ArgChains.push_back(EltLoad.getValue(1));
8240 }
8241 if (LoPart) {
8242 SDValue EltLoad = DAG.getLoad(
8243 LoPart->getValueType(0), DL, LD->getChain(),
8244 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
8245 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
8246 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8247
8248 DCI.CombineTo(LoPart, EltLoad, true);
8249 ArgChains.push_back(EltLoad.getValue(1));
8250 }
8251
8252 // Collect all chains via TokenFactor.
8253 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8254 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8255 DCI.AddToWorklist(Chain.getNode());
8256 return SDValue(N, 0);
8257 }
8258 }
8259
8260 if (LdVT.isVector() || LdVT.isInteger())
8261 return SDValue();
8262 // Transform a scalar load that is REPLICATEd as well as having other
8263 // use(s) to the form where the other use(s) use the first element of the
8264 // REPLICATE instead of the load. Otherwise instruction selection will not
8265 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8266 // point loads.
8267
8268 SDValue Replicate;
8269 SmallVector<SDNode*, 8> OtherUses;
8270 for (SDUse &Use : N->uses()) {
8271 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8272 if (Replicate)
8273 return SDValue(); // Should never happen
8274 Replicate = SDValue(Use.getUser(), 0);
8275 } else if (Use.getResNo() == 0)
8276 OtherUses.push_back(Use.getUser());
8277 }
8278 if (!Replicate || OtherUses.empty())
8279 return SDValue();
8280
8281 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8282 Replicate, DAG.getConstant(0, DL, MVT::i32));
8283 // Update uses of the loaded Value while preserving old chains.
8284 for (SDNode *U : OtherUses) {
8286 for (SDValue Op : U->ops())
8287 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8288 DAG.UpdateNodeOperands(U, Ops);
8289 }
8290 return SDValue(N, 0);
8291}
8292
8293bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8294 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8295 return true;
8296 if (Subtarget.hasVectorEnhancements2())
8297 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8298 return true;
8299 return false;
8300}
8301
8303 if (!VT.isVector() || !VT.isSimple() ||
8304 VT.getSizeInBits() != 128 ||
8305 VT.getScalarSizeInBits() % 8 != 0)
8306 return false;
8307
8308 unsigned NumElts = VT.getVectorNumElements();
8309 for (unsigned i = 0; i < NumElts; ++i) {
8310 if (M[i] < 0) continue; // ignore UNDEF indices
8311 if ((unsigned) M[i] != NumElts - 1 - i)
8312 return false;
8313 }
8314
8315 return true;
8316}
8317
8318static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8319 for (auto *U : StoredVal->users()) {
8320 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8321 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8322 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8323 continue;
8324 } else if (isa<BuildVectorSDNode>(U)) {
8325 SDValue BuildVector = SDValue(U, 0);
8326 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8327 isOnlyUsedByStores(BuildVector, DAG))
8328 continue;
8329 }
8330 return false;
8331 }
8332 return true;
8333}
8334
8335static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8336 SDValue &HiPart) {
8337 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8338 return false;
8339
8340 SDValue Op0 = Val.getOperand(0);
8341 SDValue Op1 = Val.getOperand(1);
8342
8343 if (Op0.getOpcode() == ISD::SHL)
8344 std::swap(Op0, Op1);
8345 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8346 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8347 Op1.getConstantOperandVal(1) != 64)
8348 return false;
8349 Op1 = Op1.getOperand(0);
8350
8351 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8352 Op0.getOperand(0).getValueType() != MVT::i64)
8353 return false;
8354 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8355 Op1.getOperand(0).getValueType() != MVT::i64)
8356 return false;
8357
8358 LoPart = Op0.getOperand(0);
8359 HiPart = Op1.getOperand(0);
8360 return true;
8361}
8362
8363static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8364 SDValue &HiPart) {
8365 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8366 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8367 return false;
8368
8369 if (Val->getNumOperands() != 5 ||
8370 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8371 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8372 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8373 return false;
8374
8375 LoPart = Val->getOperand(1);
8376 HiPart = Val->getOperand(3);
8377 return true;
8378}
8379
8380SDValue SystemZTargetLowering::combineSTORE(
8381 SDNode *N, DAGCombinerInfo &DCI) const {
8382 SelectionDAG &DAG = DCI.DAG;
8383 auto *SN = cast<StoreSDNode>(N);
8384 auto &Op1 = N->getOperand(1);
8385 EVT MemVT = SN->getMemoryVT();
8386
8387 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8388 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8389 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8390 if (PtrVT != StoreNodeVT) {
8391 SDLoc DL(SN);
8392 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8393 SYSTEMZAS::PTR32, 0);
8394 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8395 SN->getPointerInfo(), SN->getBaseAlign(),
8396 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8397 }
8398 }
8399
8400 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8401 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8402 // If X has wider elements then convert it to:
8403 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8404 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8405 if (SDValue Value =
8406 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8407 DCI.AddToWorklist(Value.getNode());
8408
8409 // Rewrite the store with the new form of stored value.
8410 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8411 SN->getBasePtr(), SN->getMemoryVT(),
8412 SN->getMemOperand());
8413 }
8414 }
8415
8416 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8417 if (Op1->isMachineOpcode() &&
8418 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8419 // Obtain the frame index the store was targeting.
8420 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8421 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8422 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8423 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8424 }
8425
8426 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8427 if (!SN->isTruncatingStore() &&
8428 Op1.getOpcode() == ISD::BSWAP &&
8429 Op1.getNode()->hasOneUse() &&
8430 canLoadStoreByteSwapped(Op1.getValueType())) {
8431
8432 SDValue BSwapOp = Op1.getOperand(0);
8433
8434 if (BSwapOp.getValueType() == MVT::i16)
8435 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8436
8437 SDValue Ops[] = {
8438 N->getOperand(0), BSwapOp, N->getOperand(2)
8439 };
8440
8441 return
8442 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8443 Ops, MemVT, SN->getMemOperand());
8444 }
8445 // Combine STORE (element-swap) into VSTER
8446 if (!SN->isTruncatingStore() &&
8447 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8448 Op1.getNode()->hasOneUse() &&
8449 Subtarget.hasVectorEnhancements2()) {
8450 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8451 ArrayRef<int> ShuffleMask = SVN->getMask();
8452 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8453 SDValue Ops[] = {
8454 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8455 };
8456
8457 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8458 DAG.getVTList(MVT::Other),
8459 Ops, MemVT, SN->getMemOperand());
8460 }
8461 }
8462
8463 // Combine STORE (READCYCLECOUNTER) into STCKF.
8464 if (!SN->isTruncatingStore() &&
8466 Op1.hasOneUse() &&
8467 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8468 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8469 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8470 DAG.getVTList(MVT::Other),
8471 Ops, MemVT, SN->getMemOperand());
8472 }
8473
8474 // Transform a store of a 128-bit value moved from parts into two stores.
8475 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8476 SDValue LoPart, HiPart;
8477 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8478 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8479 SDLoc DL(SN);
8480 SDValue Chain0 = DAG.getStore(
8481 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8482 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8483 SDValue Chain1 = DAG.getStore(
8484 SN->getChain(), DL, LoPart,
8485 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8486 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8487 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8488
8489 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8490 }
8491 }
8492
8493 // Replicate a reg or immediate with VREP instead of scalar multiply or
8494 // immediate load. It seems best to do this during the first DAGCombine as
8495 // it is straight-forward to handle the zero-extend node in the initial
8496 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8497 // extracting an i16 element from a v16i8 vector).
8498 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8499 isOnlyUsedByStores(Op1, DAG)) {
8500 SDValue Word = SDValue();
8501 EVT WordVT;
8502
8503 // Find a replicated immediate and return it if found in Word and its
8504 // type in WordVT.
8505 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8506 // Some constants are better handled with a scalar store.
8507 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8508 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8509 return;
8510
8511 APInt Val = C->getAPIntValue();
8512 // Truncate Val in case of a truncating store.
8513 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8514 assert(SN->isTruncatingStore() &&
8515 "Non-truncating store and immediate value does not fit?");
8516 Val = Val.trunc(TotBytes * 8);
8517 }
8518
8519 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8520 if (VCI.isVectorConstantLegal(Subtarget) &&
8521 VCI.Opcode == SystemZISD::REPLICATE) {
8522 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8523 WordVT = VCI.VecVT.getScalarType();
8524 }
8525 };
8526
8527 // Find a replicated register and return it if found in Word and its type
8528 // in WordVT.
8529 auto FindReplicatedReg = [&](SDValue MulOp) {
8530 EVT MulVT = MulOp.getValueType();
8531 if (MulOp->getOpcode() == ISD::MUL &&
8532 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8533 // Find a zero extended value and its type.
8534 SDValue LHS = MulOp->getOperand(0);
8535 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8536 WordVT = LHS->getOperand(0).getValueType();
8537 else if (LHS->getOpcode() == ISD::AssertZext)
8538 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8539 else
8540 return;
8541 // Find a replicating constant, e.g. 0x00010001.
8542 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8543 SystemZVectorConstantInfo VCI(
8544 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8545 if (VCI.isVectorConstantLegal(Subtarget) &&
8546 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8547 WordVT == VCI.VecVT.getScalarType())
8548 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8549 }
8550 }
8551 };
8552
8553 if (isa<BuildVectorSDNode>(Op1) &&
8554 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8555 SDValue SplatVal = Op1->getOperand(0);
8556 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8557 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8558 else
8559 FindReplicatedReg(SplatVal);
8560 } else {
8561 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8562 FindReplicatedImm(C, MemVT.getStoreSize());
8563 else
8564 FindReplicatedReg(Op1);
8565 }
8566
8567 if (Word != SDValue()) {
8568 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8569 "Bad type handling");
8570 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8571 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8572 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8573 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8574 SN->getBasePtr(), SN->getMemOperand());
8575 }
8576 }
8577
8578 return SDValue();
8579}
8580
8581SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8582 SDNode *N, DAGCombinerInfo &DCI) const {
8583 SelectionDAG &DAG = DCI.DAG;
8584 // Combine element-swap (LOAD) into VLER
8585 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8586 N->getOperand(0).hasOneUse() &&
8587 Subtarget.hasVectorEnhancements2()) {
8588 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8589 ArrayRef<int> ShuffleMask = SVN->getMask();
8590 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8591 SDValue Load = N->getOperand(0);
8592 LoadSDNode *LD = cast<LoadSDNode>(Load);
8593
8594 // Create the element-swapping load.
8595 SDValue Ops[] = {
8596 LD->getChain(), // Chain
8597 LD->getBasePtr() // Ptr
8598 };
8599 SDValue ESLoad =
8600 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8601 DAG.getVTList(LD->getValueType(0), MVT::Other),
8602 Ops, LD->getMemoryVT(), LD->getMemOperand());
8603
8604 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8605 // by the load dead.
8606 DCI.CombineTo(N, ESLoad);
8607
8608 // Next, combine the load away, we give it a bogus result value but a real
8609 // chain result. The result value is dead because the shuffle is dead.
8610 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8611
8612 // Return N so it doesn't get rechecked!
8613 return SDValue(N, 0);
8614 }
8615 }
8616
8617 return SDValue();
8618}
8619
8620SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8621 SDNode *N, DAGCombinerInfo &DCI) const {
8622 SelectionDAG &DAG = DCI.DAG;
8623
8624 if (!Subtarget.hasVector())
8625 return SDValue();
8626
8627 // Look through bitcasts that retain the number of vector elements.
8628 SDValue Op = N->getOperand(0);
8629 if (Op.getOpcode() == ISD::BITCAST &&
8630 Op.getValueType().isVector() &&
8631 Op.getOperand(0).getValueType().isVector() &&
8632 Op.getValueType().getVectorNumElements() ==
8633 Op.getOperand(0).getValueType().getVectorNumElements())
8634 Op = Op.getOperand(0);
8635
8636 // Pull BSWAP out of a vector extraction.
8637 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8638 EVT VecVT = Op.getValueType();
8639 EVT EltVT = VecVT.getVectorElementType();
8640 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8641 Op.getOperand(0), N->getOperand(1));
8642 DCI.AddToWorklist(Op.getNode());
8643 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8644 if (EltVT != N->getValueType(0)) {
8645 DCI.AddToWorklist(Op.getNode());
8646 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8647 }
8648 return Op;
8649 }
8650
8651 // Try to simplify a vector extraction.
8652 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8653 SDValue Op0 = N->getOperand(0);
8654 EVT VecVT = Op0.getValueType();
8655 if (canTreatAsByteVector(VecVT))
8656 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8657 IndexN->getZExtValue(), DCI, false);
8658 }
8659 return SDValue();
8660}
8661
8662SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8663 SDNode *N, DAGCombinerInfo &DCI) const {
8664 SelectionDAG &DAG = DCI.DAG;
8665 // (join_dwords X, X) == (replicate X)
8666 if (N->getOperand(0) == N->getOperand(1))
8667 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8668 N->getOperand(0));
8669 return SDValue();
8670}
8671
8673 SDValue Chain1 = N1->getOperand(0);
8674 SDValue Chain2 = N2->getOperand(0);
8675
8676 // Trivial case: both nodes take the same chain.
8677 if (Chain1 == Chain2)
8678 return Chain1;
8679
8680 // FIXME - we could handle more complex cases via TokenFactor,
8681 // assuming we can verify that this would not create a cycle.
8682 return SDValue();
8683}
8684
8685SDValue SystemZTargetLowering::combineFP_ROUND(
8686 SDNode *N, DAGCombinerInfo &DCI) const {
8687
8688 if (!Subtarget.hasVector())
8689 return SDValue();
8690
8691 // (fpround (extract_vector_elt X 0))
8692 // (fpround (extract_vector_elt X 1)) ->
8693 // (extract_vector_elt (VROUND X) 0)
8694 // (extract_vector_elt (VROUND X) 2)
8695 //
8696 // This is a special case since the target doesn't really support v2f32s.
8697 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8698 SelectionDAG &DAG = DCI.DAG;
8699 SDValue Op0 = N->getOperand(OpNo);
8700 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8702 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8703 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8704 Op0.getConstantOperandVal(1) == 0) {
8705 SDValue Vec = Op0.getOperand(0);
8706 for (auto *U : Vec->users()) {
8707 if (U != Op0.getNode() && U->hasOneUse() &&
8708 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8709 U->getOperand(0) == Vec &&
8710 U->getOperand(1).getOpcode() == ISD::Constant &&
8711 U->getConstantOperandVal(1) == 1) {
8712 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8713 if (OtherRound.getOpcode() == N->getOpcode() &&
8714 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8715 OtherRound.getValueType() == MVT::f32) {
8716 SDValue VRound, Chain;
8717 if (N->isStrictFPOpcode()) {
8718 Chain = MergeInputChains(N, OtherRound.getNode());
8719 if (!Chain)
8720 continue;
8721 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8722 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8723 Chain = VRound.getValue(1);
8724 } else
8725 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8726 MVT::v4f32, Vec);
8727 DCI.AddToWorklist(VRound.getNode());
8728 SDValue Extract1 =
8729 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8730 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8731 DCI.AddToWorklist(Extract1.getNode());
8732 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8733 if (Chain)
8734 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8735 SDValue Extract0 =
8736 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8737 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8738 if (Chain)
8739 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8740 N->getVTList(), Extract0, Chain);
8741 return Extract0;
8742 }
8743 }
8744 }
8745 }
8746 return SDValue();
8747}
8748
8749SDValue SystemZTargetLowering::combineFP_EXTEND(
8750 SDNode *N, DAGCombinerInfo &DCI) const {
8751
8752 if (!Subtarget.hasVector())
8753 return SDValue();
8754
8755 // (fpextend (extract_vector_elt X 0))
8756 // (fpextend (extract_vector_elt X 2)) ->
8757 // (extract_vector_elt (VEXTEND X) 0)
8758 // (extract_vector_elt (VEXTEND X) 1)
8759 //
8760 // This is a special case since the target doesn't really support v2f32s.
8761 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8762 SelectionDAG &DAG = DCI.DAG;
8763 SDValue Op0 = N->getOperand(OpNo);
8764 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8766 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8767 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8768 Op0.getConstantOperandVal(1) == 0) {
8769 SDValue Vec = Op0.getOperand(0);
8770 for (auto *U : Vec->users()) {
8771 if (U != Op0.getNode() && U->hasOneUse() &&
8772 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8773 U->getOperand(0) == Vec &&
8774 U->getOperand(1).getOpcode() == ISD::Constant &&
8775 U->getConstantOperandVal(1) == 2) {
8776 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8777 if (OtherExtend.getOpcode() == N->getOpcode() &&
8778 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8779 OtherExtend.getValueType() == MVT::f64) {
8780 SDValue VExtend, Chain;
8781 if (N->isStrictFPOpcode()) {
8782 Chain = MergeInputChains(N, OtherExtend.getNode());
8783 if (!Chain)
8784 continue;
8785 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8786 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8787 Chain = VExtend.getValue(1);
8788 } else
8789 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8790 MVT::v2f64, Vec);
8791 DCI.AddToWorklist(VExtend.getNode());
8792 SDValue Extract1 =
8793 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8794 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8795 DCI.AddToWorklist(Extract1.getNode());
8796 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8797 if (Chain)
8798 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8799 SDValue Extract0 =
8800 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8801 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8802 if (Chain)
8803 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8804 N->getVTList(), Extract0, Chain);
8805 return Extract0;
8806 }
8807 }
8808 }
8809 }
8810 return SDValue();
8811}
8812
8813SDValue SystemZTargetLowering::combineINT_TO_FP(
8814 SDNode *N, DAGCombinerInfo &DCI) const {
8815 if (DCI.Level != BeforeLegalizeTypes)
8816 return SDValue();
8817 SelectionDAG &DAG = DCI.DAG;
8818 LLVMContext &Ctx = *DAG.getContext();
8819 unsigned Opcode = N->getOpcode();
8820 EVT OutVT = N->getValueType(0);
8821 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8822 SDValue Op = N->getOperand(0);
8823 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8824 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8825
8826 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8827 // v2f64 = uint_to_fp v2i16
8828 // =>
8829 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8830 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8831 OutScalarBits <= 64) {
8832 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8833 EVT ExtVT = EVT::getVectorVT(
8834 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8835 unsigned ExtOpcode =
8837 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8838 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8839 }
8840 return SDValue();
8841}
8842
8843SDValue SystemZTargetLowering::combineFCOPYSIGN(
8844 SDNode *N, DAGCombinerInfo &DCI) const {
8845 SelectionDAG &DAG = DCI.DAG;
8846 EVT VT = N->getValueType(0);
8847 SDValue ValOp = N->getOperand(0);
8848 SDValue SignOp = N->getOperand(1);
8849
8850 // Remove the rounding which is not needed.
8851 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8852 SDValue WideOp = SignOp.getOperand(0);
8853 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8854 }
8855
8856 return SDValue();
8857}
8858
8859SDValue SystemZTargetLowering::combineBSWAP(
8860 SDNode *N, DAGCombinerInfo &DCI) const {
8861 SelectionDAG &DAG = DCI.DAG;
8862 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8863 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8864 N->getOperand(0).hasOneUse() &&
8865 canLoadStoreByteSwapped(N->getValueType(0))) {
8866 SDValue Load = N->getOperand(0);
8867 LoadSDNode *LD = cast<LoadSDNode>(Load);
8868
8869 // Create the byte-swapping load.
8870 SDValue Ops[] = {
8871 LD->getChain(), // Chain
8872 LD->getBasePtr() // Ptr
8873 };
8874 EVT LoadVT = N->getValueType(0);
8875 if (LoadVT == MVT::i16)
8876 LoadVT = MVT::i32;
8877 SDValue BSLoad =
8878 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8879 DAG.getVTList(LoadVT, MVT::Other),
8880 Ops, LD->getMemoryVT(), LD->getMemOperand());
8881
8882 // If this is an i16 load, insert the truncate.
8883 SDValue ResVal = BSLoad;
8884 if (N->getValueType(0) == MVT::i16)
8885 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8886
8887 // First, combine the bswap away. This makes the value produced by the
8888 // load dead.
8889 DCI.CombineTo(N, ResVal);
8890
8891 // Next, combine the load away, we give it a bogus result value but a real
8892 // chain result. The result value is dead because the bswap is dead.
8893 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8894
8895 // Return N so it doesn't get rechecked!
8896 return SDValue(N, 0);
8897 }
8898
8899 // Look through bitcasts that retain the number of vector elements.
8900 SDValue Op = N->getOperand(0);
8901 if (Op.getOpcode() == ISD::BITCAST &&
8902 Op.getValueType().isVector() &&
8903 Op.getOperand(0).getValueType().isVector() &&
8904 Op.getValueType().getVectorNumElements() ==
8905 Op.getOperand(0).getValueType().getVectorNumElements())
8906 Op = Op.getOperand(0);
8907
8908 // Push BSWAP into a vector insertion if at least one side then simplifies.
8909 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8910 SDValue Vec = Op.getOperand(0);
8911 SDValue Elt = Op.getOperand(1);
8912 SDValue Idx = Op.getOperand(2);
8913
8915 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8917 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8918 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8919 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8920 EVT VecVT = N->getValueType(0);
8921 EVT EltVT = N->getValueType(0).getVectorElementType();
8922 if (VecVT != Vec.getValueType()) {
8923 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8924 DCI.AddToWorklist(Vec.getNode());
8925 }
8926 if (EltVT != Elt.getValueType()) {
8927 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8928 DCI.AddToWorklist(Elt.getNode());
8929 }
8930 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8931 DCI.AddToWorklist(Vec.getNode());
8932 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8933 DCI.AddToWorklist(Elt.getNode());
8934 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8935 Vec, Elt, Idx);
8936 }
8937 }
8938
8939 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8940 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8941 if (SV && Op.hasOneUse()) {
8942 SDValue Op0 = Op.getOperand(0);
8943 SDValue Op1 = Op.getOperand(1);
8944
8946 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8948 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8949 EVT VecVT = N->getValueType(0);
8950 if (VecVT != Op0.getValueType()) {
8951 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8952 DCI.AddToWorklist(Op0.getNode());
8953 }
8954 if (VecVT != Op1.getValueType()) {
8955 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8956 DCI.AddToWorklist(Op1.getNode());
8957 }
8958 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8959 DCI.AddToWorklist(Op0.getNode());
8960 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8961 DCI.AddToWorklist(Op1.getNode());
8962 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8963 }
8964 }
8965
8966 return SDValue();
8967}
8968
8969SDValue SystemZTargetLowering::combineSETCC(
8970 SDNode *N, DAGCombinerInfo &DCI) const {
8971 SelectionDAG &DAG = DCI.DAG;
8972 const ISD::CondCode CC = N->getOperandCondCode(2);
8973 const SDValue LHS = N->getOperand(0);
8974 const SDValue RHS = N->getOperand(1);
8975 bool CmpNull = isNullConstant(RHS);
8976 bool CmpAllOnes = isAllOnesConstant(RHS);
8977 EVT VT = N->getValueType(0);
8978 SDLoc DL(N);
8979
8980 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8981 // change the outer compare to a i128 compare. This will normally
8982 // allow the reduction to be recognized in adjustICmp128, and even if
8983 // not, the i128 compare will still generate better code.
8984 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8986 if (Src.getOpcode() == ISD::SETCC &&
8987 Src.getValueType().isFixedLengthVector() &&
8988 Src.getValueType().getScalarType() == MVT::i1) {
8989 EVT CmpVT = Src.getOperand(0).getValueType();
8990 if (CmpVT.getSizeInBits() == 128) {
8991 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8992 SDValue LHS =
8993 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8994 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8995 : DAG.getAllOnesConstant(DL, MVT::i128);
8996 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8997 N->getFlags());
8998 }
8999 }
9000 }
9001
9002 return SDValue();
9003}
9004
9005static std::pair<SDValue, int> findCCUse(const SDValue &Val,
9006 unsigned Depth = 0) {
9007 // Limit depth of potentially exponential walk.
9008 if (Depth > 5)
9009 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
9010
9011 switch (Val.getOpcode()) {
9012 default:
9013 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
9014 case SystemZISD::IPM:
9015 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
9016 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
9017 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
9018 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
9019 case SystemZISD::SELECT_CCMASK: {
9020 SDValue Op4CCReg = Val.getOperand(4);
9021 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
9022 Op4CCReg.getOpcode() == SystemZISD::TM) {
9023 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
9024 if (OpCC != SDValue())
9025 return std::make_pair(OpCC, OpCCValid);
9026 }
9027 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
9028 if (!CCValid)
9029 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
9030 int CCValidVal = CCValid->getZExtValue();
9031 return std::make_pair(Op4CCReg, CCValidVal);
9032 }
9033 case ISD::ADD:
9034 case ISD::AND:
9035 case ISD::OR:
9036 case ISD::XOR:
9037 case ISD::SHL:
9038 case ISD::SRA:
9039 case ISD::SRL:
9040 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
9041 if (Op0CC != SDValue())
9042 return std::make_pair(Op0CC, Op0CCValid);
9043 return findCCUse(Val.getOperand(1), Depth + 1);
9044 }
9045}
9046
9047static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
9048 SelectionDAG &DAG);
9049
9051 SelectionDAG &DAG) {
9052 SDLoc DL(Val);
9053 auto Opcode = Val.getOpcode();
9054 switch (Opcode) {
9055 default:
9056 return {};
9057 case ISD::Constant:
9058 return {Val, Val, Val, Val};
9059 case SystemZISD::IPM: {
9060 SDValue IPMOp0 = Val.getOperand(0);
9061 if (IPMOp0 != CC)
9062 return {};
9063 SmallVector<SDValue, 4> ShiftedCCVals;
9064 for (auto CC : {0, 1, 2, 3})
9065 ShiftedCCVals.emplace_back(
9066 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
9067 return ShiftedCCVals;
9068 }
9069 case SystemZISD::SELECT_CCMASK: {
9070 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9071 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
9072 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9073 if (!CCValid || !CCMask)
9074 return {};
9075
9076 int CCValidVal = CCValid->getZExtValue();
9077 int CCMaskVal = CCMask->getZExtValue();
9078 // Pruning search tree early - Moving CC test and combineCCMask ahead of
9079 // recursive call to simplifyAssumingCCVal.
9080 SDValue Op4CCReg = Val.getOperand(4);
9081 if (Op4CCReg != CC)
9082 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
9083 if (Op4CCReg != CC)
9084 return {};
9085 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
9086 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
9087 if (TrueSDVals.empty() || FalseSDVals.empty())
9088 return {};
9089 SmallVector<SDValue, 4> MergedSDVals;
9090 for (auto &CCVal : {0, 1, 2, 3})
9091 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
9092 ? TrueSDVals[CCVal]
9093 : FalseSDVals[CCVal]);
9094 return MergedSDVals;
9095 }
9096 case ISD::ADD:
9097 case ISD::AND:
9098 case ISD::OR:
9099 case ISD::XOR:
9100 case ISD::SRA:
9101 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
9102 // would clobber CC).
9103 if (!Val.hasOneUse())
9104 return {};
9105 [[fallthrough]];
9106 case ISD::SHL:
9107 case ISD::SRL:
9108 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
9109 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
9110 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
9111 if (Op0SDVals.empty() || Op1SDVals.empty())
9112 return {};
9113 SmallVector<SDValue, 4> BinaryOpSDVals;
9114 for (auto CCVal : {0, 1, 2, 3})
9115 BinaryOpSDVals.emplace_back(DAG.getNode(
9116 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
9117 return BinaryOpSDVals;
9118 }
9119}
9120
9121static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
9122 SelectionDAG &DAG) {
9123 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
9124 // set by the CCReg instruction using the CCValid / CCMask masks,
9125 // If the CCReg instruction is itself a ICMP / TM testing the condition
9126 // code set by some other instruction, see whether we can directly
9127 // use that condition code.
9128 auto *CCNode = CCReg.getNode();
9129 if (!CCNode)
9130 return false;
9131
9132 if (CCNode->getOpcode() == SystemZISD::TM) {
9133 if (CCValid != SystemZ::CCMASK_TM)
9134 return false;
9135 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
9136 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9137 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9138 if (!Op0Node || !Op1Node)
9139 return -1;
9140 auto Op0APVal = Op0Node->getAPIntValue();
9141 auto Op1APVal = Op1Node->getAPIntValue();
9142 auto Result = Op0APVal & Op1APVal;
9143 bool AllOnes = Result == Op1APVal;
9144 bool AllZeros = Result == 0;
9145 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
9146 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
9147 };
9148 SDValue Op0 = CCNode->getOperand(0);
9149 SDValue Op1 = CCNode->getOperand(1);
9150 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
9151 if (Op0CC == SDValue())
9152 return false;
9153 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
9154 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
9155 if (Op0SDVals.empty() || Op1SDVals.empty())
9156 return false;
9157 int NewCCMask = 0;
9158 for (auto CC : {0, 1, 2, 3}) {
9159 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
9160 if (CCVal < 0)
9161 return false;
9162 NewCCMask <<= 1;
9163 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9164 }
9165 NewCCMask &= Op0CCValid;
9166 CCReg = Op0CC;
9167 CCMask = NewCCMask;
9168 CCValid = Op0CCValid;
9169 return true;
9170 }
9171 if (CCNode->getOpcode() != SystemZISD::ICMP ||
9172 CCValid != SystemZ::CCMASK_ICMP)
9173 return false;
9174
9175 SDValue CmpOp0 = CCNode->getOperand(0);
9176 SDValue CmpOp1 = CCNode->getOperand(1);
9177 SDValue CmpOp2 = CCNode->getOperand(2);
9178 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
9179 if (Op0CC != SDValue()) {
9180 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
9181 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
9182 if (Op0SDVals.empty() || Op1SDVals.empty())
9183 return false;
9184
9185 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
9186 auto CmpTypeVal = CmpType->getZExtValue();
9187 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
9188 const SDValue &Op1Val) {
9189 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9190 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9191 if (!Op0Node || !Op1Node)
9192 return -1;
9193 auto Op0APVal = Op0Node->getAPIntValue();
9194 auto Op1APVal = Op1Node->getAPIntValue();
9195 if (CmpTypeVal == SystemZICMP::SignedOnly)
9196 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
9197 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
9198 };
9199 int NewCCMask = 0;
9200 for (auto CC : {0, 1, 2, 3}) {
9201 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
9202 if (CCVal < 0)
9203 return false;
9204 NewCCMask <<= 1;
9205 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9206 }
9207 NewCCMask &= Op0CCValid;
9208 CCMask = NewCCMask;
9209 CCReg = Op0CC;
9210 CCValid = Op0CCValid;
9211 return true;
9212 }
9213
9214 return false;
9215}
9216
9217// Merging versus split in multiple branches cost.
9220 const Value *Lhs,
9221 const Value *Rhs,
9222 const Function *) const {
9223 const auto isFlagOutOpCC = [](const Value *V) {
9224 using namespace llvm::PatternMatch;
9225 const Value *RHSVal;
9226 const APInt *RHSC;
9227 if (const auto *I = dyn_cast<Instruction>(V)) {
9228 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
9229 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
9230 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
9231 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
9232 if (CB->isInlineAsm()) {
9233 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
9234 return IA && IA->getConstraintString().contains("{@cc}");
9235 }
9236 }
9237 }
9238 }
9239 return false;
9240 };
9241 // Pattern (ICmp %asm) or (ICmp (And %asm)).
9242 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
9243 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
9244 // conditionals will be merged or else conditionals will be split.
9245 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
9246 return {3, 0, -1};
9247 // Default.
9248 return {-1, -1, -1};
9249}
9250
9251SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
9252 DAGCombinerInfo &DCI) const {
9253 SelectionDAG &DAG = DCI.DAG;
9254
9255 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9256 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9257 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9258 if (!CCValid || !CCMask)
9259 return SDValue();
9260
9261 int CCValidVal = CCValid->getZExtValue();
9262 int CCMaskVal = CCMask->getZExtValue();
9263 SDValue Chain = N->getOperand(0);
9264 SDValue CCReg = N->getOperand(4);
9265 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9266 // the modified BR_CCMASK with the new values.
9267 // In order to avoid conditional branches with full or empty cc masks, do not
9268 // do this if ccmask is 0 or equal to ccvalid.
9269 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9270 CCMaskVal != CCValidVal)
9271 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9272 Chain,
9273 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9274 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9275 N->getOperand(3), CCReg);
9276 return SDValue();
9277}
9278
9279SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9280 SDNode *N, DAGCombinerInfo &DCI) const {
9281 SelectionDAG &DAG = DCI.DAG;
9282
9283 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9284 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9285 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9286 if (!CCValid || !CCMask)
9287 return SDValue();
9288
9289 int CCValidVal = CCValid->getZExtValue();
9290 int CCMaskVal = CCMask->getZExtValue();
9291 SDValue CCReg = N->getOperand(4);
9292
9293 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9294
9295 // Populate SDVals vector for each condition code ccval for given Val, which
9296 // can again be another nested select_ccmask with the same CC.
9297 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9298 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9300 if (Val.getOperand(4) != CCReg)
9301 return SmallVector<SDValue, 4>{};
9302 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9303 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9304 if (!CCMask)
9305 return SmallVector<SDValue, 4>{};
9306
9307 int CCMaskVal = CCMask->getZExtValue();
9308 for (auto &CC : {0, 1, 2, 3})
9309 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9310 : FalseVal);
9311 return Res;
9312 }
9313 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9314 };
9315 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9316 // with CCReg found by combineCCMask or original CCReg.
9317 SDValue TrueVal = N->getOperand(0);
9318 SDValue FalseVal = N->getOperand(1);
9319 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9320 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9321 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9322 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9323 if (TrueSDVals.empty())
9324 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9325 if (FalseSDVals.empty())
9326 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9327 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9328 SmallSet<SDValue, 4> MergedSDValsSet;
9329 // Ignoring CC values outside CCValiid.
9330 for (auto CC : {0, 1, 2, 3}) {
9331 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9332 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9333 ? TrueSDVals[CC]
9334 : FalseSDVals[CC]);
9335 }
9336 if (MergedSDValsSet.size() == 1)
9337 return *MergedSDValsSet.begin();
9338 if (MergedSDValsSet.size() == 2) {
9339 auto BeginIt = MergedSDValsSet.begin();
9340 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9341 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9342 std::swap(NewTrueVal, NewFalseVal);
9343 int NewCCMask = 0;
9344 for (auto CC : {0, 1, 2, 3}) {
9345 NewCCMask <<= 1;
9346 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9347 ? (TrueSDVals[CC] == NewTrueVal)
9348 : (FalseSDVals[CC] == NewTrueVal);
9349 }
9350 CCMaskVal = NewCCMask;
9351 CCMaskVal &= CCValidVal;
9352 TrueVal = NewTrueVal;
9353 FalseVal = NewFalseVal;
9354 IsCombinedCCReg = true;
9355 }
9356 }
9357 // If the condition is trivially false or trivially true after
9358 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9359 // (possibly modified by constructCCSDValsFromSELECT).
9360 if (CCMaskVal == 0)
9361 return FalseVal;
9362 if (CCMaskVal == CCValidVal)
9363 return TrueVal;
9364
9365 if (IsCombinedCCReg)
9366 return DAG.getNode(
9367 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9368 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9369 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9370
9371 return SDValue();
9372}
9373
9374SDValue SystemZTargetLowering::combineGET_CCMASK(
9375 SDNode *N, DAGCombinerInfo &DCI) const {
9376
9377 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9378 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9379 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9380 if (!CCValid || !CCMask)
9381 return SDValue();
9382 int CCValidVal = CCValid->getZExtValue();
9383 int CCMaskVal = CCMask->getZExtValue();
9384
9385 SDValue Select = N->getOperand(0);
9386 if (Select->getOpcode() == ISD::TRUNCATE)
9387 Select = Select->getOperand(0);
9388 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9389 return SDValue();
9390
9391 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9392 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9393 if (!SelectCCValid || !SelectCCMask)
9394 return SDValue();
9395 int SelectCCValidVal = SelectCCValid->getZExtValue();
9396 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9397
9398 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9399 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9400 if (!TrueVal || !FalseVal)
9401 return SDValue();
9402 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9403 ;
9404 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9405 SelectCCMaskVal ^= SelectCCValidVal;
9406 else
9407 return SDValue();
9408
9409 if (SelectCCValidVal & ~CCValidVal)
9410 return SDValue();
9411 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9412 return SDValue();
9413
9414 return Select->getOperand(4);
9415}
9416
9417SDValue SystemZTargetLowering::combineIntDIVREM(
9418 SDNode *N, DAGCombinerInfo &DCI) const {
9419 SelectionDAG &DAG = DCI.DAG;
9420 EVT VT = N->getValueType(0);
9421 // In the case where the divisor is a vector of constants a cheaper
9422 // sequence of instructions can replace the divide. BuildSDIV is called to
9423 // do this during DAG combining, but it only succeeds when it can build a
9424 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9425 // since it is not Legal but Custom it can only happen before
9426 // legalization. Therefore we must scalarize this early before Combine
9427 // 1. For widened vectors, this is already the result of type legalization.
9428 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9429 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9430 return DAG.UnrollVectorOp(N);
9431 return SDValue();
9432}
9433
9434
9435// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9436// This is closely modeled after the common-code combineShiftToMULH.
9437SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9438 SDNode *N, DAGCombinerInfo &DCI) const {
9439 SelectionDAG &DAG = DCI.DAG;
9440 SDLoc DL(N);
9441
9442 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9443 "SRL or SRA node is required here!");
9444
9445 if (!Subtarget.hasVector())
9446 return SDValue();
9447
9448 // Check the shift amount. Proceed with the transformation if the shift
9449 // amount is constant.
9450 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9451 if (!ShiftAmtSrc)
9452 return SDValue();
9453
9454 // The operation feeding into the shift must be an add.
9455 SDValue ShiftOperand = N->getOperand(0);
9456 if (ShiftOperand.getOpcode() != ISD::ADD)
9457 return SDValue();
9458
9459 // One operand of the add must be a multiply.
9460 SDValue MulOp = ShiftOperand.getOperand(0);
9461 SDValue AddOp = ShiftOperand.getOperand(1);
9462 if (MulOp.getOpcode() != ISD::MUL) {
9463 if (AddOp.getOpcode() != ISD::MUL)
9464 return SDValue();
9465 std::swap(MulOp, AddOp);
9466 }
9467
9468 // All operands must be equivalent extend nodes.
9469 SDValue LeftOp = MulOp.getOperand(0);
9470 SDValue RightOp = MulOp.getOperand(1);
9471
9472 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9473 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9474
9475 if (!IsSignExt && !IsZeroExt)
9476 return SDValue();
9477
9478 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9479 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9480
9481 SDValue MulhRightOp;
9482 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9483 unsigned ActiveBits = IsSignExt
9484 ? Constant->getAPIntValue().getSignificantBits()
9485 : Constant->getAPIntValue().getActiveBits();
9486 if (ActiveBits > NarrowVTSize)
9487 return SDValue();
9488 MulhRightOp = DAG.getConstant(
9489 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9490 NarrowVT);
9491 } else {
9492 if (LeftOp.getOpcode() != RightOp.getOpcode())
9493 return SDValue();
9494 // Check that the two extend nodes are the same type.
9495 if (NarrowVT != RightOp.getOperand(0).getValueType())
9496 return SDValue();
9497 MulhRightOp = RightOp.getOperand(0);
9498 }
9499
9500 SDValue MulhAddOp;
9501 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9502 unsigned ActiveBits = IsSignExt
9503 ? Constant->getAPIntValue().getSignificantBits()
9504 : Constant->getAPIntValue().getActiveBits();
9505 if (ActiveBits > NarrowVTSize)
9506 return SDValue();
9507 MulhAddOp = DAG.getConstant(
9508 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9509 NarrowVT);
9510 } else {
9511 if (LeftOp.getOpcode() != AddOp.getOpcode())
9512 return SDValue();
9513 // Check that the two extend nodes are the same type.
9514 if (NarrowVT != AddOp.getOperand(0).getValueType())
9515 return SDValue();
9516 MulhAddOp = AddOp.getOperand(0);
9517 }
9518
9519 EVT WideVT = LeftOp.getValueType();
9520 // Proceed with the transformation if the wide types match.
9521 assert((WideVT == RightOp.getValueType()) &&
9522 "Cannot have a multiply node with two different operand types.");
9523 assert((WideVT == AddOp.getValueType()) &&
9524 "Cannot have an add node with two different operand types.");
9525
9526 // Proceed with the transformation if the wide type is twice as large
9527 // as the narrow type.
9528 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9529 return SDValue();
9530
9531 // Check the shift amount with the narrow type size.
9532 // Proceed with the transformation if the shift amount is the width
9533 // of the narrow type.
9534 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9535 if (ShiftAmt != NarrowVTSize)
9536 return SDValue();
9537
9538 // Proceed if we support the multiply-and-add-high operation.
9539 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9540 NarrowVT == MVT::v4i32 ||
9541 (Subtarget.hasVectorEnhancements3() &&
9542 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9543 return SDValue();
9544
9545 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9546 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9547 DL, NarrowVT, LeftOp.getOperand(0),
9548 MulhRightOp, MulhAddOp);
9549 bool IsSigned = N->getOpcode() == ISD::SRA;
9550 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9551}
9552
9553// Op is an operand of a multiplication. Check whether this can be folded
9554// into an even/odd widening operation; if so, return the opcode to be used
9555// and update Op to the appropriate sub-operand. Note that the caller must
9556// verify that *both* operands of the multiplication support the operation.
9559 SDValue &Op) {
9560 EVT VT = Op.getValueType();
9561
9562 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9563 // to selecting the even or odd vector elements.
9564 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9565 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9566 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9567 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9568 unsigned NumElts = VT.getVectorNumElements();
9569 Op = Op.getOperand(0);
9570 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9571 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9573 ArrayRef<int> ShuffleMask = SVN->getMask();
9574 bool CanUseEven = true, CanUseOdd = true;
9575 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9576 if (ShuffleMask[Elt] == -1)
9577 continue;
9578 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9579 CanUseEven = false;
9580 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9581 CanUseOdd = false;
9582 }
9583 Op = Op.getOperand(0);
9584 if (CanUseEven)
9585 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9586 if (CanUseOdd)
9587 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9588 }
9589 }
9590
9591 // For z17, we can also support the v2i64->i128 case, which looks like
9592 // (sign/zero_extend (extract_vector_elt X 0/1))
9593 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9594 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9595 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9596 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9597 Op = Op.getOperand(0);
9598 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9599 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9600 Op.getOperand(1).getOpcode() == ISD::Constant) {
9601 unsigned Elem = Op.getConstantOperandVal(1);
9602 Op = Op.getOperand(0);
9603 if (Elem == 0)
9604 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9605 if (Elem == 1)
9606 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9607 }
9608 }
9609
9610 return 0;
9611}
9612
9613SDValue SystemZTargetLowering::combineMUL(
9614 SDNode *N, DAGCombinerInfo &DCI) const {
9615 SelectionDAG &DAG = DCI.DAG;
9616
9617 // Detect even/odd widening multiplication.
9618 SDValue Op0 = N->getOperand(0);
9619 SDValue Op1 = N->getOperand(1);
9620 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9621 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9622 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9623 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9624
9625 return SDValue();
9626}
9627
9628SDValue SystemZTargetLowering::combineINTRINSIC(
9629 SDNode *N, DAGCombinerInfo &DCI) const {
9630 SelectionDAG &DAG = DCI.DAG;
9631
9632 unsigned Id = N->getConstantOperandVal(1);
9633 switch (Id) {
9634 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9635 // or larger is simply a vector load.
9636 case Intrinsic::s390_vll:
9637 case Intrinsic::s390_vlrl:
9638 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9639 if (C->getZExtValue() >= 15)
9640 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9641 N->getOperand(3), MachinePointerInfo());
9642 break;
9643 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9644 case Intrinsic::s390_vstl:
9645 case Intrinsic::s390_vstrl:
9646 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9647 if (C->getZExtValue() >= 15)
9648 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9649 N->getOperand(4), MachinePointerInfo());
9650 break;
9651 }
9652
9653 return SDValue();
9654}
9655
9656SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9657 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9658 return N->getOperand(0);
9659 return N;
9660}
9661
9663 DAGCombinerInfo &DCI) const {
9664 switch(N->getOpcode()) {
9665 default: break;
9666 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9667 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9668 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9669 case SystemZISD::MERGE_HIGH:
9670 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9671 case ISD::LOAD: return combineLOAD(N, DCI);
9672 case ISD::STORE: return combineSTORE(N, DCI);
9673 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9674 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9675 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9677 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9679 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9680 case ISD::SINT_TO_FP:
9681 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9682 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9683 case ISD::BSWAP: return combineBSWAP(N, DCI);
9684 case ISD::SETCC: return combineSETCC(N, DCI);
9685 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9686 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9687 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9688 case ISD::SRL:
9689 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9690 case ISD::MUL: return combineMUL(N, DCI);
9691 case ISD::SDIV:
9692 case ISD::UDIV:
9693 case ISD::SREM:
9694 case ISD::UREM: return combineIntDIVREM(N, DCI);
9696 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9697 }
9698
9699 return SDValue();
9700}
9701
9702// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9703// are for Op.
9704static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9705 unsigned OpNo) {
9706 EVT VT = Op.getValueType();
9707 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9708 APInt SrcDemE;
9709 unsigned Opcode = Op.getOpcode();
9710 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9711 unsigned Id = Op.getConstantOperandVal(0);
9712 switch (Id) {
9713 case Intrinsic::s390_vpksh: // PACKS
9714 case Intrinsic::s390_vpksf:
9715 case Intrinsic::s390_vpksg:
9716 case Intrinsic::s390_vpkshs: // PACKS_CC
9717 case Intrinsic::s390_vpksfs:
9718 case Intrinsic::s390_vpksgs:
9719 case Intrinsic::s390_vpklsh: // PACKLS
9720 case Intrinsic::s390_vpklsf:
9721 case Intrinsic::s390_vpklsg:
9722 case Intrinsic::s390_vpklshs: // PACKLS_CC
9723 case Intrinsic::s390_vpklsfs:
9724 case Intrinsic::s390_vpklsgs:
9725 // VECTOR PACK truncates the elements of two source vectors into one.
9726 SrcDemE = DemandedElts;
9727 if (OpNo == 2)
9728 SrcDemE.lshrInPlace(NumElts / 2);
9729 SrcDemE = SrcDemE.trunc(NumElts / 2);
9730 break;
9731 // VECTOR UNPACK extends half the elements of the source vector.
9732 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9733 case Intrinsic::s390_vuphh:
9734 case Intrinsic::s390_vuphf:
9735 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9736 case Intrinsic::s390_vuplhh:
9737 case Intrinsic::s390_vuplhf:
9738 SrcDemE = APInt(NumElts * 2, 0);
9739 SrcDemE.insertBits(DemandedElts, 0);
9740 break;
9741 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9742 case Intrinsic::s390_vuplhw:
9743 case Intrinsic::s390_vuplf:
9744 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9745 case Intrinsic::s390_vupllh:
9746 case Intrinsic::s390_vupllf:
9747 SrcDemE = APInt(NumElts * 2, 0);
9748 SrcDemE.insertBits(DemandedElts, NumElts);
9749 break;
9750 case Intrinsic::s390_vpdi: {
9751 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9752 SrcDemE = APInt(NumElts, 0);
9753 if (!DemandedElts[OpNo - 1])
9754 break;
9755 unsigned Mask = Op.getConstantOperandVal(3);
9756 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9757 // Demand input element 0 or 1, given by the mask bit value.
9758 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9759 break;
9760 }
9761 case Intrinsic::s390_vsldb: {
9762 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9763 assert(VT == MVT::v16i8 && "Unexpected type.");
9764 unsigned FirstIdx = Op.getConstantOperandVal(3);
9765 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9766 unsigned NumSrc0Els = 16 - FirstIdx;
9767 SrcDemE = APInt(NumElts, 0);
9768 if (OpNo == 1) {
9769 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9770 SrcDemE.insertBits(DemEls, FirstIdx);
9771 } else {
9772 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9773 SrcDemE.insertBits(DemEls, 0);
9774 }
9775 break;
9776 }
9777 case Intrinsic::s390_vperm:
9778 SrcDemE = APInt::getAllOnes(NumElts);
9779 break;
9780 default:
9781 llvm_unreachable("Unhandled intrinsic.");
9782 break;
9783 }
9784 } else {
9785 switch (Opcode) {
9786 case SystemZISD::JOIN_DWORDS:
9787 // Scalar operand.
9788 SrcDemE = APInt(1, 1);
9789 break;
9790 case SystemZISD::SELECT_CCMASK:
9791 SrcDemE = DemandedElts;
9792 break;
9793 default:
9794 llvm_unreachable("Unhandled opcode.");
9795 break;
9796 }
9797 }
9798 return SrcDemE;
9799}
9800
9802 const APInt &DemandedElts,
9803 const SelectionDAG &DAG, unsigned Depth,
9804 unsigned OpNo) {
9805 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9806 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9807 KnownBits LHSKnown =
9808 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9809 KnownBits RHSKnown =
9810 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9811 Known = LHSKnown.intersectWith(RHSKnown);
9812}
9813
9814void
9817 const APInt &DemandedElts,
9818 const SelectionDAG &DAG,
9819 unsigned Depth) const {
9820 Known.resetAll();
9821
9822 // Intrinsic CC result is returned in the two low bits.
9823 unsigned Tmp0, Tmp1; // not used
9824 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9825 Known.Zero.setBitsFrom(2);
9826 return;
9827 }
9828 [[maybe_unused]] EVT VT = Op.getValueType();
9829 if (Op.getResNo() != 0)
9830 return;
9831 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9832 "KnownBits does not match VT in bitwidth");
9833 assert ((!VT.isVector() ||
9834 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9835 "DemandedElts does not match VT number of elements");
9836 unsigned BitWidth = Known.getBitWidth();
9837 unsigned Opcode = Op.getOpcode();
9838 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9839 bool IsLogical = false;
9840 unsigned Id = Op.getConstantOperandVal(0);
9841 switch (Id) {
9842 case Intrinsic::s390_vpksh: // PACKS
9843 case Intrinsic::s390_vpksf:
9844 case Intrinsic::s390_vpksg:
9845 case Intrinsic::s390_vpkshs: // PACKS_CC
9846 case Intrinsic::s390_vpksfs:
9847 case Intrinsic::s390_vpksgs:
9848 case Intrinsic::s390_vpklsh: // PACKLS
9849 case Intrinsic::s390_vpklsf:
9850 case Intrinsic::s390_vpklsg:
9851 case Intrinsic::s390_vpklshs: // PACKLS_CC
9852 case Intrinsic::s390_vpklsfs:
9853 case Intrinsic::s390_vpklsgs:
9854 case Intrinsic::s390_vpdi:
9855 case Intrinsic::s390_vsldb:
9856 case Intrinsic::s390_vperm:
9857 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9858 break;
9859 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9860 case Intrinsic::s390_vuplhh:
9861 case Intrinsic::s390_vuplhf:
9862 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9863 case Intrinsic::s390_vupllh:
9864 case Intrinsic::s390_vupllf:
9865 IsLogical = true;
9866 [[fallthrough]];
9867 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9868 case Intrinsic::s390_vuphh:
9869 case Intrinsic::s390_vuphf:
9870 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9871 case Intrinsic::s390_vuplhw:
9872 case Intrinsic::s390_vuplf: {
9873 SDValue SrcOp = Op.getOperand(1);
9874 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9875 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9876 if (IsLogical) {
9877 Known = Known.zext(BitWidth);
9878 } else
9879 Known = Known.sext(BitWidth);
9880 break;
9881 }
9882 default:
9883 break;
9884 }
9885 } else {
9886 switch (Opcode) {
9887 case SystemZISD::JOIN_DWORDS:
9888 case SystemZISD::SELECT_CCMASK:
9889 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9890 break;
9891 case SystemZISD::REPLICATE: {
9892 SDValue SrcOp = Op.getOperand(0);
9893 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9894 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9895 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9896 break;
9897 }
9898 default:
9899 break;
9900 }
9901 }
9902
9903 // Known has the width of the source operand(s). Adjust if needed to match
9904 // the passed bitwidth.
9905 if (Known.getBitWidth() != BitWidth)
9906 Known = Known.anyextOrTrunc(BitWidth);
9907}
9908
9909static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9910 const SelectionDAG &DAG, unsigned Depth,
9911 unsigned OpNo) {
9912 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9913 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9914 if (LHS == 1) return 1; // Early out.
9915 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9916 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9917 if (RHS == 1) return 1; // Early out.
9918 unsigned Common = std::min(LHS, RHS);
9919 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9920 EVT VT = Op.getValueType();
9921 unsigned VTBits = VT.getScalarSizeInBits();
9922 if (SrcBitWidth > VTBits) { // PACK
9923 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9924 if (Common > SrcExtraBits)
9925 return (Common - SrcExtraBits);
9926 return 1;
9927 }
9928 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9929 return Common;
9930}
9931
9932unsigned
9934 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9935 unsigned Depth) const {
9936 if (Op.getResNo() != 0)
9937 return 1;
9938 unsigned Opcode = Op.getOpcode();
9939 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9940 unsigned Id = Op.getConstantOperandVal(0);
9941 switch (Id) {
9942 case Intrinsic::s390_vpksh: // PACKS
9943 case Intrinsic::s390_vpksf:
9944 case Intrinsic::s390_vpksg:
9945 case Intrinsic::s390_vpkshs: // PACKS_CC
9946 case Intrinsic::s390_vpksfs:
9947 case Intrinsic::s390_vpksgs:
9948 case Intrinsic::s390_vpklsh: // PACKLS
9949 case Intrinsic::s390_vpklsf:
9950 case Intrinsic::s390_vpklsg:
9951 case Intrinsic::s390_vpklshs: // PACKLS_CC
9952 case Intrinsic::s390_vpklsfs:
9953 case Intrinsic::s390_vpklsgs:
9954 case Intrinsic::s390_vpdi:
9955 case Intrinsic::s390_vsldb:
9956 case Intrinsic::s390_vperm:
9957 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9958 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9959 case Intrinsic::s390_vuphh:
9960 case Intrinsic::s390_vuphf:
9961 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9962 case Intrinsic::s390_vuplhw:
9963 case Intrinsic::s390_vuplf: {
9964 SDValue PackedOp = Op.getOperand(1);
9965 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9966 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9967 EVT VT = Op.getValueType();
9968 unsigned VTBits = VT.getScalarSizeInBits();
9969 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9970 return Tmp;
9971 }
9972 default:
9973 break;
9974 }
9975 } else {
9976 switch (Opcode) {
9977 case SystemZISD::SELECT_CCMASK:
9978 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9979 default:
9980 break;
9981 }
9982 }
9983
9984 return 1;
9985}
9986
9988 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9989 UndefPoisonKind Kind, unsigned Depth) const {
9990 switch (Op->getOpcode()) {
9991 case SystemZISD::PCREL_WRAPPER:
9992 case SystemZISD::PCREL_OFFSET:
9993 return true;
9994 }
9995 return false;
9996}
9997
9998unsigned
10000 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
10001 unsigned StackAlign = TFI->getStackAlignment();
10002 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
10003 "Unexpected stack alignment");
10004 // The default stack probe size is 4096 if the function has no
10005 // stack-probe-size attribute.
10006 unsigned StackProbeSize =
10007 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
10008 // Round down to the stack alignment.
10009 StackProbeSize &= ~(StackAlign - 1);
10010 return StackProbeSize ? StackProbeSize : StackAlign;
10011}
10012
10013//===----------------------------------------------------------------------===//
10014// Custom insertion
10015//===----------------------------------------------------------------------===//
10016
10017// Force base value Base into a register before MI. Return the register.
10019 const SystemZInstrInfo *TII) {
10020 MachineBasicBlock *MBB = MI.getParent();
10021 MachineFunction &MF = *MBB->getParent();
10023
10024 if (Base.isReg()) {
10025 // Copy Base into a new virtual register to help register coalescing in
10026 // cases with multiple uses.
10027 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10028 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
10029 .add(Base);
10030 return Reg;
10031 }
10032
10033 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10034 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
10035 .add(Base)
10036 .addImm(0)
10037 .addReg(0);
10038 return Reg;
10039}
10040
10041// The CC operand of MI might be missing a kill marker because there
10042// were multiple uses of CC, and ISel didn't know which to mark.
10043// Figure out whether MI should have had a kill marker.
10045 // Scan forward through BB for a use/def of CC.
10047 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
10048 const MachineInstr &MI = *miI;
10049 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
10050 return false;
10051 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
10052 break; // Should have kill-flag - update below.
10053 }
10054
10055 // If we hit the end of the block, check whether CC is live into a
10056 // successor.
10057 if (miI == MBB->end()) {
10058 for (const MachineBasicBlock *Succ : MBB->successors())
10059 if (Succ->isLiveIn(SystemZ::CC))
10060 return false;
10061 }
10062
10063 return true;
10064}
10065
10066// Return true if it is OK for this Select pseudo-opcode to be cascaded
10067// together with other Select pseudo-opcodes into a single basic-block with
10068// a conditional jump around it.
10070 switch (MI.getOpcode()) {
10071 case SystemZ::Select32:
10072 case SystemZ::Select64:
10073 case SystemZ::Select128:
10074 case SystemZ::SelectF32:
10075 case SystemZ::SelectF64:
10076 case SystemZ::SelectF128:
10077 case SystemZ::SelectVR32:
10078 case SystemZ::SelectVR64:
10079 case SystemZ::SelectVR128:
10080 return true;
10081
10082 default:
10083 return false;
10084 }
10085}
10086
10087// Helper function, which inserts PHI functions into SinkMBB:
10088// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
10089// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
10091 MachineBasicBlock *TrueMBB,
10092 MachineBasicBlock *FalseMBB,
10093 MachineBasicBlock *SinkMBB) {
10094 MachineFunction *MF = TrueMBB->getParent();
10096
10097 MachineInstr *FirstMI = Selects.front();
10098 unsigned CCValid = FirstMI->getOperand(3).getImm();
10099 unsigned CCMask = FirstMI->getOperand(4).getImm();
10100
10101 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
10102
10103 // As we are creating the PHIs, we have to be careful if there is more than
10104 // one. Later Selects may reference the results of earlier Selects, but later
10105 // PHIs have to reference the individual true/false inputs from earlier PHIs.
10106 // That also means that PHI construction must work forward from earlier to
10107 // later, and that the code must maintain a mapping from earlier PHI's
10108 // destination registers, and the registers that went into the PHI.
10110
10111 for (auto *MI : Selects) {
10112 Register DestReg = MI->getOperand(0).getReg();
10113 Register TrueReg = MI->getOperand(1).getReg();
10114 Register FalseReg = MI->getOperand(2).getReg();
10115
10116 // If this Select we are generating is the opposite condition from
10117 // the jump we generated, then we have to swap the operands for the
10118 // PHI that is going to be generated.
10119 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
10120 std::swap(TrueReg, FalseReg);
10121
10122 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
10123 TrueReg = It->second.first;
10124
10125 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
10126 FalseReg = It->second.second;
10127
10128 DebugLoc DL = MI->getDebugLoc();
10129 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
10130 .addReg(TrueReg).addMBB(TrueMBB)
10131 .addReg(FalseReg).addMBB(FalseMBB);
10132
10133 // Add this PHI to the rewrite table.
10134 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
10135 }
10136
10137 MF->getProperties().resetNoPHIs();
10138}
10139
10141SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
10142 MachineBasicBlock *BB) const {
10143 MachineFunction &MF = *BB->getParent();
10144 MachineFrameInfo &MFI = MF.getFrameInfo();
10145 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
10146 assert(TFL->hasReservedCallFrame(MF) &&
10147 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
10148 (void)TFL;
10149 // Get the MaxCallFrameSize value and erase MI since it serves no further
10150 // purpose as the call frame is statically reserved in the prolog. Set
10151 // AdjustsStack as MI is *not* mapped as a frame instruction.
10152 uint32_t NumBytes = MI.getOperand(0).getImm();
10153 if (NumBytes > MFI.getMaxCallFrameSize())
10154 MFI.setMaxCallFrameSize(NumBytes);
10155 MFI.setAdjustsStack(true);
10156
10157 MI.eraseFromParent();
10158 return BB;
10159}
10160
10161// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
10163SystemZTargetLowering::emitSelect(MachineInstr &MI,
10164 MachineBasicBlock *MBB) const {
10165 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
10166 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10167
10168 unsigned CCValid = MI.getOperand(3).getImm();
10169 unsigned CCMask = MI.getOperand(4).getImm();
10170
10171 // If we have a sequence of Select* pseudo instructions using the
10172 // same condition code value, we want to expand all of them into
10173 // a single pair of basic blocks using the same condition.
10174 SmallVector<MachineInstr*, 8> Selects;
10175 SmallVector<MachineInstr*, 8> DbgValues;
10176 Selects.push_back(&MI);
10177 unsigned Count = 0;
10178 for (MachineInstr &NextMI : llvm::make_range(
10179 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
10180 if (isSelectPseudo(NextMI)) {
10181 assert(NextMI.getOperand(3).getImm() == CCValid &&
10182 "Bad CCValid operands since CC was not redefined.");
10183 if (NextMI.getOperand(4).getImm() == CCMask ||
10184 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
10185 Selects.push_back(&NextMI);
10186 continue;
10187 }
10188 break;
10189 }
10190 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10191 NextMI.usesCustomInsertionHook())
10192 break;
10193 bool User = false;
10194 for (auto *SelMI : Selects)
10195 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
10196 User = true;
10197 break;
10198 }
10199 if (NextMI.isDebugInstr()) {
10200 if (User) {
10201 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
10202 DbgValues.push_back(&NextMI);
10203 }
10204 } else if (User || ++Count > 20)
10205 break;
10206 }
10207
10208 MachineInstr *LastMI = Selects.back();
10209 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10210 checkCCKill(*LastMI, MBB));
10211 MachineBasicBlock *StartMBB = MBB;
10212 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
10213 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10214
10215 // Unless CC was killed in the last Select instruction, mark it as
10216 // live-in to both FalseMBB and JoinMBB.
10217 if (!CCKilled) {
10218 FalseMBB->addLiveIn(SystemZ::CC);
10219 JoinMBB->addLiveIn(SystemZ::CC);
10220 }
10221
10222 // StartMBB:
10223 // BRC CCMask, JoinMBB
10224 // # fallthrough to FalseMBB
10225 MBB = StartMBB;
10226 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10227 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10228 MBB->addSuccessor(JoinMBB);
10229 MBB->addSuccessor(FalseMBB);
10230
10231 // FalseMBB:
10232 // # fallthrough to JoinMBB
10233 MBB = FalseMBB;
10234 MBB->addSuccessor(JoinMBB);
10235
10236 // JoinMBB:
10237 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
10238 // ...
10239 MBB = JoinMBB;
10240 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
10241 for (auto *SelMI : Selects)
10242 SelMI->eraseFromParent();
10243
10245 for (auto *DbgMI : DbgValues)
10246 MBB->splice(InsertPos, StartMBB, DbgMI);
10247
10248 return JoinMBB;
10249}
10250
10251// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
10252// StoreOpcode is the store to use and Invert says whether the store should
10253// happen when the condition is false rather than true. If a STORE ON
10254// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10255MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10257 unsigned StoreOpcode,
10258 unsigned STOCOpcode,
10259 bool Invert) const {
10260 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10261
10262 Register SrcReg = MI.getOperand(0).getReg();
10263 MachineOperand Base = MI.getOperand(1);
10264 int64_t Disp = MI.getOperand(2).getImm();
10265 Register IndexReg = MI.getOperand(3).getReg();
10266 unsigned CCValid = MI.getOperand(4).getImm();
10267 unsigned CCMask = MI.getOperand(5).getImm();
10268 DebugLoc DL = MI.getDebugLoc();
10269
10270 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10271
10272 // ISel pattern matching also adds a load memory operand of the same
10273 // address, so take special care to find the storing memory operand.
10274 MachineMemOperand *MMO = nullptr;
10275 for (auto *I : MI.memoperands())
10276 if (I->isStore()) {
10277 MMO = I;
10278 break;
10279 }
10280
10281 // Use STOCOpcode if possible. We could use different store patterns in
10282 // order to avoid matching the index register, but the performance trade-offs
10283 // might be more complicated in that case.
10284 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10285 if (Invert)
10286 CCMask ^= CCValid;
10287
10288 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10289 .addReg(SrcReg)
10290 .add(Base)
10291 .addImm(Disp)
10292 .addImm(CCValid)
10293 .addImm(CCMask)
10294 .addMemOperand(MMO);
10295
10296 MI.eraseFromParent();
10297 return MBB;
10298 }
10299
10300 // Get the condition needed to branch around the store.
10301 if (!Invert)
10302 CCMask ^= CCValid;
10303
10304 MachineBasicBlock *StartMBB = MBB;
10305 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10306 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10307
10308 // Unless CC was killed in the CondStore instruction, mark it as
10309 // live-in to both FalseMBB and JoinMBB.
10310 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10311 !checkCCKill(MI, JoinMBB)) {
10312 FalseMBB->addLiveIn(SystemZ::CC);
10313 JoinMBB->addLiveIn(SystemZ::CC);
10314 }
10315
10316 // StartMBB:
10317 // BRC CCMask, JoinMBB
10318 // # fallthrough to FalseMBB
10319 MBB = StartMBB;
10320 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10321 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10322 MBB->addSuccessor(JoinMBB);
10323 MBB->addSuccessor(FalseMBB);
10324
10325 // FalseMBB:
10326 // store %SrcReg, %Disp(%Index,%Base)
10327 // # fallthrough to JoinMBB
10328 MBB = FalseMBB;
10329 BuildMI(MBB, DL, TII->get(StoreOpcode))
10330 .addReg(SrcReg)
10331 .add(Base)
10332 .addImm(Disp)
10333 .addReg(IndexReg)
10334 .addMemOperand(MMO);
10335 MBB->addSuccessor(JoinMBB);
10336
10337 MI.eraseFromParent();
10338 return JoinMBB;
10339}
10340
10341// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10343SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10345 bool Unsigned) const {
10346 MachineFunction &MF = *MBB->getParent();
10347 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10348 MachineRegisterInfo &MRI = MF.getRegInfo();
10349
10350 // Synthetic instruction to compare 128-bit values.
10351 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10352 Register Op0 = MI.getOperand(0).getReg();
10353 Register Op1 = MI.getOperand(1).getReg();
10354
10355 MachineBasicBlock *StartMBB = MBB;
10356 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10357 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10358
10359 // StartMBB:
10360 //
10361 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10362 // Swap the inputs to get:
10363 // CC 1 if high(Op0) > high(Op1)
10364 // CC 2 if high(Op0) < high(Op1)
10365 // CC 0 if high(Op0) == high(Op1)
10366 //
10367 // If CC != 0, we'd done, so jump over the next instruction.
10368 //
10369 // VEC[L]G Op1, Op0
10370 // JNE JoinMBB
10371 // # fallthrough to HiEqMBB
10372 MBB = StartMBB;
10373 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10374 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10375 .addReg(Op1).addReg(Op0);
10376 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10378 MBB->addSuccessor(JoinMBB);
10379 MBB->addSuccessor(HiEqMBB);
10380
10381 // HiEqMBB:
10382 //
10383 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10384 // Since we already know the high parts are equal, the CC
10385 // result will only depend on the low parts:
10386 // CC 1 if low(Op0) > low(Op1)
10387 // CC 3 if low(Op0) <= low(Op1)
10388 //
10389 // VCHLGS Tmp, Op0, Op1
10390 // # fallthrough to JoinMBB
10391 MBB = HiEqMBB;
10392 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10393 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10394 .addReg(Op0).addReg(Op1);
10395 MBB->addSuccessor(JoinMBB);
10396
10397 // Mark CC as live-in to JoinMBB.
10398 JoinMBB->addLiveIn(SystemZ::CC);
10399
10400 MI.eraseFromParent();
10401 return JoinMBB;
10402}
10403
10404// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10405// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10406// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10407// whether the field should be inverted after performing BinOpcode (e.g. for
10408// NAND).
10409MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10410 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10411 bool Invert) const {
10412 MachineFunction &MF = *MBB->getParent();
10413 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10414 MachineRegisterInfo &MRI = MF.getRegInfo();
10415
10416 // Extract the operands. Base can be a register or a frame index.
10417 // Src2 can be a register or immediate.
10418 Register Dest = MI.getOperand(0).getReg();
10419 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10420 int64_t Disp = MI.getOperand(2).getImm();
10421 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10422 Register BitShift = MI.getOperand(4).getReg();
10423 Register NegBitShift = MI.getOperand(5).getReg();
10424 unsigned BitSize = MI.getOperand(6).getImm();
10425 DebugLoc DL = MI.getDebugLoc();
10426
10427 // Get the right opcodes for the displacement.
10428 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10429 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10430 assert(LOpcode && CSOpcode && "Displacement out of range");
10431
10432 // Create virtual registers for temporary results.
10433 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10434 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10435 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10436 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10437 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10438
10439 // Insert a basic block for the main loop.
10440 MachineBasicBlock *StartMBB = MBB;
10441 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10442 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10443
10444 // StartMBB:
10445 // ...
10446 // %OrigVal = L Disp(%Base)
10447 // # fall through to LoopMBB
10448 MBB = StartMBB;
10449 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10450 MBB->addSuccessor(LoopMBB);
10451
10452 // LoopMBB:
10453 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10454 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10455 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10456 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10457 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10458 // JNE LoopMBB
10459 // # fall through to DoneMBB
10460 MBB = LoopMBB;
10461 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10462 .addReg(OrigVal).addMBB(StartMBB)
10463 .addReg(Dest).addMBB(LoopMBB);
10464 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10465 .addReg(OldVal).addReg(BitShift).addImm(0);
10466 if (Invert) {
10467 // Perform the operation normally and then invert every bit of the field.
10468 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10469 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
10470 .addReg(RotatedOldVal)
10471 .add(Src2)
10472 .setOperandDead(3);
10473 // XILF with the upper BitSize bits set.
10474 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10475 .addReg(Tmp)
10476 .addImm(-1U << (32 - BitSize))
10477 .setOperandDead(3);
10478 } else if (BinOpcode)
10479 // A simply binary operation.
10480 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10481 .addReg(RotatedOldVal)
10482 .add(Src2)
10483 .setOperandDead(3);
10484 else
10485 // Use RISBG to rotate Src2 into position and use it to replace the
10486 // field in RotatedOldVal.
10487 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10488 .addReg(RotatedOldVal)
10489 .addReg(Src2.getReg())
10490 .addImm(32)
10491 .addImm(31 + BitSize)
10492 .addImm(32 - BitSize)
10493 .setOperandDead(6);
10494 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10495 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10496 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10497 .addReg(OldVal)
10498 .addReg(NewVal)
10499 .add(Base)
10500 .addImm(Disp);
10501 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10503 MBB->addSuccessor(LoopMBB);
10504 MBB->addSuccessor(DoneMBB);
10505
10506 MI.eraseFromParent();
10507 return DoneMBB;
10508}
10509
10510// Implement EmitInstrWithCustomInserter for subword pseudo
10511// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10512// instruction that should be used to compare the current field with the
10513// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10514// for when the current field should be kept.
10515MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10516 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10517 unsigned KeepOldMask) const {
10518 MachineFunction &MF = *MBB->getParent();
10519 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10520 MachineRegisterInfo &MRI = MF.getRegInfo();
10521
10522 // Extract the operands. Base can be a register or a frame index.
10523 Register Dest = MI.getOperand(0).getReg();
10524 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10525 int64_t Disp = MI.getOperand(2).getImm();
10526 Register Src2 = MI.getOperand(3).getReg();
10527 Register BitShift = MI.getOperand(4).getReg();
10528 Register NegBitShift = MI.getOperand(5).getReg();
10529 unsigned BitSize = MI.getOperand(6).getImm();
10530 DebugLoc DL = MI.getDebugLoc();
10531
10532 // Get the right opcodes for the displacement.
10533 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10534 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10535 assert(LOpcode && CSOpcode && "Displacement out of range");
10536
10537 // Create virtual registers for temporary results.
10538 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10539 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10540 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10541 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10542 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10543 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10544
10545 // Insert 3 basic blocks for the loop.
10546 MachineBasicBlock *StartMBB = MBB;
10547 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10548 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10549 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10550 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10551
10552 // StartMBB:
10553 // ...
10554 // %OrigVal = L Disp(%Base)
10555 // # fall through to LoopMBB
10556 MBB = StartMBB;
10557 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10558 MBB->addSuccessor(LoopMBB);
10559
10560 // LoopMBB:
10561 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10562 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10563 // CompareOpcode %RotatedOldVal, %Src2
10564 // BRC KeepOldMask, UpdateMBB
10565 MBB = LoopMBB;
10566 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10567 .addReg(OrigVal).addMBB(StartMBB)
10568 .addReg(Dest).addMBB(UpdateMBB);
10569 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10570 .addReg(OldVal).addReg(BitShift).addImm(0);
10571 BuildMI(MBB, DL, TII->get(CompareOpcode))
10572 .addReg(RotatedOldVal).addReg(Src2);
10573 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10574 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10575 MBB->addSuccessor(UpdateMBB);
10576 MBB->addSuccessor(UseAltMBB);
10577
10578 // UseAltMBB:
10579 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10580 // # fall through to UpdateMBB
10581 MBB = UseAltMBB;
10582 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10583 .addReg(RotatedOldVal)
10584 .addReg(Src2)
10585 .addImm(32)
10586 .addImm(31 + BitSize)
10587 .addImm(0)
10588 .setOperandDead(6);
10589 MBB->addSuccessor(UpdateMBB);
10590
10591 // UpdateMBB:
10592 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10593 // [ %RotatedAltVal, UseAltMBB ]
10594 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10595 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10596 // JNE LoopMBB
10597 // # fall through to DoneMBB
10598 MBB = UpdateMBB;
10599 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10600 .addReg(RotatedOldVal).addMBB(LoopMBB)
10601 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10602 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10603 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10604 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10605 .addReg(OldVal)
10606 .addReg(NewVal)
10607 .add(Base)
10608 .addImm(Disp);
10609 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10611 MBB->addSuccessor(LoopMBB);
10612 MBB->addSuccessor(DoneMBB);
10613
10614 MI.eraseFromParent();
10615 return DoneMBB;
10616}
10617
10618// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10619// instruction MI.
10621SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10622 MachineBasicBlock *MBB) const {
10623 MachineFunction &MF = *MBB->getParent();
10624 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10625 MachineRegisterInfo &MRI = MF.getRegInfo();
10626
10627 // Extract the operands. Base can be a register or a frame index.
10628 Register Dest = MI.getOperand(0).getReg();
10629 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10630 int64_t Disp = MI.getOperand(2).getImm();
10631 Register CmpVal = MI.getOperand(3).getReg();
10632 Register OrigSwapVal = MI.getOperand(4).getReg();
10633 Register BitShift = MI.getOperand(5).getReg();
10634 Register NegBitShift = MI.getOperand(6).getReg();
10635 int64_t BitSize = MI.getOperand(7).getImm();
10636 DebugLoc DL = MI.getDebugLoc();
10637
10638 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10639
10640 // Get the right opcodes for the displacement and zero-extension.
10641 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10642 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10643 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10644 assert(LOpcode && CSOpcode && "Displacement out of range");
10645
10646 // Create virtual registers for temporary results.
10647 Register OrigOldVal = MRI.createVirtualRegister(RC);
10648 Register OldVal = MRI.createVirtualRegister(RC);
10649 Register SwapVal = MRI.createVirtualRegister(RC);
10650 Register StoreVal = MRI.createVirtualRegister(RC);
10651 Register OldValRot = MRI.createVirtualRegister(RC);
10652 Register RetryOldVal = MRI.createVirtualRegister(RC);
10653 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10654
10655 // Insert 2 basic blocks for the loop.
10656 MachineBasicBlock *StartMBB = MBB;
10657 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10658 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10659 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10660
10661 // StartMBB:
10662 // ...
10663 // %OrigOldVal = L Disp(%Base)
10664 // # fall through to LoopMBB
10665 MBB = StartMBB;
10666 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10667 .add(Base)
10668 .addImm(Disp)
10669 .addReg(0);
10670 MBB->addSuccessor(LoopMBB);
10671
10672 // LoopMBB:
10673 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10674 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10675 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10676 // ^^ The low BitSize bits contain the field
10677 // of interest.
10678 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10679 // ^^ Replace the upper 32-BitSize bits of the
10680 // swap value with those that we loaded and rotated.
10681 // %Dest = LL[CH] %OldValRot
10682 // CR %Dest, %CmpVal
10683 // JNE DoneMBB
10684 // # Fall through to SetMBB
10685 MBB = LoopMBB;
10686 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10687 .addReg(OrigOldVal).addMBB(StartMBB)
10688 .addReg(RetryOldVal).addMBB(SetMBB);
10689 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10690 .addReg(OrigSwapVal).addMBB(StartMBB)
10691 .addReg(RetrySwapVal).addMBB(SetMBB);
10692 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10693 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10694 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10695 .addReg(SwapVal)
10696 .addReg(OldValRot)
10697 .addImm(32)
10698 .addImm(63 - BitSize)
10699 .addImm(0)
10700 .setOperandDead(6);
10701 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10702 .addReg(OldValRot);
10703 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10704 .addReg(Dest).addReg(CmpVal);
10705 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10708 MBB->addSuccessor(DoneMBB);
10709 MBB->addSuccessor(SetMBB);
10710
10711 // SetMBB:
10712 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10713 // ^^ Rotate the new field to its proper position.
10714 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10715 // JNE LoopMBB
10716 // # fall through to ExitMBB
10717 MBB = SetMBB;
10718 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10719 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10720 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10721 .addReg(OldVal)
10722 .addReg(StoreVal)
10723 .add(Base)
10724 .addImm(Disp);
10725 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10727 MBB->addSuccessor(LoopMBB);
10728 MBB->addSuccessor(DoneMBB);
10729
10730 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10731 // to the block after the loop. At this point, CC may have been defined
10732 // either by the CR in LoopMBB or by the CS in SetMBB.
10733 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10734 DoneMBB->addLiveIn(SystemZ::CC);
10735
10736 MI.eraseFromParent();
10737 return DoneMBB;
10738}
10739
10741SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10743 unsigned Opcode, bool IsMemset) const {
10744 MachineFunction &MF = *MBB->getParent();
10745 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10746 MachineRegisterInfo &MRI = MF.getRegInfo();
10747 DebugLoc DL = MI.getDebugLoc();
10748
10749 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10750 uint64_t DestDisp = MI.getOperand(1).getImm();
10751 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10752 uint64_t SrcDisp;
10753
10754 // Fold the displacement Disp if it is out of range.
10755 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10756 if (!isUInt<12>(Disp)) {
10757 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10758 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10759 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10760 .add(Base).addImm(Disp).addReg(0);
10762 Disp = 0;
10763 }
10764 };
10765
10766 if (!IsMemset) {
10767 SrcBase = earlyUseOperand(MI.getOperand(2));
10768 SrcDisp = MI.getOperand(3).getImm();
10769 } else {
10770 SrcBase = DestBase;
10771 SrcDisp = DestDisp++;
10772 foldDisplIfNeeded(DestBase, DestDisp);
10773 }
10774
10775 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10776 bool IsImmForm = LengthMO.isImm();
10777 bool IsRegForm = !IsImmForm;
10778
10779 // Build and insert one Opcode of Length, with special treatment for memset.
10780 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10782 MachineOperand DBase, uint64_t DDisp,
10783 MachineOperand SBase, uint64_t SDisp,
10784 unsigned Length) -> void {
10785 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10786 if (IsMemset) {
10787 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10788 if (ByteMO.isImm())
10789 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10790 .add(SBase).addImm(SDisp).add(ByteMO);
10791 else
10792 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10793 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10794 if (--Length == 0)
10795 return;
10796 }
10797 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10798 .add(DBase).addImm(DDisp).addImm(Length)
10799 .add(SBase).addImm(SDisp)
10800 .setMemRefs(MI.memoperands());
10801 };
10802
10803 bool NeedsLoop = false;
10804 uint64_t ImmLength = 0;
10805 Register LenAdjReg = SystemZ::NoRegister;
10806 if (IsImmForm) {
10807 ImmLength = LengthMO.getImm();
10808 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10809 if (ImmLength == 0) {
10810 MI.eraseFromParent();
10811 return MBB;
10812 }
10813 if (Opcode == SystemZ::CLC) {
10814 if (ImmLength > 3 * 256)
10815 // A two-CLC sequence is a clear win over a loop, not least because
10816 // it needs only one branch. A three-CLC sequence needs the same
10817 // number of branches as a loop (i.e. 2), but is shorter. That
10818 // brings us to lengths greater than 768 bytes. It seems relatively
10819 // likely that a difference will be found within the first 768 bytes,
10820 // so we just optimize for the smallest number of branch
10821 // instructions, in order to avoid polluting the prediction buffer
10822 // too much.
10823 NeedsLoop = true;
10824 } else if (ImmLength > 6 * 256)
10825 // The heuristic we use is to prefer loops for anything that would
10826 // require 7 or more MVCs. With these kinds of sizes there isn't much
10827 // to choose between straight-line code and looping code, since the
10828 // time will be dominated by the MVCs themselves.
10829 NeedsLoop = true;
10830 } else {
10831 NeedsLoop = true;
10832 LenAdjReg = LengthMO.getReg();
10833 }
10834
10835 // When generating more than one CLC, all but the last will need to
10836 // branch to the end when a difference is found.
10837 MachineBasicBlock *EndMBB =
10838 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10840 : nullptr);
10841
10842 if (NeedsLoop) {
10843 Register StartCountReg =
10844 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10845 if (IsImmForm) {
10846 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10847 ImmLength &= 255;
10848 } else {
10849 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10850 .addReg(LenAdjReg)
10851 .addReg(0)
10852 .addImm(8);
10853 }
10854
10855 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10856 auto loadZeroAddress = [&]() -> MachineOperand {
10857 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10858 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10859 return MachineOperand::CreateReg(Reg, false);
10860 };
10861 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10862 DestBase = loadZeroAddress();
10863 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10864 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10865
10866 MachineBasicBlock *StartMBB = nullptr;
10867 MachineBasicBlock *LoopMBB = nullptr;
10868 MachineBasicBlock *NextMBB = nullptr;
10869 MachineBasicBlock *DoneMBB = nullptr;
10870 MachineBasicBlock *AllDoneMBB = nullptr;
10871
10872 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10873 Register StartDestReg =
10874 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10875
10876 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10877 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10878 Register ThisDestReg =
10879 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10880 Register NextSrcReg = MRI.createVirtualRegister(RC);
10881 Register NextDestReg =
10882 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10883 RC = &SystemZ::GR64BitRegClass;
10884 Register ThisCountReg = MRI.createVirtualRegister(RC);
10885 Register NextCountReg = MRI.createVirtualRegister(RC);
10886
10887 if (IsRegForm) {
10888 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10889 StartMBB = SystemZ::emitBlockAfter(MBB);
10890 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10891 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10892 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10893
10894 // MBB:
10895 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10896 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10897 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10898 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10900 .addMBB(AllDoneMBB);
10901 MBB->addSuccessor(AllDoneMBB);
10902 if (!IsMemset)
10903 MBB->addSuccessor(StartMBB);
10904 else {
10905 // MemsetOneCheckMBB:
10906 // # Jump to MemsetOneMBB for a memset of length 1, or
10907 // # fall thru to StartMBB.
10908 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10909 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10910 MBB->addSuccessor(MemsetOneCheckMBB);
10911 MBB = MemsetOneCheckMBB;
10912 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10913 .addReg(LenAdjReg).addImm(-1);
10914 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10916 .addMBB(MemsetOneMBB);
10917 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10918 MBB->addSuccessor(StartMBB, {90, 100});
10919
10920 // MemsetOneMBB:
10921 // # Jump back to AllDoneMBB after a single MVI or STC.
10922 MBB = MemsetOneMBB;
10923 insertMemMemOp(MBB, MBB->end(),
10924 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10925 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10926 1);
10927 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10928 MBB->addSuccessor(AllDoneMBB);
10929 }
10930
10931 // StartMBB:
10932 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10933 MBB = StartMBB;
10934 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10935 .addReg(StartCountReg).addImm(0);
10936 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10938 .addMBB(DoneMBB);
10939 MBB->addSuccessor(DoneMBB);
10940 MBB->addSuccessor(LoopMBB);
10941 }
10942 else {
10943 StartMBB = MBB;
10944 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10945 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10946 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10947
10948 // StartMBB:
10949 // # fall through to LoopMBB
10950 MBB->addSuccessor(LoopMBB);
10951
10952 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10953 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10954 if (EndMBB && !ImmLength)
10955 // If the loop handled the whole CLC range, DoneMBB will be empty with
10956 // CC live-through into EndMBB, so add it as live-in.
10957 DoneMBB->addLiveIn(SystemZ::CC);
10958 }
10959
10960 // LoopMBB:
10961 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10962 // [ %NextDestReg, NextMBB ]
10963 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10964 // [ %NextSrcReg, NextMBB ]
10965 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10966 // [ %NextCountReg, NextMBB ]
10967 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10968 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10969 // ( JLH EndMBB )
10970 //
10971 // The prefetch is used only for MVC. The JLH is used only for CLC.
10972 MBB = LoopMBB;
10973 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10974 .addReg(StartDestReg).addMBB(StartMBB)
10975 .addReg(NextDestReg).addMBB(NextMBB);
10976 if (!HaveSingleBase)
10977 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10978 .addReg(StartSrcReg).addMBB(StartMBB)
10979 .addReg(NextSrcReg).addMBB(NextMBB);
10980 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10981 .addReg(StartCountReg).addMBB(StartMBB)
10982 .addReg(NextCountReg).addMBB(NextMBB);
10983 if (Opcode == SystemZ::MVC)
10984 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10986 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10987 insertMemMemOp(MBB, MBB->end(),
10988 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10989 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10990 if (EndMBB) {
10991 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10993 .addMBB(EndMBB);
10994 MBB->addSuccessor(EndMBB);
10995 MBB->addSuccessor(NextMBB);
10996 }
10997
10998 // NextMBB:
10999 // %NextDestReg = LA 256(%ThisDestReg)
11000 // %NextSrcReg = LA 256(%ThisSrcReg)
11001 // %NextCountReg = AGHI %ThisCountReg, -1
11002 // CGHI %NextCountReg, 0
11003 // JLH LoopMBB
11004 // # fall through to DoneMBB
11005 //
11006 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
11007 MBB = NextMBB;
11008 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
11009 .addReg(ThisDestReg).addImm(256).addReg(0);
11010 if (!HaveSingleBase)
11011 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
11012 .addReg(ThisSrcReg).addImm(256).addReg(0);
11013 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
11014 .addReg(ThisCountReg)
11015 .addImm(-1)
11016 .setOperandDead(3);
11017 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11018 .addReg(NextCountReg).addImm(0);
11019 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11021 .addMBB(LoopMBB);
11022 MBB->addSuccessor(LoopMBB);
11023 MBB->addSuccessor(DoneMBB);
11024
11025 MBB = DoneMBB;
11026 if (IsRegForm) {
11027 // DoneMBB:
11028 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
11029 // # Use EXecute Relative Long for the remainder of the bytes. The target
11030 // instruction of the EXRL will have a length field of 1 since 0 is an
11031 // illegal value. The number of bytes processed becomes (%LenAdjReg &
11032 // 0xff) + 1.
11033 // # Fall through to AllDoneMBB.
11034 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11035 Register RemDestReg = HaveSingleBase ? RemSrcReg
11036 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11037 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
11038 .addReg(StartDestReg).addMBB(StartMBB)
11039 .addReg(NextDestReg).addMBB(NextMBB);
11040 if (!HaveSingleBase)
11041 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
11042 .addReg(StartSrcReg).addMBB(StartMBB)
11043 .addReg(NextSrcReg).addMBB(NextMBB);
11044 if (IsMemset)
11045 insertMemMemOp(MBB, MBB->end(),
11046 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
11047 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
11048 MachineInstrBuilder EXRL_MIB =
11049 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
11050 .addImm(Opcode)
11051 .addReg(LenAdjReg)
11052 .addReg(RemDestReg).addImm(DestDisp)
11053 .addReg(RemSrcReg).addImm(SrcDisp);
11054 MBB->addSuccessor(AllDoneMBB);
11055 MBB = AllDoneMBB;
11056 if (Opcode != SystemZ::MVC) {
11057 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
11058 if (EndMBB)
11059 MBB->addLiveIn(SystemZ::CC);
11060 }
11061 }
11062 MF.getProperties().resetNoPHIs();
11063 }
11064
11065 // Handle any remaining bytes with straight-line code.
11066 while (ImmLength > 0) {
11067 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
11068 // The previous iteration might have created out-of-range displacements.
11069 // Apply them using LA/LAY if so.
11070 foldDisplIfNeeded(DestBase, DestDisp);
11071 foldDisplIfNeeded(SrcBase, SrcDisp);
11072 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
11073 DestDisp += ThisLength;
11074 SrcDisp += ThisLength;
11075 ImmLength -= ThisLength;
11076 // If there's another CLC to go, branch to the end if a difference
11077 // was found.
11078 if (EndMBB && ImmLength > 0) {
11079 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
11080 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11082 .addMBB(EndMBB);
11083 MBB->addSuccessor(EndMBB);
11084 MBB->addSuccessor(NextMBB);
11085 MBB = NextMBB;
11086 }
11087 }
11088 if (EndMBB) {
11089 MBB->addSuccessor(EndMBB);
11090 MBB = EndMBB;
11091 MBB->addLiveIn(SystemZ::CC);
11092 }
11093
11094 MI.eraseFromParent();
11095 return MBB;
11096}
11097
11099SystemZTargetLowering::emitMemmoveImm(MachineInstr &MI,
11100 MachineBasicBlock *MBB) const {
11101 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11102
11103 DebugLoc DL = MI.getDebugLoc();
11104 MachineOperand DstAddr = earlyUseOperand(MI.getOperand(0));
11105 MachineOperand SrcAddr = earlyUseOperand(MI.getOperand(1));
11106 uint64_t Len = MI.getOperand(2).getImm();
11107 assert(Len > 0 && Len <= 256 && "Memmove of of unsupported constant length.");
11108
11109 // Use MVC or MVCRL after comparing the addresses.
11110 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11111 MachineBasicBlock *MvcMBB = SystemZ::emitBlockAfter(MBB);
11112 MachineBasicBlock *MvcrlMBB = SystemZ::emitBlockAfter(MvcMBB);
11113 MBB->addSuccessor(MvcMBB);
11114 MBB->addSuccessor(MvcrlMBB);
11115 MvcMBB->addSuccessor(DoneMBB);
11116 MvcrlMBB->addSuccessor(DoneMBB);
11117
11118 BuildMI(MBB, DL, TII->get(SystemZ::CLGR)).add(SrcAddr).add(DstAddr);
11119 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11121 .addMBB(MvcrlMBB);
11122
11123 BuildMI(MvcMBB, DL, TII->get(SystemZ::MVC))
11124 .add(DstAddr).addImm(0)
11125 .addImm(Len)
11126 .add(SrcAddr).addImm(0)
11127 .setMemRefs(MI.memoperands());
11128 BuildMI(MvcMBB, DL, TII->get(SystemZ::J)).addMBB(DoneMBB);
11129
11130 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::LHI), SystemZ::R0L).addImm(Len - 1);
11131 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::MVCRL))
11132 .add(DstAddr).addImm(0)
11133 .add(SrcAddr).addImm(0)
11134 .setMemRefs(MI.memoperands());
11135
11136 MI.eraseFromParent();
11137 return DoneMBB;
11138}
11139
11140// Decompose string pseudo-instruction MI into a loop that continually performs
11141// Opcode until CC != 3.
11142MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
11143 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11144 MachineFunction &MF = *MBB->getParent();
11145 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11146 MachineRegisterInfo &MRI = MF.getRegInfo();
11147 DebugLoc DL = MI.getDebugLoc();
11148
11149 uint64_t End1Reg = MI.getOperand(0).getReg();
11150 uint64_t Start1Reg = MI.getOperand(1).getReg();
11151 uint64_t Start2Reg = MI.getOperand(2).getReg();
11152 uint64_t CharReg = MI.getOperand(3).getReg();
11153
11154 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
11155 uint64_t This1Reg = MRI.createVirtualRegister(RC);
11156 uint64_t This2Reg = MRI.createVirtualRegister(RC);
11157 uint64_t End2Reg = MRI.createVirtualRegister(RC);
11158
11159 MachineBasicBlock *StartMBB = MBB;
11160 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
11161 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
11162
11163 // StartMBB:
11164 // # fall through to LoopMBB
11165 MBB->addSuccessor(LoopMBB);
11166
11167 // LoopMBB:
11168 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
11169 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
11170 // R0L = %CharReg
11171 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
11172 // JO LoopMBB
11173 // # fall through to DoneMBB
11174 //
11175 // The load of R0L can be hoisted by post-RA LICM.
11176 MBB = LoopMBB;
11177
11178 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
11179 .addReg(Start1Reg).addMBB(StartMBB)
11180 .addReg(End1Reg).addMBB(LoopMBB);
11181 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
11182 .addReg(Start2Reg).addMBB(StartMBB)
11183 .addReg(End2Reg).addMBB(LoopMBB);
11184 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
11185 BuildMI(MBB, DL, TII->get(Opcode))
11186 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
11187 .addReg(This1Reg).addReg(This2Reg);
11188 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11190 MBB->addSuccessor(LoopMBB);
11191 MBB->addSuccessor(DoneMBB);
11192
11193 DoneMBB->addLiveIn(SystemZ::CC);
11194
11195 MI.eraseFromParent();
11196 return DoneMBB;
11197}
11198
11199// Update TBEGIN instruction with final opcode and register clobbers.
11200MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
11201 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
11202 bool NoFloat) const {
11203 MachineFunction &MF = *MBB->getParent();
11204 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11205 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11206
11207 // Update opcode.
11208 MI.setDesc(TII->get(Opcode));
11209
11210 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
11211 // Make sure to add the corresponding GRSM bits if they are missing.
11212 uint64_t Control = MI.getOperand(2).getImm();
11213 static const unsigned GPRControlBit[16] = {
11214 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
11215 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
11216 };
11217 Control |= GPRControlBit[15];
11218 if (TFI->hasFP(MF))
11219 Control |= GPRControlBit[11];
11220 MI.getOperand(2).setImm(Control);
11221
11222 // Add GPR clobbers.
11223 for (int I = 0; I < 16; I++) {
11224 if ((Control & GPRControlBit[I]) == 0) {
11225 unsigned Reg = SystemZMC::GR64Regs[I];
11226 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11227 }
11228 }
11229
11230 // Add FPR/VR clobbers.
11231 if (!NoFloat && (Control & 4) != 0) {
11232 if (Subtarget.hasVector()) {
11233 for (unsigned Reg : SystemZMC::VR128Regs) {
11234 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11235 }
11236 } else {
11237 for (unsigned Reg : SystemZMC::FP64Regs) {
11238 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11239 }
11240 }
11241 }
11242
11243 return MBB;
11244}
11245
11246MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
11247 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11248 MachineFunction &MF = *MBB->getParent();
11249 MachineRegisterInfo *MRI = &MF.getRegInfo();
11250 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11251 DebugLoc DL = MI.getDebugLoc();
11252
11253 Register SrcReg = MI.getOperand(0).getReg();
11254
11255 // Create new virtual register of the same class as source.
11256 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
11257 Register DstReg = MRI->createVirtualRegister(RC);
11258
11259 // Replace pseudo with a normal load-and-test that models the def as
11260 // well.
11261 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
11262 .addReg(SrcReg)
11263 .setMIFlags(MI.getFlags());
11264 MI.eraseFromParent();
11265
11266 return MBB;
11267}
11268
11269MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11271 MachineFunction &MF = *MBB->getParent();
11272 MachineRegisterInfo *MRI = &MF.getRegInfo();
11273 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11274 DebugLoc DL = MI.getDebugLoc();
11275 const unsigned ProbeSize = getStackProbeSize(MF);
11276 Register DstReg = MI.getOperand(0).getReg();
11277 Register SizeReg = MI.getOperand(2).getReg();
11278
11279 MachineBasicBlock *StartMBB = MBB;
11280 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11281 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11282 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11283 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11284 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11285
11286 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11288
11289 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11290 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11291
11292 // LoopTestMBB
11293 // BRC TailTestMBB
11294 // # fallthrough to LoopBodyMBB
11295 StartMBB->addSuccessor(LoopTestMBB);
11296 MBB = LoopTestMBB;
11297 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11298 .addReg(SizeReg)
11299 .addMBB(StartMBB)
11300 .addReg(IncReg)
11301 .addMBB(LoopBodyMBB);
11302 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11303 .addReg(PHIReg)
11304 .addImm(ProbeSize);
11305 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11307 .addMBB(TailTestMBB);
11308 MBB->addSuccessor(LoopBodyMBB);
11309 MBB->addSuccessor(TailTestMBB);
11310
11311 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11312 // J LoopTestMBB
11313 MBB = LoopBodyMBB;
11314 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11315 .addReg(PHIReg)
11316 .addImm(ProbeSize)
11317 .setOperandDead(3);
11318 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11319 .addReg(SystemZ::R15D)
11320 .addImm(ProbeSize)
11321 .setOperandDead(3);
11322 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11323 .addReg(SystemZ::R15D)
11324 .addReg(SystemZ::R15D)
11325 .addImm(ProbeSize - 8)
11326 .addReg(0)
11327 .setOperandDead(4)
11328 .setMemRefs(VolLdMMO);
11329 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11330 MBB->addSuccessor(LoopTestMBB);
11331
11332 // TailTestMBB
11333 // BRC DoneMBB
11334 // # fallthrough to TailMBB
11335 MBB = TailTestMBB;
11336 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11337 .addReg(PHIReg)
11338 .addImm(0);
11339 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11341 .addMBB(DoneMBB);
11342 MBB->addSuccessor(TailMBB);
11343 MBB->addSuccessor(DoneMBB);
11344
11345 // TailMBB
11346 // # fallthrough to DoneMBB
11347 MBB = TailMBB;
11348 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11349 .addReg(SystemZ::R15D)
11350 .addReg(PHIReg)
11351 .setOperandDead(3);
11352 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11353 .addReg(SystemZ::R15D)
11354 .addReg(SystemZ::R15D)
11355 .addImm(-8)
11356 .addReg(PHIReg)
11357 .setOperandDead(4)
11358 .setMemRefs(VolLdMMO);
11359 MBB->addSuccessor(DoneMBB);
11360
11361 // DoneMBB
11362 MBB = DoneMBB;
11363 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11364 .addReg(SystemZ::R15D);
11365
11366 MI.eraseFromParent();
11367 return DoneMBB;
11368}
11369
11370SDValue SystemZTargetLowering::
11371getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11373 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11374 SDLoc DL(SP);
11375 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11376 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11377}
11378
11379// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11380// a dead early-clobber def reg that will be used as a scratch register
11381// when the pseudo is expanded.
11382MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11383 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11384 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11385 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11386 DebugLoc DL = MI.getDebugLoc();
11387 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11388 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11389 .addFrameIndex(MI.getOperand(0).getIndex())
11390 .addImm(MI.getOperand(1).getImm());
11391 MI.eraseFromParent();
11392 return MBB;
11393}
11394
11397 switch (MI.getOpcode()) {
11398 case SystemZ::ADJCALLSTACKDOWN:
11399 case SystemZ::ADJCALLSTACKUP:
11400 return emitAdjCallStack(MI, MBB);
11401
11402 case SystemZ::Select32:
11403 case SystemZ::Select64:
11404 case SystemZ::Select128:
11405 case SystemZ::SelectF32:
11406 case SystemZ::SelectF64:
11407 case SystemZ::SelectF128:
11408 case SystemZ::SelectVR32:
11409 case SystemZ::SelectVR64:
11410 case SystemZ::SelectVR128:
11411 return emitSelect(MI, MBB);
11412
11413 case SystemZ::CondStore8Mux:
11414 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11415 case SystemZ::CondStore8MuxInv:
11416 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11417 case SystemZ::CondStore16Mux:
11418 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11419 case SystemZ::CondStore16MuxInv:
11420 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11421 case SystemZ::CondStore32Mux:
11422 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11423 case SystemZ::CondStore32MuxInv:
11424 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11425 case SystemZ::CondStore8:
11426 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11427 case SystemZ::CondStore8Inv:
11428 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11429 case SystemZ::CondStore16:
11430 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11431 case SystemZ::CondStore16Inv:
11432 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11433 case SystemZ::CondStore32:
11434 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11435 case SystemZ::CondStore32Inv:
11436 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11437 case SystemZ::CondStore64:
11438 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11439 case SystemZ::CondStore64Inv:
11440 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11441 case SystemZ::CondStoreF32:
11442 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11443 case SystemZ::CondStoreF32Inv:
11444 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11445 case SystemZ::CondStoreF64:
11446 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11447 case SystemZ::CondStoreF64Inv:
11448 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11449
11450 case SystemZ::SCmp128Hi:
11451 return emitICmp128Hi(MI, MBB, false);
11452 case SystemZ::UCmp128Hi:
11453 return emitICmp128Hi(MI, MBB, true);
11454
11455
11456 case SystemZ::ATOMIC_SWAPW:
11457 return emitAtomicLoadBinary(MI, MBB, 0);
11458
11459 case SystemZ::ATOMIC_LOADW_AR:
11460 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11461 case SystemZ::ATOMIC_LOADW_AFI:
11462 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11463
11464 case SystemZ::ATOMIC_LOADW_SR:
11465 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11466
11467 case SystemZ::ATOMIC_LOADW_NR:
11468 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11469 case SystemZ::ATOMIC_LOADW_NILH:
11470 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11471
11472 case SystemZ::ATOMIC_LOADW_OR:
11473 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11474 case SystemZ::ATOMIC_LOADW_OILH:
11475 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11476
11477 case SystemZ::ATOMIC_LOADW_XR:
11478 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11479 case SystemZ::ATOMIC_LOADW_XILF:
11480 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11481
11482 case SystemZ::ATOMIC_LOADW_NRi:
11483 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11484 case SystemZ::ATOMIC_LOADW_NILHi:
11485 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11486
11487 case SystemZ::ATOMIC_LOADW_MIN:
11488 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11489 case SystemZ::ATOMIC_LOADW_MAX:
11490 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11491 case SystemZ::ATOMIC_LOADW_UMIN:
11492 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11493 case SystemZ::ATOMIC_LOADW_UMAX:
11494 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11495
11496 case SystemZ::ATOMIC_CMP_SWAPW:
11497 return emitAtomicCmpSwapW(MI, MBB);
11498 case SystemZ::MVCImm:
11499 case SystemZ::MVCReg:
11500 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11501 case SystemZ::NCImm:
11502 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11503 case SystemZ::OCImm:
11504 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11505 case SystemZ::XCImm:
11506 case SystemZ::XCReg:
11507 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11508 case SystemZ::CLCImm:
11509 case SystemZ::CLCReg:
11510 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11511 case SystemZ::MemsetImmImm:
11512 case SystemZ::MemsetImmReg:
11513 case SystemZ::MemsetRegImm:
11514 case SystemZ::MemsetRegReg:
11515 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11516 case SystemZ::MemmoveImm:
11517 return emitMemmoveImm(MI, MBB);
11518 case SystemZ::CLSTLoop:
11519 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11520 case SystemZ::MVSTLoop:
11521 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11522 case SystemZ::SRSTLoop:
11523 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11524 case SystemZ::TBEGIN:
11525 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11526 case SystemZ::TBEGIN_nofloat:
11527 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11528 case SystemZ::TBEGINC:
11529 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11530 case SystemZ::LTEBRCompare_Pseudo:
11531 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11532 case SystemZ::LTDBRCompare_Pseudo:
11533 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11534 case SystemZ::LTXBRCompare_Pseudo:
11535 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11536
11537 case SystemZ::PROBED_ALLOCA:
11538 return emitProbedAlloca(MI, MBB);
11539 case SystemZ::EH_SjLj_SetJmp:
11540 return emitEHSjLjSetJmp(MI, MBB);
11541 case SystemZ::EH_SjLj_LongJmp:
11542 return emitEHSjLjLongJmp(MI, MBB);
11543
11544 case TargetOpcode::STACKMAP:
11545 case TargetOpcode::PATCHPOINT:
11546 return emitPatchPoint(MI, MBB);
11547
11548 case SystemZ::MOV_STACKGUARD_DAG:
11549 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11550
11551 case SystemZ::CMP_STACKGUARD_DAG:
11552 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11553
11554 default:
11555 llvm_unreachable("Unexpected instr type to insert");
11556 }
11557}
11558
11559SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11560 SelectionDAG &DAG) const {
11561 SDLoc dl(Op);
11562 /*
11563 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11564 settings:
11565 00 Round to nearest
11566 01 Round to 0
11567 10 Round to +inf
11568 11 Round to -inf
11569
11570 FLT_ROUNDS, on the other hand, expects the following:
11571 -1 Undefined
11572 0 Round to 0
11573 1 Round to nearest
11574 2 Round to +inf
11575 3 Round to -inf
11576 */
11577
11578 // Save FPC to register.
11579 SDValue Chain = Op.getOperand(0);
11580 SDValue EFPC(
11581 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11582 Chain = EFPC.getValue(1);
11583
11584 // Transform as necessary
11585 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11586 DAG.getConstant(3, dl, MVT::i32));
11587 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11588 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11589 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11590 DAG.getConstant(1, dl, MVT::i32)));
11591
11592 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11593 DAG.getConstant(1, dl, MVT::i32));
11594 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11595
11596 return DAG.getMergeValues({RetVal, Chain}, dl);
11597}
11598
11599SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11600 SelectionDAG &DAG) const {
11601 EVT VT = Op.getValueType();
11602 Op = Op.getOperand(0);
11603 EVT OpVT = Op.getValueType();
11604
11605 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11606
11607 SDLoc DL(Op);
11608
11609 // load a 0 vector for the third operand of VSUM.
11610 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11611
11612 // execute VSUM.
11613 switch (OpVT.getScalarSizeInBits()) {
11614 case 8:
11615 case 16:
11616 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11617 [[fallthrough]];
11618 case 32:
11619 case 64:
11620 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11621 DAG.getBitcast(Op.getValueType(), Zero));
11622 break;
11623 case 128:
11624 break; // VSUM over v1i128 should not happen and would be a noop
11625 default:
11626 llvm_unreachable("Unexpected scalar size.");
11627 }
11628 // Cast to original vector type, retrieve last element.
11629 return DAG.getNode(
11630 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11631 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11632}
11633
11634static void printFunctionArgExts(const Function *F, raw_ostream &OS) {
11635 FunctionType *FT = F->getFunctionType();
11636 const AttributeList &Attrs = F->getAttributes();
11637 if (Attrs.hasRetAttrs())
11638 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11639 OS << *F->getReturnType() << " @" << F->getName() << "(";
11640 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11641 if (I)
11642 OS << ", ";
11643 OS << *FT->getParamType(I);
11644 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11645 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11646 if (ArgAttrs.hasAttribute(A))
11647 OS << " " << Attribute::getNameFromAttrKind(A);
11648 }
11649 if (F->isVarArg())
11650 OS << ", ...";
11651 OS << ")\n";
11652}
11653
11654bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11655 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11656 if (Itr == IsInternalCache.end())
11657 Itr = IsInternalCache
11658 .insert(std::pair<const Function *, bool>(
11659 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11660 .first;
11661 return Itr->second;
11662}
11663
11664bool SystemZTargetLowering::enableNarrowIntArgsVerification() const {
11665 if (!Subtarget.isTargetELF())
11666 return false;
11667
11668 if (auto V = toOptional(Subtarget.getCLOpts().argext_abi_check))
11669 return *V;
11670
11671#ifdef NDEBUG
11672 return false;
11673#endif
11674
11676}
11677
11678void SystemZTargetLowering::verifyNarrowIntegerArgs_Call(
11679 CallLoweringInfo &CLI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11680 const Function *F, SDValue Callee) const {
11681 if (!enableNarrowIntArgsVerification())
11682 return;
11683 bool IsInternal = false;
11684 const Function *CalleeFn = nullptr;
11685 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11686 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11687 IsInternal = isInternal(CalleeFn);
11688 bool C_ABI = CLI.CallConv == CallingConv::C && !IsInternal;
11689 if (!verifyNarrowIntegerArgs(C_ABI, Outs, CalleeFn, /*IsRet=*/false)) {
11690 errs() << "Callee: ";
11691 if (CalleeFn != nullptr)
11692 printFunctionArgExts(CalleeFn, errs());
11693 else
11694 errs() << "-\n";
11695 errs() << "Caller: ";
11697 if (CLI.CB)
11698 errs() << " " << *CLI.CB;
11699 llvm_unreachable("");
11700 }
11701 LLVM_DEBUG(dbgs() << "Outgoing call arguments verified as ABI compliant: ";
11702 if (CalleeFn != nullptr) printFunctionArgExts(CalleeFn, dbgs());
11703 else dbgs() << "-\n";);
11704}
11705
11706void SystemZTargetLowering::verifyNarrowIntegerArgs_Ret(
11708 const Function *F) const {
11709 if (!enableNarrowIntArgsVerification())
11710 return;
11711 bool C_ABI = CallConv == CallingConv::C && !isInternal(F);
11712 if (!verifyNarrowIntegerArgs(C_ABI, Outs, F, /*IsRet=*/true)) {
11713 errs() << "Returning from function: ";
11715 llvm_unreachable("");
11716 }
11717 LLVM_DEBUG(dbgs() << "Return argument verified as ABI compliant : ";
11719}
11720
11721// Verify that narrow integer arguments are extended according to the
11722// function header (calllee for a call, containing function for a ret).
11723// If C_ABI is true, an extension attribute must be present.
11724bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11725 bool C_ABI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11726 const Function *FunHeader, bool IsRet) const {
11727 if (IsRet && Outs.size() != 1)
11728 return true;
11729
11730 for (unsigned i = 0; i < Outs.size(); ++i) {
11731 EVT OrigArgVT = Outs[i].ArgVT;
11732 if (!OrigArgVT.isScalarInteger() || OrigArgVT.getSizeInBits() >= 64)
11733 continue;
11734 assert(Outs[i].VT == MVT::i32 && "Unexpected integer argument VT.");
11735 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11736 unsigned OrigIdx = Outs[i].OrigArgIndex;
11737
11738 // Per the C ABI there must be an extension.
11739 if (C_ABI && !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt()) {
11740 errs() << "ERROR: (C ABI violation) missing extension attribute on "
11741 << (IsRet ? "return value" : Twine("arg ") + Twine(OrigIdx))
11742 << ".\n";
11743 return false;
11744 }
11745
11746 // Flags should reflect the attributes of the function header.
11747 if (FunHeader) {
11748 const AttributeList &FunAttrs = FunHeader->getAttributes();
11749 const AttributeSet Attrs =
11750 IsRet ? FunAttrs.getRetAttrs() : FunAttrs.getParamAttrs(OrigIdx);
11751 if (Attrs.hasAttribute(Attribute::SExt) && !Flags.isSExt()) {
11752 errs() << "ERROR: Missing SExt on arg " << OrigIdx << ".\n";
11753 return false;
11754 }
11755 if (Attrs.hasAttribute(Attribute::ZExt) && !Flags.isZExt()) {
11756 errs() << "ERROR: Missing ZExt on arg " << OrigIdx << ".\n";
11757 return false;
11758 }
11759 }
11760 }
11761
11762 return true;
11763}
11764
11766 Module &M, const LibcallLoweringInfo &Libcalls) const {
11767 StringRef GuardMode = M.getStackProtectorGuard();
11768
11769 // In the TLS case, no symbol needs to be inserted.
11770 if (GuardMode == "tls" || GuardMode.empty())
11771 return;
11772
11773 // Otherwise (in the global case), insert the appropriate global variable.
11775}
unsigned NumParts
return SDValue()
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
AMDGPU Register Bank Select
static bool isZeroVector(SDValue N)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
#define Check(C,...)
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static bool isSelectPseudo(MachineInstr &MI)
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
static constexpr MCPhysReg SPReg
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SDValue getI128Select(SelectionDAG &DAG, const SDLoc &DL, Comparison C, SDValue TrueOp, SDValue FalseOp)
static SmallVector< SDValue, 4 > simplifyAssumingCCVal(SDValue &Val, SDValue &CC, SelectionDAG &DAG)
static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForLTGFR(Comparison &C)
static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, SDValue Op1)
#define CONV(X)
static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG)
static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, unsigned Opcode, SDValue Op0, SDValue Op1, SDValue &Even, SDValue &Odd)
static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue lowerAddrSpaceCast(SDValue Op, SelectionDAG &DAG)
static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Value)
static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In)
static bool isSimpleShift(SDValue N, unsigned &ShiftVal)
static SDValue mergeHighParts(SelectionDAG &DAG, const SDLoc &DL, unsigned MergedBits, EVT VT, SDValue Op0, SDValue Op1)
static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1)
static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num)
static bool isVectorElementSwap(ArrayRef< int > M, EVT VT)
static void getCSAddressAndShifts(SDValue Addr, SelectionDAG &DAG, SDLoc DL, SDValue &AlignedAddr, SDValue &BitShift, SDValue &NegBitShift)
static bool isShlDoublePermute(const SmallVectorImpl< int > &Bytes, unsigned &StartIndex, unsigned &OpNo0, unsigned &OpNo1)
static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, const Permute &P, SDValue Op0, SDValue Op1)
static SDNode * emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg)
static void adjustForStackGuardCompare(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, SDValue Op0, SDValue Op1, SDValue &Hi, SDValue &Lo)
static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static void createPHIsForSelects(SmallVector< MachineInstr *, 8 > &Selects, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *SinkMBB)
static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, SDValue *Ops, const SmallVectorImpl< int > &Bytes)
static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode, bool &Invert)
static unsigned CCMaskForCondCode(ISD::CondCode CC)
static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForFNeg(Comparison &C)
static bool isScalarToVector(SDValue Op)
static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, unsigned CCValid, unsigned CCMask)
static bool matchPermute(const SmallVectorImpl< int > &Bytes, const Permute &P, unsigned &OpNo0, unsigned &OpNo1)
static bool isAddCarryChain(SDValue Carry)
static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static MachineOperand earlyUseOperand(MachineOperand Op)
static bool canUseSiblingCall(const CCState &ArgCCInfo, SmallVectorImpl< CCValAssign > &ArgLocs, SmallVectorImpl< ISD::OutputArg > &Outs)
static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA, SDLoc &DL, SDValue &Chain)
static SDValue convertToF16(SDValue Op, SelectionDAG &DAG)
static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask, SelectionDAG &DAG)
static bool shouldSwapCmpOperands(const Comparison &C)
static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType)
static SDValue getADAEntry(SelectionDAG &DAG, SDValue Val, SDLoc DL, unsigned Offset, bool LoadAdr=false)
static SDNode * emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool getVPermMask(SDValue ShuffleOp, SmallVectorImpl< int > &Bytes)
static const Permute PermuteForms[]
static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static std::pair< SDValue, int > findCCUse(const SDValue &Val, unsigned Depth=0)
static bool isSubBorrowChain(SDValue Carry)
static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool analyzeArgSplit(const SmallVectorImpl< ArgTy > &Args, SmallVector< CCValAssign, 16 > &ArgLocs, unsigned I, MVT &PartVT, unsigned &NumParts)
static bool isInBoundsConstantVectorIndex(EVT VecVT, SDValue Idx)
static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts, unsigned OpNo)
static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op, bool IsNegative)
static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static SDValue expandBitCastI128ToF128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static SDValue tryBuildVectorShuffle(SelectionDAG &DAG, BuildVectorSDNode *BVN)
static SDValue convertFromF16(SDValue Op, SDLoc DL, SelectionDAG &DAG)
static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode)
static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In)
static SDValue MergeInputChains(SDNode *N1, SDNode *N2)
static SDValue expandBitCastF128ToI128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static void diagnoseXPLINK64VectorWithoutVF(const SystemZSubtarget &Subtarget, SelectionDAG &DAG, const SmallVectorImpl< ArgT > &Args)
static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask, uint64_t Mask, uint64_t CmpVal, unsigned ICmpType)
static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL, SDValue Op, SDValue Chain)
static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1, ISD::CondCode Cond, const SDLoc &DL, SDValue Chain=SDValue(), bool IsSignaling=false)
static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB)
static Register forceReg(MachineInstr &MI, MachineOperand &Base, const SystemZInstrInfo *TII)
static bool is32Bit(EVT VT)
static std::pair< unsigned, const TargetRegisterClass * > parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC, const unsigned *Map, unsigned Size)
static unsigned detectEvenOddMultiplyOperand(const SelectionDAG &DAG, const SystemZSubtarget &Subtarget, SDValue &Op)
static bool matchDoublePermute(const SmallVectorImpl< int > &Bytes, const Permute &P, SmallVectorImpl< int > &Transform)
static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode, SDValue Call, unsigned CCValid, uint64_t CC, ISD::CondCode Cond)
static Register getOrCreateADAVirtualRegister(MachineFunction &MF)
static SDValue buildFPVecFromScalars4(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SmallVectorImpl< SDValue > &Elems, unsigned Pos)
static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg)
static AddressingMode getLoadStoreAddrMode(bool HasVector, Type *Ty)
static void printFunctionArgExts(const Function *F, raw_ostream &OS)
static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op0, SDValue Op1)
static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static bool getShuffleInput(const SmallVectorImpl< int > &Bytes, unsigned Start, unsigned BytesPerElement, int &Base)
static AddressingMode supportedAddressingMode(Instruction *I, bool HasVector)
static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition APInt.h:318
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
BinOp getOperation() const
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:529
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM Basic Block Representation.
Definition BasicBlock.h:61
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI bool isConstant() const
CCState - This class holds information needed while lowering arguments and return values.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
uint64_t getZExtValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Diagnostic information for unsupported feature in backend.
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
bool hasAddressTaken(const User **=nullptr, bool IgnoreCallbackUses=false, bool IgnoreAssumeLikeCalls=true, bool IngoreLLVMUsed=false, bool IgnoreARCAttachedCall=false, bool IgnoreCastedDirectCall=false) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition Function.cpp:941
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:733
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
bool hasInternalLinkage() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Tracks which library functions to use for a particular subtarget or function.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
Machine Value Type.
static auto integer_fixedlen_vector_valuetypes()
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool isVector() const
Return true if this is a vector value type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
ElementCount getVectorElementCount() const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setFrameAddressIsTaken(bool T)
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
reverse_iterator rbegin()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineFunctionProperties & getProperties() const
Get the function properties.
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
ArrayRef< int > getMask() const
const_iterator begin() const
Definition SmallSet.h:216
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:712
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
A SystemZ-specific class detailing special use registers particular for calling conventions.
static SystemZConstantPoolValue * Create(const GlobalValue *GV, SystemZCP::SystemZCPModifier Modifier)
SystemZCallingConventionRegisters * getSpecialRegisters() const
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
bool hasInlineStackProbe(const MachineFunction &MF) const override
Returns true if stack probing through inline assembly is requested.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &, EVT) const override
Return the ValueType of the result of SETCC operations.
bool allowTruncateForTailCall(Type *, Type *) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag, const SDLoc &DL, const AsmOperandInfo &Constraint, SelectionDAG &DAG) const override
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
bool canMergeStoresTo(unsigned AS, EVT MemVT, const MachineFunction &MF) const override
Returns if it's reasonable to merge stores to MemVT size.
std::pair< SDValue, SDValue > makeExternalCall(SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT, ArrayRef< SDValue > Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL, bool DoesNotReturn, bool IsReturnValueUsed) const
void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const override
Insert SSP declaration if global stack protector is used.
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const override
Target-specific splitting of values into parts that fit a register storing a legal type.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, unsigned Depth) const override
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
SystemZTargetLowering(const TargetMachine &TM, const SystemZSubtarget &STI)
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
FPImmAction getFPImmAction(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns how the legalizer should materialize the specified FP immediate.
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
bool isTypeDesirableForOp(SDNode *N, EVT VT) const override
Overload that takes the specific node being optimized.
TargetLowering::ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AS, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
Determine if the target supports unaligned memory accesses.
const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const override
Returns a 0 terminated array of registers that can be safely used as scratch registers.
TargetLowering::ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const override
Target-specific combining of register parts into its original value.
bool isTruncateFree(Type *, Type *) const override
Return true if it's free to truncate a value of type FromTy to type ToTy.
SDValue useLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, MVT VT, SDValue Arg, SDLoc DL, SDValue Chain, bool IsStrict) const
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine the number of bits in the operation that are sign bits.
void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
CondMergingParams getJumpConditionMergingParams(Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, const Function *F) const override
TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const override
Determines the optimal series of memory ops to replace the memset / memcpy.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
bool aggressivelyPreferBuildVectorSources(EVT VecVT) const override
AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be cast by the IR-level AtomicExpand pass into.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
unsigned getStackProbeSize(const MachineFunction &MF) const
XPLINK64 calling convention specific use registers Particular to z/OS when in 64 bit mode.
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const
Inserts necessary declarations for SSP (stack protection) purpose.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Let target indicate that an extending atomic load of the specified type is legal.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of a boolean value from i1 to a wider type.
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
unsigned VerifyArgABICompliance
When set to true, call/return argument extensions of narrow integers are verified in the target backe...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:476
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:942
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ STRICT_PSEUDO_FMAX
Definition ISDOpcodes.h:465
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:441
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ STRICT_PSEUDO_FMIN
Definition ISDOpcodes.h:464
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:475
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:931
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:469
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:461
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
const unsigned GR64Regs[16]
const unsigned VR128Regs[32]
const unsigned VR16Regs[32]
const unsigned GR128Regs[16]
const unsigned FP32Regs[16]
const unsigned FP16Regs[16]
const unsigned GR32Regs[16]
const unsigned FP64Regs[16]
const int64_t ELFCallFrameSize
const unsigned VR64Regs[32]
const unsigned FP128Regs[16]
const unsigned VR32Regs[32]
unsigned odd128(bool Is32bit)
const unsigned CCMASK_CMP_GE
Definition SystemZ.h:46
static bool isImmHH(uint64_t Val)
Definition SystemZ.h:182
const unsigned CCMASK_TEND
Definition SystemZ.h:103
const unsigned CCMASK_CS_EQ
Definition SystemZ.h:73
const unsigned CCMASK_TBEGIN
Definition SystemZ.h:98
const unsigned CCMASK_0
Definition SystemZ.h:33
const MCPhysReg ELFArgFPRs[ELFNumArgFPRs]
MachineBasicBlock * splitBlockBefore(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_TM_SOME_1
Definition SystemZ.h:88
const unsigned CCMASK_LOGICAL_CARRY
Definition SystemZ.h:66
const unsigned TDCMASK_NORMAL_MINUS
Definition SystemZ.h:128
const unsigned CCMASK_TDC
Definition SystemZ.h:115
const unsigned CCMASK_FCMP
Definition SystemZ.h:54
const unsigned CCMASK_TM_SOME_0
Definition SystemZ.h:87
static bool isImmHL(uint64_t Val)
Definition SystemZ.h:177
const unsigned TDCMASK_SUBNORMAL_MINUS
Definition SystemZ.h:130
const unsigned PFD_READ
Definition SystemZ.h:121
const unsigned CCMASK_1
Definition SystemZ.h:34
const unsigned TDCMASK_NORMAL_PLUS
Definition SystemZ.h:127
const unsigned PFD_WRITE
Definition SystemZ.h:122
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:43
const unsigned TDCMASK_QNAN_MINUS
Definition SystemZ.h:134
const unsigned CCMASK_CS
Definition SystemZ.h:75
const unsigned CCMASK_ANY
Definition SystemZ.h:37
const unsigned CCMASK_ARITH
Definition SystemZ.h:61
const unsigned CCMASK_TM_MIXED_MSB_0
Definition SystemZ.h:84
const unsigned TDCMASK_SUBNORMAL_PLUS
Definition SystemZ.h:129
static bool isImmLL(uint64_t Val)
Definition SystemZ.h:167
const unsigned VectorBits
Definition SystemZ.h:160
static bool isImmLH(uint64_t Val)
Definition SystemZ.h:172
MachineBasicBlock * emitBlockAfter(MachineBasicBlock *MBB)
const unsigned TDCMASK_INFINITY_PLUS
Definition SystemZ.h:131
unsigned reverseCCMask(unsigned CCMask)
const unsigned CCMASK_TM_ALL_0
Definition SystemZ.h:83
const unsigned IPM_CC
Definition SystemZ.h:118
const unsigned CCMASK_CMP_LE
Definition SystemZ.h:45
const unsigned CCMASK_CMP_O
Definition SystemZ.h:50
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:41
const unsigned VectorBytes
Definition SystemZ.h:164
const unsigned TDCMASK_INFINITY_MINUS
Definition SystemZ.h:132
const unsigned CCMASK_ICMP
Definition SystemZ.h:53
const unsigned CCMASK_VCMP_ALL
Definition SystemZ.h:107
const unsigned CCMASK_VCMP_NONE
Definition SystemZ.h:109
MachineBasicBlock * splitBlockAfter(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_VCMP
Definition SystemZ.h:110
const unsigned CCMASK_TM_MIXED_MSB_1
Definition SystemZ.h:85
const unsigned CCMASK_TM_MSB_0
Definition SystemZ.h:89
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:60
const unsigned CCMASK_CS_NE
Definition SystemZ.h:74
const unsigned TDCMASK_SNAN_PLUS
Definition SystemZ.h:135
const unsigned CCMASK_TM
Definition SystemZ.h:91
const unsigned CCMASK_3
Definition SystemZ.h:36
const unsigned CCMASK_NONE
Definition SystemZ.h:32
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:42
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:44
const unsigned TDCMASK_ZERO_PLUS
Definition SystemZ.h:125
const unsigned TDCMASK_QNAN_PLUS
Definition SystemZ.h:133
const unsigned TDCMASK_ZERO_MINUS
Definition SystemZ.h:126
unsigned even128(bool Is32bit)
const unsigned CCMASK_TM_ALL_1
Definition SystemZ.h:86
const unsigned CCMASK_LOGICAL_BORROW
Definition SystemZ.h:68
const unsigned ELFNumArgFPRs
const unsigned CCMASK_CMP_UO
Definition SystemZ.h:49
const unsigned CCMASK_LOGICAL
Definition SystemZ.h:70
const unsigned CCMASK_TM_MSB_1
Definition SystemZ.h:90
const unsigned TDCMASK_SNAN_MINUS
Definition SystemZ.h:136
support::ulittle32_t Word
Definition IRSymtab.h:53
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Define
Register definition.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
@ Load
The value being inserted comes from a load (InsertElement only).
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
@ Force
Turn off window algorithm.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
constexpr std::optional< bool > toOptional(BoolOrDefault X)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
#define EQ(a, b)
Definition regexec.c:65
AddressingMode(bool LongDispl, bool IdxReg)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:286
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:196
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
SmallVector< unsigned, 2 > OpVals
bool isVectorConstantLegal(const SystemZSubtarget &Subtarget)
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.