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"
22#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsS390.h"
26#include "llvm/IR/Module.h"
32#include <cctype>
33#include <optional>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "systemz-lower"
38
39// Temporarily let this be disabled by default until all known problems
40// related to argument extensions are fixed.
42 "argext-abi-check", cl::init(false),
43 cl::desc("Verify that narrow int args are properly extended per the "
44 "SystemZ ABI."));
45
46namespace {
47// Represents information about a comparison.
48struct Comparison {
49 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
50 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
51 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
52
53 // The operands to the comparison.
54 SDValue Op0, Op1;
55
56 // Chain if this is a strict floating-point comparison.
57 SDValue Chain;
58
59 // The opcode that should be used to compare Op0 and Op1.
60 unsigned Opcode;
61
62 // A SystemZICMP value. Only used for integer comparisons.
63 unsigned ICmpType;
64
65 // The mask of CC values that Opcode can produce.
66 unsigned CCValid;
67
68 // The mask of CC values for which the original condition is true.
69 unsigned CCMask;
70};
71} // end anonymous namespace
72
73// Classify VT as either 32 or 64 bit.
74static bool is32Bit(EVT VT) {
75 switch (VT.getSimpleVT().SimpleTy) {
76 case MVT::i32:
77 return true;
78 case MVT::i64:
79 return false;
80 default:
81 llvm_unreachable("Unsupported type");
82 }
83}
84
85// Return a version of MachineOperand that can be safely used before the
86// final use.
88 if (Op.isReg())
89 Op.setIsKill(false);
90 return Op;
91}
92
94 const SystemZSubtarget &STI)
95 : TargetLowering(TM, STI), Subtarget(STI) {
96 MVT PtrVT = MVT::i64;
97
98 auto *Regs = STI.getSpecialRegisters();
99
100 // Set up the register classes.
101 if (Subtarget.hasHighWord())
102 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
103 else
104 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
105 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
106 if (!useSoftFloat()) {
107 if (Subtarget.hasVector()) {
108 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
109 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
110 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
111 } else {
112 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
113 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
114 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
115 }
116 if (Subtarget.hasVectorEnhancements1())
117 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
118 else
119 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
120
121 if (Subtarget.hasVector()) {
122 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
123 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
124 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
125 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
126 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
127 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
128 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
129 }
130
131 if (Subtarget.hasVector())
132 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
133 }
134
135 // Without vector support, model GR128 register pairs as v2i64.
136 if (!Subtarget.hasVector())
137 addRegisterClass(MVT::v2i64, &SystemZ::GR128BitRegClass);
138
139 // Compute derived properties from the register classes
140 computeRegisterProperties(Subtarget.getRegisterInfo());
141
142 // Set up special registers.
143 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
144
145 // TODO: It may be better to default to latency-oriented scheduling, however
146 // LLVM's current latency-oriented scheduler can't handle physreg definitions
147 // such as SystemZ has with CC, so set this to the register-pressure
148 // scheduler, because it can.
150
153
155
156 // Instructions are strings of 2-byte aligned 2-byte values.
158 // For performance reasons we prefer 16-byte alignment.
160
161 // Handle operations that are handled in a similar way for all types.
162 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
163 I <= MVT::LAST_FP_VALUETYPE;
164 ++I) {
166 if (isTypeLegal(VT)) {
167 // Lower SET_CC into an IPM-based sequence.
171
172 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
174
175 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
178 }
179 }
180
181 // Expand jump table branches as address arithmetic followed by an
182 // indirect jump.
184
185 // Expand BRCOND into a BR_CC (see above).
187
188 // Handle integer types except i128.
189 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
190 I <= MVT::LAST_INTEGER_VALUETYPE;
191 ++I) {
193 if (isTypeLegal(VT) && VT != MVT::i128) {
195
196 // Expand individual DIV and REMs into DIVREMs.
203
204 // Support addition/subtraction with overflow.
207
208 // Support addition/subtraction with carry.
211
212 // Support carry in as value rather than glue.
215
216 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
217 // available, or if the operand is constant.
219
220 // Use POPCNT on z196 and above.
221 if (Subtarget.hasPopulationCount())
223 else
225
226 // No special instructions for these.
229
230 // Use *MUL_LOHI where possible instead of MULH*.
235
236 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
237 // unsigned on z10 (only z196 and above have native support for
238 // unsigned conversions).
245 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
246 auto OpAction =
247 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
248 setOperationAction(Op, VT, OpAction);
249 }
250 }
251 }
252
253 // Handle i128 if legal.
254 if (isTypeLegal(MVT::i128)) {
255 // No special instructions for these.
262
263 // We may be able to use VSLDB/VSLD/VSRD for these.
266
267 // No special instructions for these before z17.
268 if (!Subtarget.hasVectorEnhancements3()) {
278 } else {
279 // Even if we do have a legal 128-bit multiply, we do not
280 // want 64-bit multiply-high operations to use it.
283 }
284
285 // Support addition/subtraction with carry.
290
291 // Use VPOPCT and add up partial results.
293
294 // Additional instructions available with z17.
295 if (Subtarget.hasVectorEnhancements3()) {
296 setOperationAction(ISD::ABS, MVT::i128, Legal);
297
299 MVT::i128, Legal);
300 }
301 }
302
303 // These need custom handling in order to handle the f16 conversions.
312
313 // Lower 8- and 16-bit atomic operations into full i32 operations during
314 // type legalization.
320 {MVT::i8, MVT::i16}, Custom);
321
322 // Whether or not i128 is not a legal type, we need to custom lower
323 // the atomic operations in order to exploit SystemZ instructions.
328
329 // Mark sign/zero extending atomic loads as legal, which will make
330 // DAGCombiner fold extensions into atomic loads if possible.
332 {MVT::i8, MVT::i16, MVT::i32}, Legal);
334 {MVT::i8, MVT::i16}, Legal);
336 MVT::i8, Legal);
337
338 // We can use the CC result of compare-and-swap to implement
339 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
343
345
346 // Traps are legal, as we will convert them to "j .+2".
347 setOperationAction(ISD::TRAP, MVT::Other, Legal);
348
349 // We have native support for a 64-bit CTLZ, via FLOGR.
353
354 // On z17 we have native support for a 64-bit CTTZ.
355 if (Subtarget.hasMiscellaneousExtensions4()) {
359 }
360
361 // On z15 we have native support for a 64-bit CTPOP.
362 if (Subtarget.hasMiscellaneousExtensions3()) {
365 }
366
367 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
369
370 // Expand 128 bit shifts without using a libcall.
374
375 // Also expand 256 bit shifts if i128 is a legal type.
376 if (isTypeLegal(MVT::i128)) {
380 }
381
382 // Handle bitcast from fp128 to i128.
383 if (!isTypeLegal(MVT::i128))
385
386 // We have native instructions for i8, i16 and i32 extensions, but not i1.
388 for (MVT VT : MVT::integer_valuetypes()) {
392 }
393
394 // Handle the various types of symbolic address.
400
401 // We need to handle dynamic allocations specially because of the
402 // 160-byte area at the bottom of the stack.
405
408
409 // Handle prefetches with PFD or PFDRL.
411
412 // Handle readcyclecounter with STCKF.
414
416 // Assume by default that all vector operations need to be expanded.
417 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
418 if (getOperationAction(Opcode, VT) == Legal)
419 setOperationAction(Opcode, VT, Expand);
420
421 // Likewise all truncating stores and extending loads.
422 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
423 setTruncStoreAction(VT, InnerVT, Expand);
426 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
427 }
428
429 if (Subtarget.hasVector() && isTypeLegal(VT)) {
430 // These operations are legal for anything that can be stored in a
431 // vector register, even if there is no native support for the format
432 // as such. In particular, we can do these for v4f32 even though there
433 // are no specific instructions for that format.
439
440 // Likewise, except that we need to replace the nodes with something
441 // more specific.
444 }
445 }
446
447 if (!Subtarget.hasVector()) {
448 // A v2i64 GR128 pair can only be built from or split into its halves.
449 // Loads and stores are expanded to avoid tying up a register pair.
452 MVT::v2i64, Legal);
454 MVT::v2i64, Custom);
455 }
456
457 // Handle integer vector types.
459 if (Subtarget.hasVector() && isTypeLegal(VT)) {
460 // These operations have direct equivalents.
465 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
469 }
470 if (Subtarget.hasVectorEnhancements3() &&
471 VT != MVT::v16i8 && VT != MVT::v8i16) {
476 }
481 if (Subtarget.hasVectorEnhancements1())
483 else
487
488 // Convert a GPR scalar to a vector by inserting it into element 0.
490
491 // Use a series of unpacks for extensions.
494
495 // Detect shifts/rotates by a scalar amount and convert them into
496 // V*_BY_SCALAR.
501
502 // Add ISD::VECREDUCE_ADD as custom in order to implement
503 // it with VZERO+VSUM
505
506 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
507 // and inverting the result as necessary.
509
511 Legal);
512 }
513 }
514
515 if (Subtarget.hasVector()) {
516 // There should be no need to check for float types other than v2f64
517 // since <2 x f32> isn't a legal type.
526
535 }
536
537 if (Subtarget.hasVectorEnhancements2()) {
546
555 }
556
557 // Handle floating-point types.
558 if (!useSoftFloat()) {
559 // Promote all f16 operations to float, with some exceptions below.
560 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
561 setOperationAction(Opc, MVT::f16, Promote);
563 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
564 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
565 setTruncStoreAction(VT, MVT::f16, Expand);
566 }
568 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
572
573 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
574 setOperationAction(Op, MVT::f16, Legal);
575 }
576
577 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
578 I <= MVT::LAST_FP_VALUETYPE;
579 ++I) {
581 if (isTypeLegal(VT) && VT != MVT::f16) {
582 // We can use FI for FRINT.
584
585 // We can use the extended form of FI for other rounding operations.
586 if (Subtarget.hasFPExtension()) {
593 }
594
595 // No special instructions for these.
601
602 // Special treatment.
604
605 // Handle constrained floating-point operations.
614 if (Subtarget.hasFPExtension()) {
621 }
622
623 // Extension from f16 needs libcall.
626 }
627 }
628
629 // Handle floating-point vector types.
630 if (Subtarget.hasVector()) {
631 // Scalar-to-vector conversion is just a subreg.
635
636 // Some insertions and extractions can be done directly but others
637 // need to go via integers.
644
645 // These operations have direct equivalents.
646 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
647 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
648 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
649 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
650 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
651 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
652 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
653 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
654 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
657 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
661
662 // Handle constrained floating-point operations.
676
681 if (Subtarget.hasVectorEnhancements1()) {
684 }
685 }
686
687 // The vector enhancements facility 1 has instructions for these.
688 if (Subtarget.hasVectorEnhancements1()) {
689 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
690 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
691 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
692 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
693 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
694 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
695 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
696 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
697 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
700 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
704
705 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
714 }
715
716 // Handle constrained floating-point operations.
730 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
731 MVT::v4f32, MVT::v2f64 }) {
738 }
739 }
740
741 // We only have fused f128 multiply-addition on vector registers.
742 if (!Subtarget.hasVectorEnhancements1()) {
745 }
746
747 // We don't have a copysign instruction on vector registers.
748 if (Subtarget.hasVectorEnhancements1())
750
751 // Needed so that we don't try to implement f128 constant loads using
752 // a load-and-extend of a f80 constant (in cases where the constant
753 // would fit in an f80).
754 for (MVT VT : MVT::fp_valuetypes())
755 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
756
757 // We don't have extending load instruction on vector registers.
758 if (Subtarget.hasVectorEnhancements1()) {
759 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
760 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
761 }
762
763 // Floating-point truncation and stores need to be done separately.
764 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
765 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
766 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
767
768 // We have 64-bit FPR<->GPR moves, but need special handling for
769 // 32-bit forms.
770 if (!Subtarget.hasVector()) {
773 }
774
775 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
776 // structure, but VAEND is a no-op.
780
781 if (Subtarget.isTargetzOS()) {
782 // Handle address space casts between mixed sized pointers.
785 }
786
788
789 // Codes for which we want to perform some z-specific combinations.
793 ISD::LOAD,
806 ISD::SRL,
807 ISD::SRA,
808 ISD::MUL,
809 ISD::SDIV,
810 ISD::UDIV,
811 ISD::SREM,
812 ISD::UREM,
815
816 // Handle intrinsics.
819
820 // We're not using SJLJ for exception handling, but they're implemented
821 // solely to support use of __builtin_setjmp / __builtin_longjmp.
824
825 // We want to use MVC in preference to even a single load/store pair.
826 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
828
829 // Same with memmove.
830 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
832
833 // The main memset sequence is a byte store followed by an MVC.
834 // Two STC or MV..I stores win over that, but the kind of fused stores
835 // generated by target-independent code don't when the byte value is
836 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
837 // than "STC;MVC". Handle the choice in target-specific code instead.
838 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
840
841 // Default to having -disable-strictnode-mutation on
842 IsStrictFPEnabled = true;
843}
844
846 return Subtarget.hasSoftFloat();
847}
848
851 // Widen subvectors to the full width rather than promoting integer
852 // elements. This is better because:
853 //
854 // (a) it means that we can handle the ABI for passing and returning
855 // sub-128 vectors without having to handle them as legal types.
856 //
857 // (b) we don't have instructions to extend on load and truncate on store,
858 // so promoting the integers is less efficient.
859 //
860 // (c) there are no multiplication instructions for the widest integer
861 // type (v2i64).
862
863 // Expand (narrow) f16 vectors during type legalization to avoid
864 // operations for all elements as with expansion after widening. Without
865 // vector support, v2i64 is only legal as a GR128 pair, so do not widen or
866 // promote to it.
867 if (!Subtarget.hasVector() || VT.getScalarType() == MVT::f16)
870 if (VT.getScalarSizeInBits() % 8 == 0)
871 return TypeWidenVector;
873}
874
876 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
877 unsigned &NumIntermediates, MVT &RegisterVT) const {
878 // Pass fp16 vectors in VR(s).
879 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
880 IntermediateVT = RegisterVT = MVT::v8f16;
881 return NumIntermediates =
883 }
885 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
886 // Without vector support, v2i64 is a GR128 pair, which is never used to pass
887 // values. Pass the elements individually.
888 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector()) {
889 IntermediateVT = RegisterVT = MVT::i64;
890 NumIntermediates *= 2;
891 NumRegs *= 2;
892 }
893 return NumRegs;
894}
895
898 EVT VT) const {
899 // 128-bit single-element vector types are passed like other vectors,
900 // not like their element type.
901 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
902 VT.getVectorNumElements() == 1)
903 return MVT::v16i8;
904 // Pass fp16 vectors in VR(s).
905 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
906 return MVT::v8f16;
907 MVT RegisterVT =
909 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
910 return MVT::i64;
911 return RegisterVT;
912}
913
915 LLVMContext &Context, CallingConv::ID CC, EVT VT) const {
916 // Pass fp16 vectors in VR(s).
917 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
919 unsigned NumRegs =
921 MVT RegisterVT =
923 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
924 return NumRegs * 2;
925 return NumRegs;
926}
927
929 LLVMContext &, EVT VT) const {
930 if (!VT.isVector())
931 return MVT::i32;
933}
934
936 const MachineFunction &MF, EVT VT) const {
937 if (useSoftFloat())
938 return false;
939
940 VT = VT.getScalarType();
941
942 if (!VT.isSimple())
943 return false;
944
945 switch (VT.getSimpleVT().SimpleTy) {
946 case MVT::f32:
947 case MVT::f64:
948 return true;
949 case MVT::f128:
950 return Subtarget.hasVectorEnhancements1();
951 default:
952 break;
953 }
954
955 return false;
956}
957
958// Return true if the constant can be generated with a vector instruction,
959// such as VGM, VGMB or VREPI.
962 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
963 if (!Subtarget.hasVector() ||
964 (isFP128 && !Subtarget.hasVectorEnhancements1()))
965 return false;
966
967 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
968 // preferred way of creating all-zero and all-one vectors so give it
969 // priority over other methods below.
970 unsigned Mask = 0;
971 unsigned I = 0;
972 for (; I < SystemZ::VectorBytes; ++I) {
973 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
974 if (Byte == 0xff)
975 Mask |= 1ULL << I;
976 else if (Byte != 0)
977 break;
978 }
979 if (I == SystemZ::VectorBytes) {
980 Opcode = SystemZISD::BYTE_MASK;
981 OpVals.push_back(Mask);
983 return true;
984 }
985
986 if (SplatBitSize > 64)
987 return false;
988
989 auto TryValue = [&](uint64_t Value) -> bool {
990 // Try VECTOR REPLICATE IMMEDIATE
991 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
992 if (isInt<16>(SignedValue)) {
993 OpVals.push_back(((unsigned) SignedValue));
994 Opcode = SystemZISD::REPLICATE;
996 SystemZ::VectorBits / SplatBitSize);
997 return true;
998 }
999 // Try VECTOR GENERATE MASK
1000 unsigned Start, End;
1001 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
1002 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
1003 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
1004 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
1005 OpVals.push_back(Start - (64 - SplatBitSize));
1006 OpVals.push_back(End - (64 - SplatBitSize));
1007 Opcode = SystemZISD::ROTATE_MASK;
1009 SystemZ::VectorBits / SplatBitSize);
1010 return true;
1011 }
1012 return false;
1013 };
1014
1015 // First try assuming that any undefined bits above the highest set bit
1016 // and below the lowest set bit are 1s. This increases the likelihood of
1017 // being able to use a sign-extended element value in VECTOR REPLICATE
1018 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
1019 uint64_t SplatBitsZ = SplatBits.getZExtValue();
1020 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
1021 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
1022 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
1023 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
1024 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
1025 if (TryValue(SplatBitsZ | Upper | Lower))
1026 return true;
1027
1028 // Now try assuming that any undefined bits between the first and
1029 // last defined set bits are set. This increases the chances of
1030 // using a non-wraparound mask.
1031 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
1032 return TryValue(SplatBitsZ | Middle);
1033}
1034
1036 if (IntImm.isSingleWord()) {
1037 IntBits = APInt(128, IntImm.getZExtValue());
1038 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
1039 } else
1040 IntBits = IntImm;
1041 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
1042
1043 // Find the smallest splat.
1044 SplatBits = IntImm;
1045 unsigned Width = SplatBits.getBitWidth();
1046 while (Width > 8) {
1047 unsigned HalfSize = Width / 2;
1048 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
1049 APInt LowValue = SplatBits.trunc(HalfSize);
1050
1051 // If the two halves do not match, stop here.
1052 if (HighValue != LowValue || 8 > HalfSize)
1053 break;
1054
1055 SplatBits = HighValue;
1056 Width = HalfSize;
1057 }
1058 SplatUndef = 0;
1059 SplatBitSize = Width;
1060}
1061
1063 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1064 bool HasAnyUndefs;
1065
1066 // Get IntBits by finding the 128 bit splat.
1067 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1068 true);
1069
1070 // Get SplatBits by finding the 8 bit or greater splat.
1071 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1072 true);
1073}
1074
1077 bool ForCodeSize) const {
1078 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1079 if (Imm.isZero() || Imm.isNegZero())
1080 return FPImmAction::Legal;
1081
1085}
1086
1089 MachineBasicBlock *MBB) const {
1090 DebugLoc DL = MI.getDebugLoc();
1091 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1092 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1093
1094 MachineFunction *MF = MBB->getParent();
1096
1097 const BasicBlock *BB = MBB->getBasicBlock();
1098 MachineFunction::iterator I = ++MBB->getIterator();
1099
1100 Register DstReg = MI.getOperand(0).getReg();
1101 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1102 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1103 (void)TRI;
1104 Register MainDstReg = MRI.createVirtualRegister(RC);
1105 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1106
1107 MVT PVT = getPointerTy(MF->getDataLayout());
1108 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1109 // For v = setjmp(buf), we generate.
1110 // Algorithm:
1111 //
1112 // ---------
1113 // | thisMBB |
1114 // ---------
1115 // |
1116 // ------------------------
1117 // | |
1118 // ---------- ---------------
1119 // | mainMBB | | restoreMBB |
1120 // | v = 0 | | v = 1 |
1121 // ---------- ---------------
1122 // | |
1123 // -------------------------
1124 // |
1125 // -----------------------------
1126 // | sinkMBB |
1127 // | phi(v_mainMBB,v_restoreMBB) |
1128 // -----------------------------
1129 // thisMBB:
1130 // buf[FPOffset] = Frame Pointer if hasFP.
1131 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1132 // buf[BCOffset] = Backchain value if building with -mbackchain.
1133 // buf[SPOffset] = Stack Pointer.
1134 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1135 // SjLjSetup restoreMBB
1136 // mainMBB:
1137 // v_main = 0
1138 // sinkMBB:
1139 // v = phi(v_main, v_restore)
1140 // restoreMBB:
1141 // v_restore = 1
1142
1143 MachineBasicBlock *ThisMBB = MBB;
1144 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1145 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1146 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1147
1148 MF->insert(I, MainMBB);
1149 MF->insert(I, SinkMBB);
1150 MF->push_back(RestoreMBB);
1151 RestoreMBB->setMachineBlockAddressTaken();
1152
1154
1155 // Transfer the remainder of BB and its successor edges to sinkMBB.
1156 SinkMBB->splice(SinkMBB->begin(), MBB,
1157 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1159
1160 // thisMBB:
1161 const int64_t FPOffset = 0; // Slot 1.
1162 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1163 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1164 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1165
1166 // Buf address.
1167 Register BufReg = MI.getOperand(1).getReg();
1168
1169 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1170 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1171
1172 // Prepare IP for longjmp.
1173 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1174 .addMBB(RestoreMBB);
1175 // Store IP for return from jmp, slot 2, offset = 1.
1176 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1177 .addReg(LabelReg)
1178 .addReg(BufReg)
1179 .addImm(LabelOffset)
1180 .addReg(0);
1181
1182 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1183 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1184 if (HasFP) {
1185 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1186 .addReg(SpecialRegs->getFramePointerRegister())
1187 .addReg(BufReg)
1188 .addImm(FPOffset)
1189 .addReg(0);
1190 }
1191
1192 // Store SP.
1193 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1194 .addReg(SpecialRegs->getStackPointerRegister())
1195 .addReg(BufReg)
1196 .addImm(SPOffset)
1197 .addReg(0);
1198
1199 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1200 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1201 if (BackChain) {
1202 Register BCReg = MRI.createVirtualRegister(PtrRC);
1203 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1204 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1205 .addReg(SpecialRegs->getStackPointerRegister())
1206 .addImm(TFL->getBackchainOffset(*MF))
1207 .addReg(0);
1208
1209 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1210 .addReg(BCReg)
1211 .addReg(BufReg)
1212 .addImm(BCOffset)
1213 .addReg(0);
1214 }
1215
1216 // Setup.
1217 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1218 .addMBB(RestoreMBB);
1219
1220 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1221 MIB.addRegMask(RegInfo->getNoPreservedMask());
1222
1223 ThisMBB->addSuccessor(MainMBB);
1224 ThisMBB->addSuccessor(RestoreMBB);
1225
1226 // mainMBB:
1227 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1228 MainMBB->addSuccessor(SinkMBB);
1229
1230 // sinkMBB:
1231 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1232 .addReg(MainDstReg)
1233 .addMBB(MainMBB)
1234 .addReg(RestoreDstReg)
1235 .addMBB(RestoreMBB);
1236
1237 // restoreMBB.
1238 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1239 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1240 RestoreMBB->addSuccessor(SinkMBB);
1241
1242 MI.eraseFromParent();
1243
1244 return SinkMBB;
1245}
1246
1249 MachineBasicBlock *MBB) const {
1250
1251 DebugLoc DL = MI.getDebugLoc();
1252 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1253
1254 MachineFunction *MF = MBB->getParent();
1256
1257 MVT PVT = getPointerTy(MF->getDataLayout());
1258 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1259 Register BufReg = MI.getOperand(0).getReg();
1260 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1261 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1262
1263 Register Tmp = MRI.createVirtualRegister(RC);
1264 Register BCReg = MRI.createVirtualRegister(RC);
1265
1267
1268 const int64_t FPOffset = 0;
1269 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1270 const int64_t BCOffset = 2 * PVT.getStoreSize();
1271 const int64_t SPOffset = 3 * PVT.getStoreSize();
1272 const int64_t LPOffset = 4 * PVT.getStoreSize();
1273
1274 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1275 .addReg(BufReg)
1276 .addImm(LabelOffset)
1277 .addReg(0);
1278
1279 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1280 SpecialRegs->getFramePointerRegister())
1281 .addReg(BufReg)
1282 .addImm(FPOffset)
1283 .addReg(0);
1284
1285 // We are restoring R13 even though we never stored in setjmp from llvm,
1286 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1287 // gcc setjmp and llvm longjmp.
1288 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1289 .addReg(BufReg)
1290 .addImm(LPOffset)
1291 .addReg(0);
1292
1293 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1294 if (BackChain) {
1295 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1296 .addReg(BufReg)
1297 .addImm(BCOffset)
1298 .addReg(0);
1299 }
1300
1301 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1302 SpecialRegs->getStackPointerRegister())
1303 .addReg(BufReg)
1304 .addImm(SPOffset)
1305 .addReg(0);
1306
1307 if (BackChain) {
1308 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1309 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1310 .addReg(BCReg)
1311 .addReg(SpecialRegs->getStackPointerRegister())
1312 .addImm(TFL->getBackchainOffset(*MF))
1313 .addReg(0);
1314 }
1315
1316 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1317
1318 MI.eraseFromParent();
1319 return MBB;
1320}
1321
1323 const MachineFunction &MF) const {
1324 // Without vector support, a v2i64 store would just be split again.
1325 return MemVT != MVT::v2i64 || Subtarget.hasVector();
1326}
1327
1329 EVT VecVT) const {
1330 // Without vector support, a v2i64 is just a pair of GPRs.
1331 return !Subtarget.hasVector();
1332}
1333
1334/// Returns true if stack probing through inline assembly is requested.
1336 // If the function specifically requests inline stack probes, emit them.
1337 if (MF.getFunction().hasFnAttribute("probe-stack"))
1338 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1339 "inline-asm";
1340 return false;
1341}
1342
1347
1352
1355 const AtomicRMWInst *RMW) const {
1356 // Don't expand subword operations as they require special treatment.
1357 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1359
1360 // Don't expand if there is a target instruction available.
1361 if (Subtarget.hasInterlockedAccess1() &&
1362 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1369
1371}
1372
1374 // We can use CGFI or CLGFI.
1375 return isInt<32>(Imm) || isUInt<32>(Imm);
1376}
1377
1379 // We can use ALGFI or SLGFI.
1380 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1381}
1382
1384 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1385 // Unaligned accesses should never be slower than the expanded version.
1386 // We check specifically for aligned accesses in the few cases where
1387 // they are required.
1388 if (Fast)
1389 *Fast = 1;
1390 return true;
1391}
1392
1394 EVT VT = Y.getValueType();
1395
1396 // We can use NC(G)RK for types in GPRs ...
1397 if (VT == MVT::i32 || VT == MVT::i64)
1398 return Subtarget.hasMiscellaneousExtensions3();
1399
1400 // ... or VNC for types in VRs.
1401 if (VT.isVector() || VT == MVT::i128)
1402 return Subtarget.hasVector();
1403
1404 return false;
1405}
1406
1407// Information about the addressing mode for a memory access.
1409 // True if a long displacement is supported.
1411
1412 // True if use of index register is supported.
1414
1415 AddressingMode(bool LongDispl, bool IdxReg) :
1416 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1417};
1418
1419// Return the desired addressing mode for a Load which has only one use (in
1420// the same block) which is a Store.
1422 Type *Ty) {
1423 // With vector support a Load->Store combination may be combined to either
1424 // an MVC or vector operations and it seems to work best to allow the
1425 // vector addressing mode.
1426 if (HasVector)
1427 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1428
1429 // Otherwise only the MVC case is special.
1430 bool MVC = Ty->isIntegerTy(8);
1431 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1432}
1433
1434// Return the addressing mode which seems most desirable given an LLVM
1435// Instruction pointer.
1436static AddressingMode
1439 switch (II->getIntrinsicID()) {
1440 default: break;
1441 case Intrinsic::memset:
1442 case Intrinsic::memmove:
1443 case Intrinsic::memcpy:
1444 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1445 }
1446 }
1447
1448 if (isa<LoadInst>(I) && I->hasOneUse()) {
1449 auto *SingleUser = cast<Instruction>(*I->user_begin());
1450 if (SingleUser->getParent() == I->getParent()) {
1451 if (isa<ICmpInst>(SingleUser)) {
1452 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1453 if (C->getBitWidth() <= 64 &&
1454 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1455 // Comparison of memory with 16 bit signed / unsigned immediate
1456 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1457 } else if (isa<StoreInst>(SingleUser))
1458 // Load->Store
1459 return getLoadStoreAddrMode(HasVector, I->getType());
1460 }
1461 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1462 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1463 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1464 // Load->Store
1465 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1466 }
1467
1468 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1469
1470 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1471 // dependencies (LDE only supports small offsets).
1472 // * Utilize the vector registers to hold floating point
1473 // values (vector load / store instructions only support small
1474 // offsets).
1475
1476 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1477 I->getOperand(0)->getType());
1478 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1479 bool IsVectorAccess = MemAccessTy->isVectorTy();
1480
1481 // A store of an extracted vector element will be combined into a VSTE type
1482 // instruction.
1483 if (!IsVectorAccess && isa<StoreInst>(I)) {
1484 Value *DataOp = I->getOperand(0);
1485 if (isa<ExtractElementInst>(DataOp))
1486 IsVectorAccess = true;
1487 }
1488
1489 // A load which gets inserted into a vector element will be combined into a
1490 // VLE type instruction.
1491 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1492 User *LoadUser = *I->user_begin();
1493 if (isa<InsertElementInst>(LoadUser))
1494 IsVectorAccess = true;
1495 }
1496
1497 if (IsFPAccess || IsVectorAccess)
1498 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1499 }
1500
1501 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1502}
1503
1505 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1506 // Punt on globals for now, although they can be used in limited
1507 // RELATIVE LONG cases.
1508 if (AM.BaseGV)
1509 return false;
1510
1511 // Require a 20-bit signed offset.
1512 if (!isInt<20>(AM.BaseOffs))
1513 return false;
1514
1515 bool RequireD12 =
1516 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1517 AddressingMode SupportedAM(!RequireD12, true);
1518 if (I != nullptr)
1519 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1520
1521 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1522 return false;
1523
1524 if (!SupportedAM.IndexReg)
1525 // No indexing allowed.
1526 return AM.Scale == 0;
1527 else
1528 // Indexing is OK but no scale factor can be applied.
1529 return AM.Scale == 0 || AM.Scale == 1;
1530}
1531
1533 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1534 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1535 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1536
1537 assert(Limit != ~0U &&
1538 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1539
1540 if (Op.isZeroMemset())
1541 return false; // Memset zero: Use XC.
1542
1543 const int MVCFastLen = 16;
1544 // Use MVC up to 16 bytes for memcpy. Small memset uses STC/MVI for first
1545 // byte.
1546 if (Op.isMemcpy() && Op.size() <= MVCFastLen)
1547 return false;
1548 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1549 return false;
1550
1551 // Avoid unaligned VL/VST:s.
1552 if ((Op.size() >= 16 && !Op.isAligned(Align(8))) ||
1553 (Op.size() >= 25 && Op.size() <= 31))
1554 return false;
1555
1557 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1558}
1559
1561 LLVMContext &Context, const MemOp &Op,
1562 const AttributeList &FuncAttributes) const {
1563 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1564}
1565
1566bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1567 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1568 return false;
1569 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1570 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1571 return FromBits > ToBits;
1572}
1573
1575 if (!FromVT.isInteger() || !ToVT.isInteger())
1576 return false;
1577 unsigned FromBits = FromVT.getFixedSizeInBits();
1578 unsigned ToBits = ToVT.getFixedSizeInBits();
1579 return FromBits > ToBits;
1580}
1581
1583 unsigned Opc = N->getOpcode();
1584 if ((Opc == ISD::SINT_TO_FP || Opc == ISD::UINT_TO_FP) && VT.isVector() &&
1585 VT.getScalarSizeInBits() < N->getValueType(0).getScalarSizeInBits())
1586 return false;
1588}
1589
1590//===----------------------------------------------------------------------===//
1591// Inline asm support
1592//===----------------------------------------------------------------------===//
1593
1596 if (Constraint.size() == 1) {
1597 switch (Constraint[0]) {
1598 case 'a': // Address register
1599 case 'd': // Data register (equivalent to 'r')
1600 case 'f': // Floating-point register
1601 case 'h': // High-part register
1602 case 'r': // General-purpose register
1603 case 'v': // Vector register
1604 return C_RegisterClass;
1605
1606 case 'Q': // Memory with base and unsigned 12-bit displacement
1607 case 'R': // Likewise, plus an index
1608 case 'S': // Memory with base and signed 20-bit displacement
1609 case 'T': // Likewise, plus an index
1610 case 'm': // Equivalent to 'T'.
1611 return C_Memory;
1612
1613 case 'I': // Unsigned 8-bit constant
1614 case 'J': // Unsigned 12-bit constant
1615 case 'K': // Signed 16-bit constant
1616 case 'L': // Signed 20-bit displacement (on all targets we support)
1617 case 'M': // 0x7fffffff
1618 return C_Immediate;
1619
1620 default:
1621 break;
1622 }
1623 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1624 switch (Constraint[1]) {
1625 case 'Q': // Address with base and unsigned 12-bit displacement
1626 case 'R': // Likewise, plus an index
1627 case 'S': // Address with base and signed 20-bit displacement
1628 case 'T': // Likewise, plus an index
1629 return C_Address;
1630
1631 default:
1632 break;
1633 }
1634 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1635 if (StringRef("{@cc}").compare(Constraint) == 0)
1636 return C_Other;
1637 }
1638 return TargetLowering::getConstraintType(Constraint);
1639}
1640
1643 AsmOperandInfo &Info, const char *Constraint) const {
1645 Value *CallOperandVal = Info.CallOperandVal;
1646 // If we don't have a value, we can't do a match,
1647 // but allow it at the lowest weight.
1648 if (!CallOperandVal)
1649 return CW_Default;
1650 Type *type = CallOperandVal->getType();
1651 // Look at the constraint type.
1652 switch (*Constraint) {
1653 default:
1654 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1655 break;
1656
1657 case 'a': // Address register
1658 case 'd': // Data register (equivalent to 'r')
1659 case 'h': // High-part register
1660 case 'r': // General-purpose register
1661 Weight =
1662 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1663 break;
1664
1665 case 'f': // Floating-point register
1666 if (!useSoftFloat())
1667 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1668 break;
1669
1670 case 'v': // Vector register
1671 if (Subtarget.hasVector())
1672 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1673 : CW_Default;
1674 break;
1675
1676 case 'I': // Unsigned 8-bit constant
1677 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1678 if (isUInt<8>(C->getZExtValue()))
1679 Weight = CW_Constant;
1680 break;
1681
1682 case 'J': // Unsigned 12-bit constant
1683 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1684 if (isUInt<12>(C->getZExtValue()))
1685 Weight = CW_Constant;
1686 break;
1687
1688 case 'K': // Signed 16-bit constant
1689 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1690 if (isInt<16>(C->getSExtValue()))
1691 Weight = CW_Constant;
1692 break;
1693
1694 case 'L': // Signed 20-bit displacement (on all targets we support)
1695 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1696 if (isInt<20>(C->getSExtValue()))
1697 Weight = CW_Constant;
1698 break;
1699
1700 case 'M': // 0x7fffffff
1701 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1702 if (C->getZExtValue() == 0x7fffffff)
1703 Weight = CW_Constant;
1704 break;
1705 }
1706 return Weight;
1707}
1708
1709// Parse a "{tNNN}" register constraint for which the register type "t"
1710// has already been verified. MC is the class associated with "t" and
1711// Map maps 0-based register numbers to LLVM register numbers.
1712static std::pair<unsigned, const TargetRegisterClass *>
1714 const unsigned *Map, unsigned Size) {
1715 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1716 if (isdigit(Constraint[2])) {
1717 unsigned Index;
1718 bool Failed =
1719 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1720 if (!Failed && Index < Size && Map[Index])
1721 return std::make_pair(Map[Index], RC);
1722 }
1723 return std::make_pair(0U, nullptr);
1724}
1725
1726std::pair<unsigned, const TargetRegisterClass *>
1728 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1729 if (Constraint.size() == 1) {
1730 // GCC Constraint Letters
1731 switch (Constraint[0]) {
1732 default: break;
1733 case 'd': // Data register (equivalent to 'r')
1734 case 'r': // General-purpose register
1735 if (VT.getSizeInBits() == 64)
1736 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1737 else if (VT.getSizeInBits() == 128)
1738 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1739 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1740
1741 case 'a': // Address register
1742 if (VT == MVT::i64)
1743 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1744 else if (VT == MVT::i128)
1745 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1746 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1747
1748 case 'h': // High-part register (an LLVM extension)
1749 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1750
1751 case 'f': // Floating-point register
1752 if (!useSoftFloat()) {
1753 if (VT.getSizeInBits() == 16)
1754 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1755 else if (VT.getSizeInBits() == 64)
1756 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1757 else if (VT.getSizeInBits() == 128)
1758 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1759 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1760 }
1761 break;
1762
1763 case 'v': // Vector register
1764 if (Subtarget.hasVector()) {
1765 if (VT.getSizeInBits() == 16)
1766 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1767 if (VT.getSizeInBits() == 32)
1768 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1769 if (VT.getSizeInBits() == 64)
1770 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1771 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1772 }
1773 break;
1774 }
1775 }
1776 if (Constraint.starts_with("{")) {
1777
1778 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1779 // to check the size on.
1780 auto getVTSizeInBits = [&VT]() {
1781 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1782 };
1783
1784 // We need to override the default register parsing for GPRs and FPRs
1785 // because the interpretation depends on VT. The internal names of
1786 // the registers are also different from the external names
1787 // (F0D and F0S instead of F0, etc.).
1788 if (Constraint[1] == 'r') {
1789 if (getVTSizeInBits() == 32)
1790 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1792 if (getVTSizeInBits() == 128)
1793 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1795 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1797 }
1798 if (Constraint[1] == 'f') {
1799 if (useSoftFloat())
1800 return std::make_pair(
1801 0u, static_cast<const TargetRegisterClass *>(nullptr));
1802 if (getVTSizeInBits() == 16)
1803 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1805 if (getVTSizeInBits() == 32)
1806 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1808 if (getVTSizeInBits() == 128)
1809 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1811 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1813 }
1814 if (Constraint[1] == 'v') {
1815 if (!Subtarget.hasVector())
1816 return std::make_pair(
1817 0u, static_cast<const TargetRegisterClass *>(nullptr));
1818 if (getVTSizeInBits() == 16)
1819 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1821 if (getVTSizeInBits() == 32)
1822 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1824 if (getVTSizeInBits() == 64)
1825 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1827 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1829 }
1830 if (Constraint[1] == '@') {
1831 if (StringRef("{@cc}").compare(Constraint) == 0)
1832 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1833 }
1834 }
1835 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1836}
1837
1838// FIXME? Maybe this could be a TableGen attribute on some registers and
1839// this table could be generated automatically from RegInfo.
1842 const MachineFunction &MF) const {
1843 Register Reg =
1845 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1846 : SystemZ::NoRegister)
1847 .Case("r15",
1848 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1849 .Default(Register());
1850
1851 return Reg;
1852}
1853
1855 ExceptionHandling EH, const Constant *PersonalityFn) const {
1856 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1857}
1858
1860 ExceptionHandling EH, const Constant *PersonalityFn) const {
1861 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1862}
1863
1864// Convert condition code in CCReg to an i32 value.
1866 SDLoc DL(CCReg);
1867 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1868 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1869 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1870}
1871
1872// Lower @cc targets via setcc.
1874 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1875 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1876 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1877 return SDValue();
1878
1879 // Check that return type is valid.
1880 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1881 OpInfo.ConstraintVT.getSizeInBits() < 8)
1882 report_fatal_error("Glue output operand is of invalid type");
1883
1884 if (Glue.getNode()) {
1885 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1886 Chain = Glue.getValue(1);
1887 } else
1888 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1889 return getCCResult(DAG, Glue);
1890}
1891
1893 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1894 SelectionDAG &DAG) const {
1895 // Only support length 1 constraints for now.
1896 if (Constraint.size() == 1) {
1897 switch (Constraint[0]) {
1898 case 'I': // Unsigned 8-bit constant
1899 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1900 if (isUInt<8>(C->getZExtValue()))
1901 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1902 Op.getValueType()));
1903 return;
1904
1905 case 'J': // Unsigned 12-bit constant
1906 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1907 if (isUInt<12>(C->getZExtValue()))
1908 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1909 Op.getValueType()));
1910 return;
1911
1912 case 'K': // Signed 16-bit constant
1913 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1914 if (isInt<16>(C->getSExtValue()))
1915 Ops.push_back(DAG.getSignedTargetConstant(
1916 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1917 return;
1918
1919 case 'L': // Signed 20-bit displacement (on all targets we support)
1920 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1921 if (isInt<20>(C->getSExtValue()))
1922 Ops.push_back(DAG.getSignedTargetConstant(
1923 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1924 return;
1925
1926 case 'M': // 0x7fffffff
1927 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1928 if (C->getZExtValue() == 0x7fffffff)
1929 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1930 Op.getValueType()));
1931 return;
1932 }
1933 }
1935}
1936
1937//===----------------------------------------------------------------------===//
1938// Calling conventions
1939//===----------------------------------------------------------------------===//
1940
1941#define GET_CALLING_CONV_IMPL
1942#include "SystemZGenCallingConv.inc"
1943
1945 CallingConv::ID) const {
1946 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1947 SystemZ::R14D, 0 };
1948 return ScratchRegs;
1949}
1950
1952 Type *ToType) const {
1953 return isTruncateFree(FromType, ToType);
1954}
1955
1957 return CI->isTailCall();
1958}
1959
1960// Value is a value that has been passed to us in the location described by VA
1961// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1962// any loads onto Chain.
1964 CCValAssign &VA, SDValue Chain,
1965 SDValue Value) {
1966 // If the argument has been promoted from a smaller type, insert an
1967 // assertion to capture this.
1968 if (VA.getLocInfo() == CCValAssign::SExt)
1970 DAG.getValueType(VA.getValVT()));
1971 else if (VA.getLocInfo() == CCValAssign::ZExt)
1973 DAG.getValueType(VA.getValVT()));
1974
1975 if (VA.isExtInLoc())
1976 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1977 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1978 // If this is a short vector argument loaded from the stack,
1979 // extend from i64 to full vector size and then bitcast.
1980 assert(VA.getLocVT() == MVT::i64);
1981 assert(VA.getValVT().isVector());
1982 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1983 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1984 } else
1985 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1986 return Value;
1987}
1988
1989// Value is a value of type VA.getValVT() that we need to copy into
1990// the location described by VA. Return a copy of Value converted to
1991// VA.getValVT(). The caller is responsible for handling indirect values.
1993 CCValAssign &VA, SDValue Value) {
1994 switch (VA.getLocInfo()) {
1995 case CCValAssign::SExt:
1996 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1997 case CCValAssign::ZExt:
1998 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1999 case CCValAssign::AExt:
2000 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
2001 case CCValAssign::BCvt: {
2002 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
2003 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
2004 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
2005 // For an f32 vararg we need to first promote it to an f64 and then
2006 // bitcast it to an i64.
2007 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
2008 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
2009 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
2010 ? MVT::v2i64
2011 : VA.getLocVT();
2012 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
2013 // For ELF, this is a short vector argument to be stored to the stack,
2014 // bitcast to v2i64 and then extract first element.
2015 if (BitCastToType == MVT::v2i64)
2016 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
2017 DAG.getConstant(0, DL, MVT::i32));
2018 return Value;
2019 }
2020 case CCValAssign::Full:
2021 return Value;
2022 default:
2023 llvm_unreachable("Unhandled getLocInfo()");
2024 }
2025}
2026
2028 SDLoc DL(In);
2029 SDValue Lo, Hi;
2030 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2031 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
2032 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
2033 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
2034 DAG.getConstant(64, DL, MVT::i32)));
2035 } else {
2036 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
2037 }
2038
2039 return DAG.getNode(SystemZISD::PAIR128, DL, MVT::v2i64, Hi, Lo);
2040}
2041
2043 SDLoc DL(In);
2044 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
2045 DL, MVT::i64, In);
2046 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
2047 DL, MVT::i64, In);
2048
2049 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2050 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
2051 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
2052 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
2053 DAG.getConstant(64, DL, MVT::i32));
2054 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
2055 } else {
2056 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
2057 }
2058}
2059
2061 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2062 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2063 EVT ValueVT = Val.getValueType();
2064 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2065 // Inline assembly operand.
2066 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
2067 return true;
2068 }
2069
2070 return false;
2071}
2072
2074 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2075 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2076 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2077 // Inline assembly operand.
2078 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2079 return DAG.getBitcast(ValueVT, Res);
2080 }
2081
2082 return SDValue();
2083}
2084
2085// The first part of a split stack argument is at index I in Args (and
2086// ArgLocs). Return the type of a part and the number of them by reference.
2087template <class ArgTy>
2089 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2090 MVT &PartVT, unsigned &NumParts) {
2091 if (!Args[I].Flags.isSplit())
2092 return false;
2093 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2094 "ArgLocs havoc.");
2095 PartVT = ArgLocs[I].getValVT();
2096 NumParts = 1;
2097 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2098 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2099 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2100 ++NumParts;
2101 if (Args[PartIdx].Flags.isSplitEnd())
2102 break;
2103 }
2104 return true;
2105}
2106
2107// Return the virtual register holding the incoming "ADA" special register (R5)
2108// of an XPLINK function, creating it on first use. LowerFormalArguments is not
2109// called for naked functions, but those still get R5 on entry and may use it to
2110// address globals and functions.
2112 SystemZMachineFunctionInfo *FuncInfo =
2114 Register ADAvReg = FuncInfo->getADAVirtualRegister();
2115 if (ADAvReg)
2116 return ADAvReg;
2117
2119 ADAvReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2120 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2122 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2123 FuncInfo->setADAVirtualRegister(ADAvReg);
2124 return ADAvReg;
2125}
2126
2128 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2129 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2130 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2132 MachineFrameInfo &MFI = MF.getFrameInfo();
2134 SystemZMachineFunctionInfo *FuncInfo =
2136 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2137 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2138
2139 // Assign locations to all of the incoming arguments.
2141 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2142 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2143 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2144
2145 unsigned NumFixedGPRs = 0;
2146 unsigned NumFixedFPRs = 0;
2147 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2148 SDValue ArgValue;
2149 CCValAssign &VA = ArgLocs[I];
2150 EVT LocVT = VA.getLocVT();
2151 if (VA.isRegLoc()) {
2152 // Arguments passed in registers
2153 const TargetRegisterClass *RC;
2154 switch (LocVT.getSimpleVT().SimpleTy) {
2155 default:
2156 // Integers smaller than i64 should be promoted to i64.
2157 llvm_unreachable("Unexpected argument type");
2158 case MVT::i32:
2159 NumFixedGPRs += 1;
2160 RC = &SystemZ::GR32BitRegClass;
2161 break;
2162 case MVT::i64:
2163 NumFixedGPRs += 1;
2164 RC = &SystemZ::GR64BitRegClass;
2165 break;
2166 case MVT::f16:
2167 NumFixedFPRs += 1;
2168 RC = &SystemZ::FP16BitRegClass;
2169 break;
2170 case MVT::f32:
2171 NumFixedFPRs += 1;
2172 RC = &SystemZ::FP32BitRegClass;
2173 break;
2174 case MVT::f64:
2175 NumFixedFPRs += 1;
2176 RC = &SystemZ::FP64BitRegClass;
2177 break;
2178 case MVT::f128:
2179 NumFixedFPRs += 2;
2180 RC = &SystemZ::FP128BitRegClass;
2181 break;
2182 case MVT::v16i8:
2183 case MVT::v8i16:
2184 case MVT::v4i32:
2185 case MVT::v2i64:
2186 case MVT::v8f16:
2187 case MVT::v4f32:
2188 case MVT::v2f64:
2189 RC = &SystemZ::VR128BitRegClass;
2190 break;
2191 }
2192
2193 Register VReg = MRI.createVirtualRegister(RC);
2194 MRI.addLiveIn(VA.getLocReg(), VReg);
2195 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2196 } else {
2197 assert(VA.isMemLoc() && "Argument not register or memory");
2198
2199 // Create the frame index object for this incoming parameter.
2200 // FIXME: Pre-include call frame size in the offset, should not
2201 // need to manually add it here.
2202 int64_t ArgSPOffset = VA.getLocMemOffset();
2203 if (Subtarget.isTargetXPLINK64()) {
2204 auto &XPRegs =
2205 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2206 ArgSPOffset += XPRegs.getCallFrameSize();
2207 }
2208 int FI =
2209 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2210
2211 // Create the SelectionDAG nodes corresponding to a load
2212 // from this parameter. Unpromoted ints and floats are
2213 // passed as right-justified 8-byte values.
2214 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2215 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2216 VA.getLocVT() == MVT::f16) {
2217 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2218 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2219 DAG.getIntPtrConstant(SlotOffs, DL));
2220 }
2221 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2223 }
2224
2225 // Convert the value of the argument register into the value that's
2226 // being passed.
2227 if (VA.getLocInfo() == CCValAssign::Indirect) {
2228 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2230 // If the original argument was split (e.g. i128), we need
2231 // to load all parts of it here (using the same address).
2232 MVT PartVT;
2233 unsigned NumParts;
2234 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2235 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2236 ++I;
2237 CCValAssign &PartVA = ArgLocs[I];
2238 unsigned PartOffset = Ins[I].PartOffset;
2239 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2240 DAG.getIntPtrConstant(PartOffset, DL));
2241 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2243 assert(PartOffset && "Offset should be non-zero.");
2244 }
2245 }
2246 } else if (Subtarget.isTargetXPLINK64() &&
2247 (VA.getLocInfo() == CCValAssign::SExt ||
2248 VA.getLocInfo() == CCValAssign::ZExt) &&
2249 Ins[I].ArgVT.isSimple()) {
2250 // Some prior z/OS compilers do not always perform the extension of
2251 // short integer arguments or pointers. To accommodate those, do not
2252 // rely on that extension by avoiding any AssertSext/AssertZext nodes by
2253 // directly truncating ArgValue to the original argument type.
2254 MVT OrigVT = Ins[I].ArgVT.getSimpleVT();
2255 InVals.push_back(DAG.getNode(ISD::TRUNCATE, DL, OrigVT, ArgValue));
2256 } else
2257 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2258 }
2259
2260 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2261 // Save the number of non-varargs registers for later use by va_start, etc.
2262 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2263 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2264
2265 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2266 Subtarget.getSpecialRegisters());
2267
2268 // Likewise the address (in the form of a frame index) of where the
2269 // first stack vararg would be. The 1-byte size here is arbitrary.
2270 // FIXME: Pre-include call frame size in the offset, should not
2271 // need to manually add it here.
2272 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2273 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2274 FuncInfo->setVarArgsFrameIndex(FI);
2275 }
2276
2277 if (IsVarArg && Subtarget.isTargetELF()) {
2278 // Save the number of non-varargs registers for later use by va_start, etc.
2279 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2280 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2281
2282 // Likewise the address (in the form of a frame index) of where the
2283 // first stack vararg would be. The 1-byte size here is arbitrary.
2284 int64_t VarArgsOffset = CCInfo.getStackSize();
2285 FuncInfo->setVarArgsFrameIndex(
2286 MFI.CreateFixedObject(1, VarArgsOffset, true));
2287
2288 // ...and a similar frame index for the caller-allocated save area
2289 // that will be used to store the incoming registers.
2290 int64_t RegSaveOffset =
2291 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2292 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2293 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2294
2295 // Store the FPR varargs in the reserved frame slots. (We store the
2296 // GPRs as part of the prologue.)
2297 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2299 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2300 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2301 int FI =
2303 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2305 &SystemZ::FP64BitRegClass);
2306 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2307 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2309 }
2310 // Join the stores, which are independent of one another.
2311 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2312 ArrayRef(&MemOps[NumFixedFPRs],
2313 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2314 }
2315 }
2316
2317 return Chain;
2318}
2319
2320static bool canUseSiblingCall(const CCState &ArgCCInfo,
2323 // Punt if there are any indirect or stack arguments, or if the call
2324 // needs the callee-saved argument register R6, or if the call uses
2325 // the callee-saved register arguments SwiftSelf and SwiftError.
2326 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2327 CCValAssign &VA = ArgLocs[I];
2329 return false;
2330 if (!VA.isRegLoc())
2331 return false;
2332 Register Reg = VA.getLocReg();
2333 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2334 return false;
2335 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2336 return false;
2337 }
2338 return true;
2339}
2340
2342 unsigned Offset, bool LoadAdr = false) {
2346
2347 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2348 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2349
2350 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2351 if (!LoadAdr)
2352 Result = DAG.getLoad(
2353 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2355
2356 return Result;
2357}
2358
2359// ADA access using Global value
2360// Note: for functions, address of descriptor is returned
2362 EVT PtrVT) {
2363 unsigned ADAtype;
2364 bool LoadAddr = false;
2365 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2366 bool IsFunction =
2367 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2368 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2369
2370 if (IsFunction) {
2371 if (IsInternal) {
2373 LoadAddr = true;
2374 } else
2376 } else {
2378 }
2379 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2380
2381 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2382}
2383
2384static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2385 SDLoc &DL, SDValue &Chain) {
2386 unsigned ADADelta = 0; // ADA offset in desc.
2387 unsigned EPADelta = 8; // EPA offset in desc.
2390
2391 // XPLink calling convention.
2392 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2393 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2394 G->getGlobal()->hasPrivateLinkage());
2395 if (IsInternal) {
2397 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2398 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2399 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2400 return true;
2401 } else {
2403 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2404 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2405 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2406 }
2407 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2409 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2410 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2411 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2412 } else {
2413 // Function pointer case
2414 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2415 DAG.getConstant(ADADelta, DL, PtrVT));
2416 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2418 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2419 DAG.getConstant(EPADelta, DL, PtrVT));
2420 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2422 }
2423 return false;
2424}
2425
2426SDValue
2428 SmallVectorImpl<SDValue> &InVals) const {
2429 SelectionDAG &DAG = CLI.DAG;
2430 SDLoc &DL = CLI.DL;
2432 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2434 SDValue Chain = CLI.Chain;
2435 SDValue Callee = CLI.Callee;
2436 bool &IsTailCall = CLI.IsTailCall;
2437 CallingConv::ID CallConv = CLI.CallConv;
2438 bool IsVarArg = CLI.IsVarArg;
2440 EVT PtrVT = getPointerTy(MF.getDataLayout());
2441 LLVMContext &Ctx = *DAG.getContext();
2442 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2443
2444 // FIXME: z/OS support to be added in later.
2445 if (Subtarget.isTargetXPLINK64()) {
2446 if (CLI.CB && CLI.CB->isMustTailCall())
2447 report_fatal_error("musttail call is not supported on XPLINK64");
2448 IsTailCall = false;
2449 }
2450
2451 // Integer args <=32 bits should have an extension attribute.
2452 verifyNarrowIntegerArgs_Call(CLI, Outs, &MF.getFunction(), Callee);
2453
2454 // Analyze the operands of the call, assigning locations to each operand.
2456 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2457 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2458
2459 // We don't support GuaranteedTailCallOpt, only automatically-detected
2460 // sibling calls.
2461 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2462 IsTailCall = false;
2463
2464 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
2465 report_fatal_error("failed to perform tail call elimination on a call "
2466 "site marked musttail");
2467
2468 // Get a count of how many bytes are to be pushed on the stack.
2469 unsigned NumBytes = ArgCCInfo.getStackSize();
2470
2471 // Mark the start of the call.
2472 if (!IsTailCall)
2473 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2474
2475 // Copy argument values to their designated locations.
2477 SmallVector<SDValue, 8> MemOpChains;
2478 SDValue StackPtr;
2479 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2480 CCValAssign &VA = ArgLocs[I];
2481 SDValue ArgValue = OutVals[I];
2482
2483 if (VA.getLocInfo() == CCValAssign::Indirect) {
2484 // Store the argument in a stack slot and pass its address.
2485 EVT SlotVT;
2486 MVT PartVT;
2487 unsigned NumParts = 1;
2488 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2489 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2490 else
2491 SlotVT = Outs[I].VT;
2492 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2493 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2494
2495 MachinePointerInfo StackPtrInfo =
2497 MemOpChains.push_back(
2498 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2499 // If the original argument was split (e.g. i128), we need
2500 // to store all parts of it here (and pass just one address).
2501 assert(Outs[I].PartOffset == 0);
2502 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2503 ++I;
2504 SDValue PartValue = OutVals[I];
2505 unsigned PartOffset = Outs[I].PartOffset;
2506 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2507 DAG.getIntPtrConstant(PartOffset, DL));
2508 MemOpChains.push_back(
2509 DAG.getStore(Chain, DL, PartValue, Address,
2510 StackPtrInfo.getWithOffset(PartOffset)));
2511 assert(PartOffset && "Offset should be non-zero.");
2512 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2513 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2514 }
2515 ArgValue = SpillSlot;
2516 } else
2517 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2518
2519 if (VA.isRegLoc()) {
2520 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2521 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2522 // and low values.
2523 if (VA.getLocVT() == MVT::i128)
2524 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2525 // Queue up the argument copies and emit them at the end.
2526 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2527 } else {
2528 assert(VA.isMemLoc() && "Argument not register or memory");
2529
2530 // Work out the address of the stack slot. Unpromoted ints and
2531 // floats are passed as right-justified 8-byte values.
2532 if (!StackPtr.getNode())
2533 StackPtr = DAG.getCopyFromReg(Chain, DL,
2534 Regs->getStackPointerRegister(), PtrVT);
2535 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2536 VA.getLocMemOffset();
2537 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2538 Offset += 4;
2539 else if (VA.getLocVT() == MVT::f16)
2540 Offset += 6;
2541 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2543
2544 // Emit the store.
2545 MemOpChains.push_back(
2546 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2547
2548 // Although long doubles or vectors are passed through the stack when
2549 // they are vararg (non-fixed arguments), if a long double or vector
2550 // occupies the third and fourth slot of the argument list GPR3 should
2551 // still shadow the third slot of the argument list.
2552 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2553 SDValue ShadowArgValue =
2554 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2555 DAG.getIntPtrConstant(1, DL));
2556 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2557 }
2558 }
2559 }
2560
2561 // Join the stores, which are independent of one another.
2562 if (!MemOpChains.empty())
2563 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2564
2565 // Accept direct calls by converting symbolic call addresses to the
2566 // associated Target* opcodes. Force %r1 to be used for indirect
2567 // tail calls.
2568 SDValue Glue;
2569
2570 if (Subtarget.isTargetXPLINK64()) {
2571 SDValue ADA;
2572 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2573 if (!IsBRASL) {
2574 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2575 ->getAddressOfCalleeRegister();
2576 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2577 Glue = Chain.getValue(1);
2578 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2579 }
2580 RegsToPass.push_back(std::make_pair(
2581 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2582 } else {
2583 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2584 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2585 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2586 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2587 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2588 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2589 } else if (IsTailCall) {
2590 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2591 Glue = Chain.getValue(1);
2592 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2593 }
2594 }
2595
2596 // Build a sequence of copy-to-reg nodes, chained and glued together.
2597 for (const auto &[Reg, N] : RegsToPass) {
2598 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2599 Glue = Chain.getValue(1);
2600 }
2601
2602 // The first call operand is the chain and the second is the target address.
2604 Ops.push_back(Chain);
2605 Ops.push_back(Callee);
2606
2607 // Add argument registers to the end of the list so that they are
2608 // known live into the call.
2609 for (const auto &[Reg, N] : RegsToPass)
2610 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2611
2612 // Add a register mask operand representing the call-preserved registers.
2613 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2614 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2615 assert(Mask && "Missing call preserved mask for calling convention");
2616 Ops.push_back(DAG.getRegisterMask(Mask));
2617
2618 // Glue the call to the argument copies, if any.
2619 if (Glue.getNode())
2620 Ops.push_back(Glue);
2621
2622 // Emit the call.
2623 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2624 if (IsTailCall) {
2625 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2626 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2627 return Ret;
2628 }
2629 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2630 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2631 Glue = Chain.getValue(1);
2632
2633 // Mark the end of the call, which is glued to the call itself.
2634 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2635 Glue = Chain.getValue(1);
2636
2637 // Assign locations to each value returned by this call.
2639 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2640 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2641
2642 // Copy all of the result registers out of their specified physreg.
2643 for (CCValAssign &VA : RetLocs) {
2644 // Copy the value out, gluing the copy to the end of the call sequence.
2645 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2646 VA.getLocVT(), Glue);
2647 Chain = RetValue.getValue(1);
2648 Glue = RetValue.getValue(2);
2649
2650 // Convert the value of the return register into the value that's
2651 // being returned.
2652 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2653 }
2654
2655 return Chain;
2656}
2657
2658// Generate a call taking the given operands as arguments and returning a
2659// result of type RetVT.
2661 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2662 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2663 bool DoesNotReturn, bool IsReturnValueUsed) const {
2665 Args.reserve(Ops.size());
2666
2667 for (SDValue Op : Ops) {
2669 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2670 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2671 Entry.IsZExt = !Entry.IsSExt;
2672 Args.push_back(Entry);
2673 }
2674
2675 SDValue Callee =
2676 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2677
2678 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2680 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2681 CLI.setDebugLoc(DL)
2682 .setChain(Chain)
2683 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2684 .setNoReturn(DoesNotReturn)
2685 .setDiscardResult(!IsReturnValueUsed)
2686 .setSExtResult(SignExtend)
2687 .setZExtResult(!SignExtend);
2688 return LowerCallTo(CLI);
2689}
2690
2692 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2693 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
2694 const Type *RetTy) const {
2695 // Special case that we cannot easily detect in RetCC_SystemZ since
2696 // i128 may not be a legal type.
2697 for (auto &Out : Outs)
2698 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2699 return false;
2700
2702 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2703 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2704}
2705
2706SDValue
2708 bool IsVarArg,
2710 const SmallVectorImpl<SDValue> &OutVals,
2711 const SDLoc &DL, SelectionDAG &DAG) const {
2713
2714 // Integer args <=32 bits should have an extension attribute.
2715 verifyNarrowIntegerArgs_Ret(CallConv, Outs, &MF.getFunction());
2716
2717 // Assign locations to each returned value.
2719 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2720 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2721
2722 // Quick exit for void returns
2723 if (RetLocs.empty())
2724 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2725
2726 if (CallConv == CallingConv::GHC)
2727 report_fatal_error("GHC functions return void only");
2728
2729 // Copy the result values into the output registers.
2730 SDValue Glue;
2732 RetOps.push_back(Chain);
2733 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2734 CCValAssign &VA = RetLocs[I];
2735 SDValue RetValue = OutVals[I];
2736
2737 // Make the return register live on exit.
2738 assert(VA.isRegLoc() && "Can only return in registers!");
2739
2740 // Promote the value as required.
2741 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2742
2743 // Chain and glue the copies together.
2744 Register Reg = VA.getLocReg();
2745 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2746 Glue = Chain.getValue(1);
2747 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2748 }
2749
2750 // Update chain and glue.
2751 RetOps[0] = Chain;
2752 if (Glue.getNode())
2753 RetOps.push_back(Glue);
2754
2755 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2756}
2757
2758// Return true if Op is an intrinsic node with chain that returns the CC value
2759// as its only (other) argument. Provide the associated SystemZISD opcode and
2760// the mask of valid CC values if so.
2761static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2762 unsigned &CCValid) {
2763 unsigned Id = Op.getConstantOperandVal(1);
2764 switch (Id) {
2765 case Intrinsic::s390_tbegin:
2766 Opcode = SystemZISD::TBEGIN;
2767 CCValid = SystemZ::CCMASK_TBEGIN;
2768 return true;
2769
2770 case Intrinsic::s390_tbegin_nofloat:
2771 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2772 CCValid = SystemZ::CCMASK_TBEGIN;
2773 return true;
2774
2775 case Intrinsic::s390_tend:
2776 Opcode = SystemZISD::TEND;
2777 CCValid = SystemZ::CCMASK_TEND;
2778 return true;
2779
2780 default:
2781 return false;
2782 }
2783}
2784
2785// Return true if Op is an intrinsic node without chain that returns the
2786// CC value as its final argument. Provide the associated SystemZISD
2787// opcode and the mask of valid CC values if so.
2788static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2789 unsigned Id = Op.getConstantOperandVal(0);
2790 switch (Id) {
2791 case Intrinsic::s390_vpkshs:
2792 case Intrinsic::s390_vpksfs:
2793 case Intrinsic::s390_vpksgs:
2794 Opcode = SystemZISD::PACKS_CC;
2795 CCValid = SystemZ::CCMASK_VCMP;
2796 return true;
2797
2798 case Intrinsic::s390_vpklshs:
2799 case Intrinsic::s390_vpklsfs:
2800 case Intrinsic::s390_vpklsgs:
2801 Opcode = SystemZISD::PACKLS_CC;
2802 CCValid = SystemZ::CCMASK_VCMP;
2803 return true;
2804
2805 case Intrinsic::s390_vceqbs:
2806 case Intrinsic::s390_vceqhs:
2807 case Intrinsic::s390_vceqfs:
2808 case Intrinsic::s390_vceqgs:
2809 case Intrinsic::s390_vceqqs:
2810 Opcode = SystemZISD::VICMPES;
2811 CCValid = SystemZ::CCMASK_VCMP;
2812 return true;
2813
2814 case Intrinsic::s390_vchbs:
2815 case Intrinsic::s390_vchhs:
2816 case Intrinsic::s390_vchfs:
2817 case Intrinsic::s390_vchgs:
2818 case Intrinsic::s390_vchqs:
2819 Opcode = SystemZISD::VICMPHS;
2820 CCValid = SystemZ::CCMASK_VCMP;
2821 return true;
2822
2823 case Intrinsic::s390_vchlbs:
2824 case Intrinsic::s390_vchlhs:
2825 case Intrinsic::s390_vchlfs:
2826 case Intrinsic::s390_vchlgs:
2827 case Intrinsic::s390_vchlqs:
2828 Opcode = SystemZISD::VICMPHLS;
2829 CCValid = SystemZ::CCMASK_VCMP;
2830 return true;
2831
2832 case Intrinsic::s390_vtm:
2833 Opcode = SystemZISD::VTM;
2834 CCValid = SystemZ::CCMASK_VCMP;
2835 return true;
2836
2837 case Intrinsic::s390_vfaebs:
2838 case Intrinsic::s390_vfaehs:
2839 case Intrinsic::s390_vfaefs:
2840 Opcode = SystemZISD::VFAE_CC;
2841 CCValid = SystemZ::CCMASK_ANY;
2842 return true;
2843
2844 case Intrinsic::s390_vfaezbs:
2845 case Intrinsic::s390_vfaezhs:
2846 case Intrinsic::s390_vfaezfs:
2847 Opcode = SystemZISD::VFAEZ_CC;
2848 CCValid = SystemZ::CCMASK_ANY;
2849 return true;
2850
2851 case Intrinsic::s390_vfeebs:
2852 case Intrinsic::s390_vfeehs:
2853 case Intrinsic::s390_vfeefs:
2854 Opcode = SystemZISD::VFEE_CC;
2855 CCValid = SystemZ::CCMASK_ANY;
2856 return true;
2857
2858 case Intrinsic::s390_vfeezbs:
2859 case Intrinsic::s390_vfeezhs:
2860 case Intrinsic::s390_vfeezfs:
2861 Opcode = SystemZISD::VFEEZ_CC;
2862 CCValid = SystemZ::CCMASK_ANY;
2863 return true;
2864
2865 case Intrinsic::s390_vfenebs:
2866 case Intrinsic::s390_vfenehs:
2867 case Intrinsic::s390_vfenefs:
2868 Opcode = SystemZISD::VFENE_CC;
2869 CCValid = SystemZ::CCMASK_ANY;
2870 return true;
2871
2872 case Intrinsic::s390_vfenezbs:
2873 case Intrinsic::s390_vfenezhs:
2874 case Intrinsic::s390_vfenezfs:
2875 Opcode = SystemZISD::VFENEZ_CC;
2876 CCValid = SystemZ::CCMASK_ANY;
2877 return true;
2878
2879 case Intrinsic::s390_vistrbs:
2880 case Intrinsic::s390_vistrhs:
2881 case Intrinsic::s390_vistrfs:
2882 Opcode = SystemZISD::VISTR_CC;
2884 return true;
2885
2886 case Intrinsic::s390_vstrcbs:
2887 case Intrinsic::s390_vstrchs:
2888 case Intrinsic::s390_vstrcfs:
2889 Opcode = SystemZISD::VSTRC_CC;
2890 CCValid = SystemZ::CCMASK_ANY;
2891 return true;
2892
2893 case Intrinsic::s390_vstrczbs:
2894 case Intrinsic::s390_vstrczhs:
2895 case Intrinsic::s390_vstrczfs:
2896 Opcode = SystemZISD::VSTRCZ_CC;
2897 CCValid = SystemZ::CCMASK_ANY;
2898 return true;
2899
2900 case Intrinsic::s390_vstrsb:
2901 case Intrinsic::s390_vstrsh:
2902 case Intrinsic::s390_vstrsf:
2903 Opcode = SystemZISD::VSTRS_CC;
2904 CCValid = SystemZ::CCMASK_ANY;
2905 return true;
2906
2907 case Intrinsic::s390_vstrszb:
2908 case Intrinsic::s390_vstrszh:
2909 case Intrinsic::s390_vstrszf:
2910 Opcode = SystemZISD::VSTRSZ_CC;
2911 CCValid = SystemZ::CCMASK_ANY;
2912 return true;
2913
2914 case Intrinsic::s390_vfcedbs:
2915 case Intrinsic::s390_vfcesbs:
2916 Opcode = SystemZISD::VFCMPES;
2917 CCValid = SystemZ::CCMASK_VCMP;
2918 return true;
2919
2920 case Intrinsic::s390_vfchdbs:
2921 case Intrinsic::s390_vfchsbs:
2922 Opcode = SystemZISD::VFCMPHS;
2923 CCValid = SystemZ::CCMASK_VCMP;
2924 return true;
2925
2926 case Intrinsic::s390_vfchedbs:
2927 case Intrinsic::s390_vfchesbs:
2928 Opcode = SystemZISD::VFCMPHES;
2929 CCValid = SystemZ::CCMASK_VCMP;
2930 return true;
2931
2932 case Intrinsic::s390_vftcidb:
2933 case Intrinsic::s390_vftcisb:
2934 Opcode = SystemZISD::VFTCI;
2935 CCValid = SystemZ::CCMASK_VCMP;
2936 return true;
2937
2938 case Intrinsic::s390_tdc:
2939 Opcode = SystemZISD::TDC;
2940 CCValid = SystemZ::CCMASK_TDC;
2941 return true;
2942
2943 default:
2944 return false;
2945 }
2946}
2947
2948// Emit an intrinsic with chain and an explicit CC register result.
2950 unsigned Opcode) {
2951 // Copy all operands except the intrinsic ID.
2952 unsigned NumOps = Op.getNumOperands();
2954 Ops.reserve(NumOps - 1);
2955 Ops.push_back(Op.getOperand(0));
2956 for (unsigned I = 2; I < NumOps; ++I)
2957 Ops.push_back(Op.getOperand(I));
2958
2959 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2960 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2961 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2962 SDValue OldChain = SDValue(Op.getNode(), 1);
2963 SDValue NewChain = SDValue(Intr.getNode(), 1);
2964 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2965 return Intr.getNode();
2966}
2967
2968// Emit an intrinsic with an explicit CC register result.
2970 unsigned Opcode) {
2971 // Copy all operands except the intrinsic ID.
2972 SDLoc DL(Op);
2973 unsigned NumOps = Op.getNumOperands();
2975 Ops.reserve(NumOps - 1);
2976 for (unsigned I = 1; I < NumOps; ++I) {
2977 SDValue CurrOper = Op.getOperand(I);
2978 if (CurrOper.getValueType() == MVT::f16) {
2979 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
2980 "Unhandled intrinsic with f16 operand.");
2981 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
2982 }
2983 Ops.push_back(CurrOper);
2984 }
2985
2986 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
2987 return Intr.getNode();
2988}
2989
2990// CC is a comparison that will be implemented using an integer or
2991// floating-point comparison. Return the condition code mask for
2992// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2993// unsigned comparisons and clear for signed ones. In the floating-point
2994// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2996#define CONV(X) \
2997 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2998 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2999 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
3000
3001 switch (CC) {
3002 default:
3003 llvm_unreachable("Invalid integer condition!");
3004
3005 CONV(EQ);
3006 CONV(NE);
3007 CONV(GT);
3008 CONV(GE);
3009 CONV(LT);
3010 CONV(LE);
3011
3012 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
3014 }
3015#undef CONV
3016}
3017
3018// If C can be converted to a comparison against zero, adjust the operands
3019// as necessary.
3020static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3021 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3022 return;
3023
3024 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
3025 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3026 return;
3027
3028 int64_t Value = ConstOp1->getSExtValue();
3029 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
3030 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
3031 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
3032 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
3033 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3034 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
3035 }
3036}
3037
3038// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
3039// adjust the operands as necessary.
3040static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
3041 Comparison &C) {
3042 // For us to make any changes, it must a comparison between a single-use
3043 // load and a constant.
3044 if (!C.Op0.hasOneUse() ||
3045 C.Op0.getOpcode() != ISD::LOAD ||
3046 C.Op1.getOpcode() != ISD::Constant)
3047 return;
3048
3049 // We must have an 8- or 16-bit load.
3050 auto *Load = cast<LoadSDNode>(C.Op0);
3051 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
3052 if ((NumBits != 8 && NumBits != 16) ||
3053 NumBits != Load->getMemoryVT().getStoreSizeInBits())
3054 return;
3055
3056 // The load must be an extending one and the constant must be within the
3057 // range of the unextended value.
3058 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
3059 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3060 return;
3061 uint64_t Value = ConstOp1->getZExtValue();
3062 uint64_t Mask = (1 << NumBits) - 1;
3063 if (Load->getExtensionType() == ISD::SEXTLOAD) {
3064 // Make sure that ConstOp1 is in range of C.Op0.
3065 int64_t SignedValue = ConstOp1->getSExtValue();
3066 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
3067 return;
3068 if (C.ICmpType != SystemZICMP::SignedOnly) {
3069 // Unsigned comparison between two sign-extended values is equivalent
3070 // to unsigned comparison between two zero-extended values.
3071 Value &= Mask;
3072 } else if (NumBits == 8) {
3073 // Try to treat the comparison as unsigned, so that we can use CLI.
3074 // Adjust CCMask and Value as necessary.
3075 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
3076 // Test whether the high bit of the byte is set.
3077 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
3078 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
3079 // Test whether the high bit of the byte is clear.
3080 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
3081 else
3082 // No instruction exists for this combination.
3083 return;
3084 C.ICmpType = SystemZICMP::UnsignedOnly;
3085 }
3086 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
3087 if (Value > Mask)
3088 return;
3089 // If the constant is in range, we can use any comparison.
3090 C.ICmpType = SystemZICMP::Any;
3091 } else
3092 return;
3093
3094 // Make sure that the first operand is an i32 of the right extension type.
3095 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
3098 if (C.Op0.getValueType() != MVT::i32 ||
3099 Load->getExtensionType() != ExtType) {
3100 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
3101 Load->getBasePtr(), Load->getPointerInfo(),
3102 Load->getMemoryVT(), Load->getAlign(),
3103 Load->getMemOperand()->getFlags());
3104 // Update the chain uses.
3105 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3106 }
3107
3108 // Make sure that the second operand is an i32 with the right value.
3109 if (C.Op1.getValueType() != MVT::i32 ||
3110 Value != ConstOp1->getZExtValue())
3111 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3112}
3113
3114// Return true if Op is either an unextended load, or a load suitable
3115// for integer register-memory comparisons of type ICmpType.
3116static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3117 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3118 if (Load) {
3119 // There are no instructions to compare a register with a memory byte.
3120 if (Load->getMemoryVT() == MVT::i8)
3121 return false;
3122 // Otherwise decide on extension type.
3123 switch (Load->getExtensionType()) {
3124 case ISD::NON_EXTLOAD:
3125 return true;
3126 case ISD::SEXTLOAD:
3127 return ICmpType != SystemZICMP::UnsignedOnly;
3128 case ISD::ZEXTLOAD:
3129 return ICmpType != SystemZICMP::SignedOnly;
3130 default:
3131 break;
3132 }
3133 }
3134 return false;
3135}
3136
3137// Return true if it is better to swap the operands of C.
3138static bool shouldSwapCmpOperands(const Comparison &C) {
3139 // If one side of the compare is a load of the stackguard reference value,
3140 // then that load should be Op1.
3141 if (C.Op0.isMachineOpcode() &&
3142 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3143 return true;
3144
3145 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3146 if (C.Op0.getValueType() == MVT::i128)
3147 return false;
3148 if (C.Op0.getValueType() == MVT::f128)
3149 return false;
3150
3151 // Always keep a floating-point constant second, since comparisons with
3152 // zero can use LOAD TEST and comparisons with other constants make a
3153 // natural memory operand.
3154 if (isa<ConstantFPSDNode>(C.Op1))
3155 return false;
3156
3157 // Never swap comparisons with zero since there are many ways to optimize
3158 // those later.
3159 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3160 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3161 return false;
3162
3163 // Also keep natural memory operands second if the loaded value is
3164 // only used here. Several comparisons have memory forms.
3165 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3166 return false;
3167
3168 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3169 // In that case we generally prefer the memory to be second.
3170 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3171 // The only exceptions are when the second operand is a constant and
3172 // we can use things like CHHSI.
3173 if (!ConstOp1)
3174 return true;
3175 // The unsigned memory-immediate instructions can handle 16-bit
3176 // unsigned integers.
3177 if (C.ICmpType != SystemZICMP::SignedOnly &&
3178 isUInt<16>(ConstOp1->getZExtValue()))
3179 return false;
3180 // The signed memory-immediate instructions can handle 16-bit
3181 // signed integers.
3182 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3183 isInt<16>(ConstOp1->getSExtValue()))
3184 return false;
3185 return true;
3186 }
3187
3188 // Try to promote the use of CGFR and CLGFR.
3189 unsigned Opcode0 = C.Op0.getOpcode();
3190 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3191 return true;
3192 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3193 return true;
3194 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3195 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3196 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3197 return true;
3198
3199 return false;
3200}
3201
3202// Check whether C tests for equality between X and Y and whether X - Y
3203// or Y - X is also computed. In that case it's better to compare the
3204// result of the subtraction against zero.
3206 Comparison &C) {
3207 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3208 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3209 for (SDNode *N : C.Op0->users()) {
3210 if (N->getOpcode() == ISD::SUB &&
3211 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3212 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3213 // Disable the nsw and nuw flags: the backend needs to handle
3214 // overflow as well during comparison elimination.
3215 N->dropFlags(SDNodeFlags::NoWrap);
3216 C.Op0 = SDValue(N, 0);
3217 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3218 return;
3219 }
3220 }
3221 }
3222}
3223
3224// Check whether C compares a floating-point value with zero and if that
3225// floating-point value is also negated. In this case we can use the
3226// negation to set CC, so avoiding separate LOAD AND TEST and
3227// LOAD (NEGATIVE/COMPLEMENT) instructions.
3228static void adjustForFNeg(Comparison &C) {
3229 // This optimization is invalid for strict comparisons, since FNEG
3230 // does not raise any exceptions.
3231 if (C.Chain)
3232 return;
3233 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3234 if (C1 && C1->isZero()) {
3235 for (SDNode *N : C.Op0->users()) {
3236 if (N->getOpcode() == ISD::FNEG) {
3237 C.Op0 = SDValue(N, 0);
3238 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3239 return;
3240 }
3241 }
3242 }
3243}
3244
3245// Check whether C compares (shl X, 32) with 0 and whether X is
3246// also sign-extended. In that case it is better to test the result
3247// of the sign extension using LTGFR.
3248//
3249// This case is important because InstCombine transforms a comparison
3250// with (sext (trunc X)) into a comparison with (shl X, 32).
3251static void adjustForLTGFR(Comparison &C) {
3252 // Check for a comparison between (shl X, 32) and 0.
3253 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3254 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3255 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3256 if (C1 && C1->getZExtValue() == 32) {
3257 SDValue ShlOp0 = C.Op0.getOperand(0);
3258 // See whether X has any SIGN_EXTEND_INREG uses.
3259 for (SDNode *N : ShlOp0->users()) {
3260 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3261 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3262 C.Op0 = SDValue(N, 0);
3263 return;
3264 }
3265 }
3266 }
3267 }
3268}
3269
3270// If C compares the truncation of an extending load, try to compare
3271// the untruncated value instead. This exposes more opportunities to
3272// reuse CC.
3273static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3274 Comparison &C) {
3275 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3276 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3277 C.Op1.getOpcode() == ISD::Constant &&
3278 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3279 C.Op1->getAsZExtVal() == 0) {
3280 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3281 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3282 C.Op0.getValueSizeInBits().getFixedValue()) {
3283 unsigned Type = L->getExtensionType();
3284 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3285 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3286 C.Op0 = C.Op0.getOperand(0);
3287 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3288 }
3289 }
3290 }
3291}
3292
3293// Adjust if a given Compare is a check of the stack guard against a stack
3294// guard instance on the stack. Specifically, this checks if:
3295// - The operands are a load of the stack guard, and a load from a stack slot
3296// - The original opcode is ICMP
3297// - ICMPType is compatible with unsigned comparison.
3299 Comparison &C) {
3300
3301 // Opcode must be ICMP.
3302 if (C.Opcode != SystemZISD::ICMP)
3303 return;
3304 // ICmpType must be Unsigned or Any.
3305 if (C.ICmpType == SystemZICMP::SignedOnly)
3306 return;
3307 // Op0 must be FrameIndex Load.
3308 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3309 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3310 return;
3311 // Op1 must be LOAD_STACK_GUARD.
3312 if (!C.Op1.isMachineOpcode() ||
3313 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3314 return;
3315
3316 // At this point we are sure that this is a proper CMP_STACKGUARD
3317 // case, update the opcode to reflect this.
3318 C.Opcode = SystemZISD::CMP_STACKGUARD;
3319 C.Op1 = SDValue();
3320}
3321
3322// Return true if shift operation N has an in-range constant shift value.
3323// Store it in ShiftVal if so.
3324static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3325 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3326 if (!Shift)
3327 return false;
3328
3329 uint64_t Amount = Shift->getZExtValue();
3330 if (Amount >= N.getValueSizeInBits())
3331 return false;
3332
3333 ShiftVal = Amount;
3334 return true;
3335}
3336
3337// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3338// instruction and whether the CC value is descriptive enough to handle
3339// a comparison of type Opcode between the AND result and CmpVal.
3340// CCMask says which comparison result is being tested and BitSize is
3341// the number of bits in the operands. If TEST UNDER MASK can be used,
3342// return the corresponding CC mask, otherwise return 0.
3343static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3344 uint64_t Mask, uint64_t CmpVal,
3345 unsigned ICmpType) {
3346 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3347
3348 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3349 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3350 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3351 return 0;
3352
3353 // Work out the masks for the lowest and highest bits.
3355 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3356
3357 // Signed ordered comparisons are effectively unsigned if the sign
3358 // bit is dropped.
3359 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3360
3361 // Check for equality comparisons with 0, or the equivalent.
3362 if (CmpVal == 0) {
3363 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3365 if (CCMask == SystemZ::CCMASK_CMP_NE)
3367 }
3368 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3369 if (CCMask == SystemZ::CCMASK_CMP_LT)
3371 if (CCMask == SystemZ::CCMASK_CMP_GE)
3373 }
3374 if (EffectivelyUnsigned && CmpVal < Low) {
3375 if (CCMask == SystemZ::CCMASK_CMP_LE)
3377 if (CCMask == SystemZ::CCMASK_CMP_GT)
3379 }
3380
3381 // Check for equality comparisons with the mask, or the equivalent.
3382 if (CmpVal == Mask) {
3383 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3385 if (CCMask == SystemZ::CCMASK_CMP_NE)
3387 }
3388 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3389 if (CCMask == SystemZ::CCMASK_CMP_GT)
3391 if (CCMask == SystemZ::CCMASK_CMP_LE)
3393 }
3394 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3395 if (CCMask == SystemZ::CCMASK_CMP_GE)
3397 if (CCMask == SystemZ::CCMASK_CMP_LT)
3399 }
3400
3401 // Check for ordered comparisons with the top bit.
3402 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3403 if (CCMask == SystemZ::CCMASK_CMP_LE)
3405 if (CCMask == SystemZ::CCMASK_CMP_GT)
3407 }
3408 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3409 if (CCMask == SystemZ::CCMASK_CMP_LT)
3411 if (CCMask == SystemZ::CCMASK_CMP_GE)
3413 }
3414
3415 // If there are just two bits, we can do equality checks for Low and High
3416 // as well.
3417 if (Mask == Low + High) {
3418 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3420 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3422 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3424 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3426 }
3427
3428 // Looks like we've exhausted our options.
3429 return 0;
3430}
3431
3432// See whether C can be implemented as a TEST UNDER MASK instruction.
3433// Update the arguments with the TM version if so.
3435 Comparison &C) {
3436 // Use VECTOR TEST UNDER MASK for i128 operations.
3437 if (C.Op0.getValueType() == MVT::i128) {
3438 // We can use VTM for EQ/NE comparisons of x & y against 0.
3439 if (C.Op0.getOpcode() == ISD::AND &&
3440 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3441 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3442 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3443 if (Mask && Mask->getAPIntValue() == 0) {
3444 C.Opcode = SystemZISD::VTM;
3445 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3446 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3447 C.CCValid = SystemZ::CCMASK_VCMP;
3448 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3449 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3450 else
3451 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3452 }
3453 }
3454 return;
3455 }
3456
3457 // Check that we have a comparison with a constant.
3458 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3459 if (!ConstOp1)
3460 return;
3461 uint64_t CmpVal = ConstOp1->getZExtValue();
3462
3463 // Check whether the nonconstant input is an AND with a constant mask.
3464 Comparison NewC(C);
3465 uint64_t MaskVal;
3466 ConstantSDNode *Mask = nullptr;
3467 if (C.Op0.getOpcode() == ISD::AND) {
3468 NewC.Op0 = C.Op0.getOperand(0);
3469 NewC.Op1 = C.Op0.getOperand(1);
3470 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3471 if (!Mask)
3472 return;
3473 MaskVal = Mask->getZExtValue();
3474 } else {
3475 // There is no instruction to compare with a 64-bit immediate
3476 // so use TMHH instead if possible. We need an unsigned ordered
3477 // comparison with an i64 immediate.
3478 if (NewC.Op0.getValueType() != MVT::i64 ||
3479 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3480 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3481 NewC.ICmpType == SystemZICMP::SignedOnly)
3482 return;
3483 // Convert LE and GT comparisons into LT and GE.
3484 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3485 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3486 if (CmpVal == uint64_t(-1))
3487 return;
3488 CmpVal += 1;
3489 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3490 }
3491 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3492 // be masked off without changing the result.
3493 MaskVal = -(CmpVal & -CmpVal);
3494 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3495 }
3496 if (!MaskVal)
3497 return;
3498
3499 // Check whether the combination of mask, comparison value and comparison
3500 // type are suitable.
3501 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3502 unsigned NewCCMask, ShiftVal;
3503 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3504 NewC.Op0.getOpcode() == ISD::SHL &&
3505 isSimpleShift(NewC.Op0, ShiftVal) &&
3506 (MaskVal >> ShiftVal != 0) &&
3507 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3508 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3509 MaskVal >> ShiftVal,
3510 CmpVal >> ShiftVal,
3511 SystemZICMP::Any))) {
3512 NewC.Op0 = NewC.Op0.getOperand(0);
3513 MaskVal >>= ShiftVal;
3514 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3515 NewC.Op0.getOpcode() == ISD::SRL &&
3516 isSimpleShift(NewC.Op0, ShiftVal) &&
3517 (MaskVal << ShiftVal != 0) &&
3518 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3519 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3520 MaskVal << ShiftVal,
3521 CmpVal << ShiftVal,
3523 NewC.Op0 = NewC.Op0.getOperand(0);
3524 MaskVal <<= ShiftVal;
3525 } else {
3526 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3527 NewC.ICmpType);
3528 if (!NewCCMask)
3529 return;
3530 }
3531
3532 // Go ahead and make the change.
3533 C.Opcode = SystemZISD::TM;
3534 C.Op0 = NewC.Op0;
3535 if (Mask && Mask->getZExtValue() == MaskVal)
3536 C.Op1 = SDValue(Mask, 0);
3537 else
3538 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3539 C.CCValid = SystemZ::CCMASK_TM;
3540 C.CCMask = NewCCMask;
3541}
3542
3543// Implement i128 comparison in vector registers.
3544static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3545 Comparison &C) {
3546 if (C.Opcode != SystemZISD::ICMP)
3547 return;
3548 if (C.Op0.getValueType() != MVT::i128)
3549 return;
3550
3551 // Recognize vector comparison reductions.
3552 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3553 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3554 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3555 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3556 bool CmpNull = isNullConstant(C.Op1);
3557 SDValue Src = peekThroughBitcasts(C.Op0);
3558 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3559 Src = Src.getOperand(0);
3560 CmpNull = !CmpNull;
3561 }
3562 unsigned Opcode = 0;
3563 if (Src.hasOneUse()) {
3564 switch (Src.getOpcode()) {
3565 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3566 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3567 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3568 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3569 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3570 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3571 default: break;
3572 }
3573 }
3574 if (Opcode) {
3575 C.Opcode = Opcode;
3576 C.Op0 = Src->getOperand(0);
3577 C.Op1 = Src->getOperand(1);
3578 C.CCValid = SystemZ::CCMASK_VCMP;
3580 if (!CmpEq)
3581 C.CCMask ^= C.CCValid;
3582 return;
3583 }
3584 }
3585
3586 // Everything below here is not useful if we have native i128 compares.
3587 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3588 return;
3589
3590 // (In-)Equality comparisons can be implemented via VCEQGS.
3591 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3592 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3593 C.Opcode = SystemZISD::VICMPES;
3594 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3595 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3596 C.CCValid = SystemZ::CCMASK_VCMP;
3597 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3598 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3599 else
3600 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3601 return;
3602 }
3603
3604 // Normalize other comparisons to GT.
3605 bool Swap = false, Invert = false;
3606 switch (C.CCMask) {
3607 case SystemZ::CCMASK_CMP_GT: break;
3608 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3609 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3610 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3611 default: llvm_unreachable("Invalid integer condition!");
3612 }
3613 if (Swap)
3614 std::swap(C.Op0, C.Op1);
3615
3616 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3617 C.Opcode = SystemZISD::UCMP128HI;
3618 else
3619 C.Opcode = SystemZISD::SCMP128HI;
3620 C.CCValid = SystemZ::CCMASK_ANY;
3621 C.CCMask = SystemZ::CCMASK_1;
3622
3623 if (Invert)
3624 C.CCMask ^= C.CCValid;
3625}
3626
3627// See whether the comparison argument contains a redundant AND
3628// and remove it if so. This sometimes happens due to the generic
3629// BRCOND expansion.
3631 Comparison &C) {
3632 if (C.Op0.getOpcode() != ISD::AND)
3633 return;
3634 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3635 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3636 return;
3637 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3638 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3639 return;
3640
3641 C.Op0 = C.Op0.getOperand(0);
3642}
3643
3644// Return a Comparison that tests the condition-code result of intrinsic
3645// node Call against constant integer CC using comparison code Cond.
3646// Opcode is the opcode of the SystemZISD operation for the intrinsic
3647// and CCValid is the set of possible condition-code results.
3648static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3649 SDValue Call, unsigned CCValid, uint64_t CC,
3651 Comparison C(Call, SDValue(), SDValue());
3652 C.Opcode = Opcode;
3653 C.CCValid = CCValid;
3654 if (Cond == ISD::SETEQ)
3655 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3656 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3657 else if (Cond == ISD::SETNE)
3658 // ...and the inverse of that.
3659 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3660 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3661 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3662 // always true for CC>3.
3663 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3664 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3665 // ...and the inverse of that.
3666 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3667 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3668 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3669 // always true for CC>3.
3670 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3671 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3672 // ...and the inverse of that.
3673 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3674 else
3675 llvm_unreachable("Unexpected integer comparison type");
3676 C.CCMask &= CCValid;
3677 return C;
3678}
3679
3680// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3681static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3682 ISD::CondCode Cond, const SDLoc &DL,
3683 SDValue Chain = SDValue(),
3684 bool IsSignaling = false) {
3685 if (CmpOp1.getOpcode() == ISD::Constant) {
3686 assert(!Chain);
3687 unsigned Opcode, CCValid;
3688 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3689 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3690 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3691 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3692 CmpOp1->getAsZExtVal(), Cond);
3693 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3694 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3695 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3696 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3697 CmpOp1->getAsZExtVal(), Cond);
3698 }
3699 Comparison C(CmpOp0, CmpOp1, Chain);
3700 C.CCMask = CCMaskForCondCode(Cond);
3701 if (C.Op0.getValueType().isFloatingPoint()) {
3702 C.CCValid = SystemZ::CCMASK_FCMP;
3703 if (!C.Chain)
3704 C.Opcode = SystemZISD::FCMP;
3705 else if (!IsSignaling)
3706 C.Opcode = SystemZISD::STRICT_FCMP;
3707 else
3708 C.Opcode = SystemZISD::STRICT_FCMPS;
3710 } else {
3711 assert(!C.Chain);
3712 C.CCValid = SystemZ::CCMASK_ICMP;
3713 C.Opcode = SystemZISD::ICMP;
3714 // Choose the type of comparison. Equality and inequality tests can
3715 // use either signed or unsigned comparisons. The choice also doesn't
3716 // matter if both sign bits are known to be clear. In those cases we
3717 // want to give the main isel code the freedom to choose whichever
3718 // form fits best.
3719 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3720 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3721 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3722 C.ICmpType = SystemZICMP::Any;
3723 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3724 C.ICmpType = SystemZICMP::UnsignedOnly;
3725 else
3726 C.ICmpType = SystemZICMP::SignedOnly;
3727 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3728 adjustForRedundantAnd(DAG, DL, C);
3729 adjustZeroCmp(DAG, DL, C);
3730 adjustSubwordCmp(DAG, DL, C);
3731 adjustForSubtraction(DAG, DL, C);
3733 adjustICmpTruncate(DAG, DL, C);
3734 }
3735
3736 if (shouldSwapCmpOperands(C)) {
3737 std::swap(C.Op0, C.Op1);
3738 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3739 }
3740
3742 adjustICmp128(DAG, DL, C);
3744 return C;
3745}
3746
3747// Emit the comparison instruction described by C.
3748static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3749 if (!C.Op1.getNode()) {
3750 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3751 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3752 SDNode *Node;
3753 switch (C.Op0.getOpcode()) {
3755 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3756 return SDValue(Node, 0);
3758 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3759 return SDValue(Node, Node->getNumValues() - 1);
3760 default:
3761 llvm_unreachable("Invalid comparison operands");
3762 }
3763 }
3764 if (C.Opcode == SystemZISD::ICMP)
3765 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3766 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3767 if (C.Opcode == SystemZISD::TM) {
3768 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3770 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3771 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3772 }
3773 if (C.Opcode == SystemZISD::VICMPES ||
3774 C.Opcode == SystemZISD::VICMPHS ||
3775 C.Opcode == SystemZISD::VICMPHLS ||
3776 C.Opcode == SystemZISD::VFCMPES ||
3777 C.Opcode == SystemZISD::VFCMPHS ||
3778 C.Opcode == SystemZISD::VFCMPHES) {
3779 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3780 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3781 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3782 return SDValue(Val.getNode(), 1);
3783 }
3784 if (C.Chain) {
3785 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3786 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3787 }
3788 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3789}
3790
3791// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3792// 64 bits. Extend is the extension type to use. Store the high part
3793// in Hi and the low part in Lo.
3794static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3795 SDValue Op0, SDValue Op1, SDValue &Hi,
3796 SDValue &Lo) {
3797 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3798 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3799 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3800 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3801 DAG.getConstant(32, DL, MVT::i64));
3802 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3803 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3804}
3805
3806// Lower a binary operation that produces two VT results, one in each
3807// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3808// and Opcode performs the GR128 operation. Store the even register result
3809// in Even and the odd register result in Odd.
3810static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3811 unsigned Opcode, SDValue Op0, SDValue Op1,
3812 SDValue &Even, SDValue &Odd) {
3813 SDValue Result = DAG.getNode(Opcode, DL, MVT::v2i64, Op0, Op1);
3814 bool Is32Bit = is32Bit(VT);
3815 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3816 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3817}
3818
3819// Return an i32 value that is 1 if the CC value produced by CCReg is
3820// in the mask CCMask and 0 otherwise. CC is known to have a value
3821// in CCValid, so other values can be ignored.
3822static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3823 unsigned CCValid, unsigned CCMask) {
3824 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3825 DAG.getConstant(0, DL, MVT::i32),
3826 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3827 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3828 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3829}
3830
3831// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3832// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3833// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3834// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3835// floating-point comparisons.
3838 switch (CC) {
3839 case ISD::SETOEQ:
3840 case ISD::SETEQ:
3841 switch (Mode) {
3842 case CmpMode::Int: return SystemZISD::VICMPE;
3843 case CmpMode::FP: return SystemZISD::VFCMPE;
3844 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3845 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3846 }
3847 llvm_unreachable("Bad mode");
3848
3849 case ISD::SETOGE:
3850 case ISD::SETGE:
3851 switch (Mode) {
3852 case CmpMode::Int: return 0;
3853 case CmpMode::FP: return SystemZISD::VFCMPHE;
3854 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3855 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3856 }
3857 llvm_unreachable("Bad mode");
3858
3859 case ISD::SETOGT:
3860 case ISD::SETGT:
3861 switch (Mode) {
3862 case CmpMode::Int: return SystemZISD::VICMPH;
3863 case CmpMode::FP: return SystemZISD::VFCMPH;
3864 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3865 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3866 }
3867 llvm_unreachable("Bad mode");
3868
3869 case ISD::SETUGT:
3870 switch (Mode) {
3871 case CmpMode::Int: return SystemZISD::VICMPHL;
3872 case CmpMode::FP: return 0;
3873 case CmpMode::StrictFP: return 0;
3874 case CmpMode::SignalingFP: return 0;
3875 }
3876 llvm_unreachable("Bad mode");
3877
3878 default:
3879 return 0;
3880 }
3881}
3882
3883// Return the SystemZISD vector comparison operation for CC or its inverse,
3884// or 0 if neither can be done directly. Indicate in Invert whether the
3885// result is for the inverse of CC. Mode is as above.
3887 bool &Invert) {
3888 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3889 Invert = false;
3890 return Opcode;
3891 }
3892
3893 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3894 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3895 Invert = true;
3896 return Opcode;
3897 }
3898
3899 return 0;
3900}
3901
3902// Return a v2f64 that contains the extended form of elements Start and Start+1
3903// of v4f32 value Op. If Chain is nonnull, return the strict form.
3904static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3905 SDValue Op, SDValue Chain) {
3906 int Mask[] = { Start, -1, Start + 1, -1 };
3907 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3908 if (Chain) {
3909 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3910 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3911 }
3912 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3913}
3914
3915// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3916// producing a result of type VT. If Chain is nonnull, return the strict form.
3917SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3918 const SDLoc &DL, EVT VT,
3919 SDValue CmpOp0,
3920 SDValue CmpOp1,
3921 SDValue Chain) const {
3922 // There is no hardware support for v4f32 (unless we have the vector
3923 // enhancements facility 1), so extend the vector into two v2f64s
3924 // and compare those.
3925 if (CmpOp0.getValueType() == MVT::v4f32 &&
3926 !Subtarget.hasVectorEnhancements1()) {
3927 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3928 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3929 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3930 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3931 if (Chain) {
3932 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3933 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3934 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3935 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3936 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3937 H1.getValue(1), L1.getValue(1),
3938 HRes.getValue(1), LRes.getValue(1) };
3939 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3940 SDValue Ops[2] = { Res, NewChain };
3941 return DAG.getMergeValues(Ops, DL);
3942 }
3943 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3944 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3945 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3946 }
3947 if (Chain) {
3948 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3949 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3950 }
3951 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3952}
3953
3954// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3955// an integer mask of type VT. If Chain is nonnull, we have a strict
3956// floating-point comparison. If in addition IsSignaling is true, we have
3957// a strict signaling floating-point comparison.
3958SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3959 const SDLoc &DL, EVT VT,
3961 SDValue CmpOp0,
3962 SDValue CmpOp1,
3963 SDValue Chain,
3964 bool IsSignaling) const {
3965 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3966 assert (!Chain || IsFP);
3967 assert (!IsSignaling || Chain);
3968 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3969 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3970 bool Invert = false;
3971 SDValue Cmp;
3972 switch (CC) {
3973 // Handle tests for order using (or (ogt y x) (oge x y)).
3974 case ISD::SETUO:
3975 Invert = true;
3976 [[fallthrough]];
3977 case ISD::SETO: {
3978 assert(IsFP && "Unexpected integer comparison");
3979 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3980 DL, VT, CmpOp1, CmpOp0, Chain);
3981 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3982 DL, VT, CmpOp0, CmpOp1, Chain);
3983 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3984 if (Chain)
3985 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3986 LT.getValue(1), GE.getValue(1));
3987 break;
3988 }
3989
3990 // Handle <> tests using (or (ogt y x) (ogt x y)).
3991 case ISD::SETUEQ:
3992 Invert = true;
3993 [[fallthrough]];
3994 case ISD::SETONE: {
3995 assert(IsFP && "Unexpected integer comparison");
3996 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3997 DL, VT, CmpOp1, CmpOp0, Chain);
3998 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3999 DL, VT, CmpOp0, CmpOp1, Chain);
4000 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
4001 if (Chain)
4002 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4003 LT.getValue(1), GT.getValue(1));
4004 break;
4005 }
4006
4007 // Otherwise a single comparison is enough. It doesn't really
4008 // matter whether we try the inversion or the swap first, since
4009 // there are no cases where both work.
4010 default:
4011 // Optimize sign-bit comparisons to signed compares.
4012 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
4014 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4015 APInt Mask;
4016 if (CmpOp0.getOpcode() == ISD::AND
4017 && ISD::isConstantSplatVector(CmpOp0.getOperand(1).getNode(), Mask)
4018 && Mask == APInt::getSignMask(EltSize)) {
4020 CmpOp0 = CmpOp0.getOperand(0);
4021 }
4022 }
4023 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4024 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
4025 else {
4027 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4028 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
4029 else
4030 llvm_unreachable("Unhandled comparison");
4031 }
4032 if (Chain)
4033 Chain = Cmp.getValue(1);
4034 break;
4035 }
4036 if (Invert) {
4037 SDValue Mask =
4038 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
4039 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
4040 }
4041 if (Chain && Chain.getNode() != Cmp.getNode()) {
4042 SDValue Ops[2] = { Cmp, Chain };
4043 Cmp = DAG.getMergeValues(Ops, DL);
4044 }
4045 return Cmp;
4046}
4047
4048SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
4049 SelectionDAG &DAG) const {
4050 SDValue CmpOp0 = Op.getOperand(0);
4051 SDValue CmpOp1 = Op.getOperand(1);
4052 ISD::CondCode CC = Op.getOperandCondCode(2);
4053 SDLoc DL(Op);
4054 EVT VT = Op.getValueType();
4055 if (VT.isVector())
4056 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
4057
4058 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4059 SDValue CCReg = emitCmp(DAG, DL, C);
4060 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4061}
4062
4063SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
4064 SelectionDAG &DAG,
4065 bool IsSignaling) const {
4066 SDValue Chain = Op.getOperand(0);
4067 SDValue CmpOp0 = Op.getOperand(1);
4068 SDValue CmpOp1 = Op.getOperand(2);
4069 ISD::CondCode CC = Op.getOperandCondCode(3);
4070 SDLoc DL(Op);
4071 EVT VT = Op.getNode()->getValueType(0);
4072 if (VT.isVector()) {
4073 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
4074 Chain, IsSignaling);
4075 return Res.getValue(Op.getResNo());
4076 }
4077
4078 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
4079 SDValue CCReg = emitCmp(DAG, DL, C);
4080 CCReg->setFlags(Op->getFlags());
4081 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4082 SDValue Ops[2] = { Result, CCReg.getValue(1) };
4083 return DAG.getMergeValues(Ops, DL);
4084}
4085
4086SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4087 ISD::CondCode CC = Op.getOperandCondCode(1);
4088 SDValue CmpOp0 = Op.getOperand(2);
4089 SDValue CmpOp1 = Op.getOperand(3);
4090 SDValue Dest = Op.getOperand(4);
4091 SDLoc DL(Op);
4092
4093 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4094 SDValue CCReg = emitCmp(DAG, DL, C);
4095 return DAG.getNode(
4096 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
4097 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4098 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
4099}
4100
4101// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
4102// allowing Pos and Neg to be wider than CmpOp.
4103static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4104 return (Neg.getOpcode() == ISD::SUB &&
4105 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4106 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4107 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4108 Pos.getOperand(0) == CmpOp)));
4109}
4110
4111// Return the absolute or negative absolute of Op; IsNegative decides which.
4113 bool IsNegative) {
4114 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4115 if (IsNegative)
4116 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4117 DAG.getConstant(0, DL, Op.getValueType()), Op);
4118 return Op;
4119}
4120
4122 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4123 EVT VT = MVT::i128;
4124 unsigned Op;
4125
4126 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4127 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4128 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4129 std::swap(TrueOp, FalseOp);
4130 C.CCMask ^= C.CCValid;
4131 }
4132 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4133 std::swap(C.Op0, C.Op1);
4134 C.CCMask = SystemZ::CCMASK_CMP_GT;
4135 }
4136 switch (C.CCMask) {
4138 Op = SystemZISD::VICMPE;
4139 break;
4141 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4142 Op = SystemZISD::VICMPHL;
4143 else
4144 Op = SystemZISD::VICMPH;
4145 break;
4146 default:
4147 llvm_unreachable("Unhandled comparison");
4148 break;
4149 }
4150
4151 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4152 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4153 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4154 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4155}
4156
4157SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4158 SelectionDAG &DAG) const {
4159 SDValue CmpOp0 = Op.getOperand(0);
4160 SDValue CmpOp1 = Op.getOperand(1);
4161 SDValue TrueOp = Op.getOperand(2);
4162 SDValue FalseOp = Op.getOperand(3);
4163 ISD::CondCode CC = Op.getOperandCondCode(4);
4164 SDLoc DL(Op);
4165
4166 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4167 // legalizer, as it will be handled according to the type of the resulting
4168 // value. Extend them here if needed.
4169 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4170 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4171 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4172 }
4173
4174 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4175
4176 // Check for absolute and negative-absolute selections, including those
4177 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4178 // This check supplements the one in DAGCombiner.
4179 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4180 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4181 C.Op1.getOpcode() == ISD::Constant &&
4182 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4183 C.Op1->getAsZExtVal() == 0) {
4184 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4185 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4186 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4187 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4188 }
4189
4190 if (Subtarget.hasVectorEnhancements3() &&
4191 C.Opcode == SystemZISD::ICMP &&
4192 C.Op0.getValueType() == MVT::i128 &&
4193 TrueOp.getValueType() == MVT::i128) {
4194 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4195 }
4196
4197 SDValue CCReg = emitCmp(DAG, DL, C);
4198 SDValue Ops[] = {TrueOp, FalseOp,
4199 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4200 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4201
4202 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4203}
4204
4205SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4206 SelectionDAG &DAG) const {
4207 SDLoc DL(Node);
4208 const GlobalValue *GV = Node->getGlobal();
4209 int64_t Offset = Node->getOffset();
4210 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4212
4214 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4215 if (isInt<32>(Offset)) {
4216 // Assign anchors at 1<<12 byte boundaries.
4217 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4218 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4219 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4220
4221 // The offset can be folded into the address if it is aligned to a
4222 // halfword.
4223 Offset -= Anchor;
4224 if (Offset != 0 && (Offset & 1) == 0) {
4225 SDValue Full =
4226 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4227 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4228 Offset = 0;
4229 }
4230 } else {
4231 // Conservatively load a constant offset greater than 32 bits into a
4232 // register below.
4233 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4234 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4235 }
4236 } else if (Subtarget.isTargetELF()) {
4237 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4238 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4239 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4241 } else if (Subtarget.isTargetzOS()) {
4242 Result = getADAEntry(DAG, GV, DL, PtrVT);
4243 } else
4244 llvm_unreachable("Unexpected Subtarget");
4245
4246 // If there was a non-zero offset that we didn't fold, create an explicit
4247 // addition for it.
4248 if (Offset != 0)
4249 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4250 DAG.getSignedConstant(Offset, DL, PtrVT));
4251
4252 return Result;
4253}
4254
4255SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4256 SelectionDAG &DAG,
4257 unsigned Opcode,
4258 SDValue GOTOffset) const {
4259 SDLoc DL(Node);
4260 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4261 SDValue Chain = DAG.getEntryNode();
4262 SDValue Glue;
4263
4266 report_fatal_error("In GHC calling convention TLS is not supported");
4267
4268 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4269 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4270 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4271 Glue = Chain.getValue(1);
4272 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4273 Glue = Chain.getValue(1);
4274
4275 // The first call operand is the chain and the second is the TLS symbol.
4277 Ops.push_back(Chain);
4278 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4279 Node->getValueType(0),
4280 0, 0));
4281
4282 // Add argument registers to the end of the list so that they are
4283 // known live into the call.
4284 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4285 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4286
4287 // Add a register mask operand representing the call-preserved registers.
4288 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4289 const uint32_t *Mask =
4290 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4291 assert(Mask && "Missing call preserved mask for calling convention");
4292 Ops.push_back(DAG.getRegisterMask(Mask));
4293
4294 // Glue the call to the argument copies.
4295 Ops.push_back(Glue);
4296
4297 // Emit the call.
4298 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4299 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4300 Glue = Chain.getValue(1);
4301
4302 // Copy the return value from %r2.
4303 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4304}
4305
4306SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4307 SelectionDAG &DAG) const {
4308 SDValue Chain = DAG.getEntryNode();
4309 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4310
4311 // The high part of the thread pointer is in access register 0.
4312 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4313 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4314
4315 // The low part of the thread pointer is in access register 1.
4316 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4317 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4318
4319 // Merge them into a single 64-bit address.
4320 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4321 DAG.getConstant(32, DL, PtrVT));
4322 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4323}
4324
4325SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4326 SelectionDAG &DAG) const {
4327 if (DAG.getTarget().useEmulatedTLS())
4328 return LowerToTLSEmulatedModel(Node, DAG);
4329 SDLoc DL(Node);
4330 const GlobalValue *GV = Node->getGlobal();
4331 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4332 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4333
4336 report_fatal_error("In GHC calling convention TLS is not supported");
4337
4338 SDValue TP = lowerThreadPointer(DL, DAG);
4339
4340 // Get the offset of GA from the thread pointer, based on the TLS model.
4342 switch (model) {
4344 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4345 SystemZConstantPoolValue *CPV =
4347
4348 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4349 Offset = DAG.getLoad(
4350 PtrVT, DL, DAG.getEntryNode(), Offset,
4352
4353 // Call __tls_get_offset to retrieve the offset.
4354 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4355 break;
4356 }
4357
4359 // Load the GOT offset of the module ID.
4360 SystemZConstantPoolValue *CPV =
4362
4363 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4364 Offset = DAG.getLoad(
4365 PtrVT, DL, DAG.getEntryNode(), Offset,
4367
4368 // Call __tls_get_offset to retrieve the module base offset.
4369 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4370
4371 // Note: The SystemZLDCleanupPass will remove redundant computations
4372 // of the module base offset. Count total number of local-dynamic
4373 // accesses to trigger execution of that pass.
4374 SystemZMachineFunctionInfo* MFI =
4375 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4377
4378 // Add the per-symbol offset.
4380
4381 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4382 DTPOffset = DAG.getLoad(
4383 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4385
4386 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4387 break;
4388 }
4389
4390 case TLSModel::InitialExec: {
4391 // Load the offset from the GOT.
4392 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4394 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4395 Offset =
4396 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4398 break;
4399 }
4400
4401 case TLSModel::LocalExec: {
4402 // Force the offset into the constant pool and load it from there.
4403 SystemZConstantPoolValue *CPV =
4405
4406 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4407 Offset = DAG.getLoad(
4408 PtrVT, DL, DAG.getEntryNode(), Offset,
4410 break;
4411 }
4412 }
4413
4414 // Add the base and offset together.
4415 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4416}
4417
4418SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4419 SelectionDAG &DAG) const {
4420 SDLoc DL(Node);
4421 const BlockAddress *BA = Node->getBlockAddress();
4422 int64_t Offset = Node->getOffset();
4423 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4424
4425 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4426 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4427 return Result;
4428}
4429
4430SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4431 SelectionDAG &DAG) const {
4432 SDLoc DL(JT);
4433 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4434 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4435
4436 // Use LARL to load the address of the table.
4437 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4438}
4439
4440SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4441 SelectionDAG &DAG) const {
4442 SDLoc DL(CP);
4443 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4444
4447 Result =
4448 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4449 else
4450 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4451 CP->getOffset());
4452
4453 // Use LARL to load the address of the constant pool entry.
4454 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4455}
4456
4457SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4458 SelectionDAG &DAG) const {
4459 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4461 MachineFrameInfo &MFI = MF.getFrameInfo();
4462 MFI.setFrameAddressIsTaken(true);
4463
4464 SDLoc DL(Op);
4465 unsigned Depth = Op.getConstantOperandVal(0);
4466 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4467
4468 // By definition, the frame address is the address of the back chain. (In
4469 // the case of packed stack without backchain, return the address where the
4470 // backchain would have been stored. This will either be an unused space or
4471 // contain a saved register).
4472 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4473 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4474
4475 if (Depth > 0) {
4476 // FIXME The frontend should detect this case.
4477 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4478 report_fatal_error("Unsupported stack frame traversal count");
4479
4480 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4481 while (Depth--) {
4482 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4483 MachinePointerInfo());
4484 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4485 }
4486 }
4487
4488 return BackChain;
4489}
4490
4491SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4492 SelectionDAG &DAG) const {
4494 MachineFrameInfo &MFI = MF.getFrameInfo();
4495 MFI.setReturnAddressIsTaken(true);
4496
4497 SDLoc DL(Op);
4498 unsigned Depth = Op.getConstantOperandVal(0);
4499 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4500
4501 if (Depth > 0) {
4502 // FIXME The frontend should detect this case.
4503 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4504 report_fatal_error("Unsupported stack frame traversal count");
4505
4506 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4507 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4508 int Offset = TFL->getReturnAddressOffset(MF);
4509 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4510 DAG.getSignedConstant(Offset, DL, PtrVT));
4511 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4512 MachinePointerInfo());
4513 }
4514
4515 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4516 // implicit live-in.
4517 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4519 &SystemZ::GR64BitRegClass);
4520 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4521}
4522
4523SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4524 SelectionDAG &DAG) const {
4525 SDLoc DL(Op);
4526 SDValue In = Op.getOperand(0);
4527 EVT InVT = In.getValueType();
4528 EVT ResVT = Op.getValueType();
4529
4530 // Convert loads directly. This is normally done by DAGCombiner,
4531 // but we need this case for bitcasts that are created during lowering
4532 // and which are then lowered themselves.
4533 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4534 if (ISD::isNormalLoad(LoadN)) {
4535 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4536 LoadN->getBasePtr(), LoadN->getMemOperand());
4537 // Update the chain uses.
4538 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4539 return NewLoad;
4540 }
4541
4542 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4543 SDValue In64;
4544 if (Subtarget.hasHighWord()) {
4545 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4546 MVT::i64);
4547 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4548 MVT::i64, SDValue(U64, 0), In);
4549 } else {
4550 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4551 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4552 DAG.getConstant(32, DL, MVT::i64));
4553 }
4554 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4555 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4556 DL, MVT::f32, Out64);
4557 }
4558 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4559 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4560 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4561 MVT::f64, SDValue(U64, 0), In);
4562 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4563 if (Subtarget.hasHighWord())
4564 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4565 MVT::i32, Out64);
4566 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4567 DAG.getConstant(32, DL, MVT::i64));
4568 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4569 }
4570 llvm_unreachable("Unexpected bitcast combination");
4571}
4572
4573SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4574 SelectionDAG &DAG) const {
4575
4576 if (Subtarget.isTargetXPLINK64())
4577 return lowerVASTART_XPLINK(Op, DAG);
4578 else
4579 return lowerVASTART_ELF(Op, DAG);
4580}
4581
4582SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4583 SelectionDAG &DAG) const {
4585 SystemZMachineFunctionInfo *FuncInfo =
4586 MF.getInfo<SystemZMachineFunctionInfo>();
4587
4588 SDLoc DL(Op);
4589
4590 // vastart just stores the address of the VarArgsFrameIndex slot into the
4591 // memory location argument.
4592 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4593 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4594 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4595 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4596 MachinePointerInfo(SV));
4597}
4598
4599SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4600 SelectionDAG &DAG) const {
4602 SystemZMachineFunctionInfo *FuncInfo =
4603 MF.getInfo<SystemZMachineFunctionInfo>();
4604 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4605
4606 SDValue Chain = Op.getOperand(0);
4607 SDValue Addr = Op.getOperand(1);
4608 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4609 SDLoc DL(Op);
4610
4611 // The initial values of each field.
4612 const unsigned NumFields = 4;
4613 SDValue Fields[NumFields] = {
4614 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4615 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4616 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4617 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4618 };
4619
4620 // Store each field into its respective slot.
4621 SDValue MemOps[NumFields];
4622 unsigned Offset = 0;
4623 for (unsigned I = 0; I < NumFields; ++I) {
4624 SDValue FieldAddr = Addr;
4625 if (Offset != 0)
4626 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4628 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4629 MachinePointerInfo(SV, Offset));
4630 Offset += 8;
4631 }
4632 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4633}
4634
4635SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4636 SelectionDAG &DAG) const {
4637 SDValue Chain = Op.getOperand(0);
4638 SDValue DstPtr = Op.getOperand(1);
4639 SDValue SrcPtr = Op.getOperand(2);
4640 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4641 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4642 SDLoc DL(Op);
4643
4644 uint32_t Sz =
4645 Subtarget.isTargetXPLINK64() ? DAG.getDataLayout().getPointerSize(0) : 32;
4646 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4647 Align(8), Align(8), /*isVolatile*/ false,
4648 /*AlwaysInline*/ false,
4649 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4650 MachinePointerInfo(SrcSV));
4651}
4652
4653SDValue
4654SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4655 SelectionDAG &DAG) const {
4656 if (Subtarget.isTargetXPLINK64())
4657 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4658 else
4659 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4660}
4661
4662SDValue
4663SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4664 SelectionDAG &DAG) const {
4665 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4667 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4668 SDValue Chain = Op.getOperand(0);
4669 SDValue Size = Op.getOperand(1);
4670 SDValue Align = Op.getOperand(2);
4671 SDLoc DL(Op);
4672
4673 // If user has set the no alignment function attribute, ignore
4674 // alloca alignments.
4675 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4676
4677 uint64_t StackAlign = TFI->getStackAlignment();
4678 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4679 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4680
4681 SDValue NeededSpace = Size;
4682
4683 // Add extra space for alignment if needed.
4684 EVT PtrVT = getPointerTy(MF.getDataLayout());
4685 if (ExtraAlignSpace)
4686 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4687 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4688
4689 bool IsSigned = false;
4690 bool DoesNotReturn = false;
4691 bool IsReturnValueUsed = false;
4692 EVT VT = Op.getValueType();
4693 SDValue AllocaCall =
4694 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4695 CallingConv::C, IsSigned, DL, DoesNotReturn,
4696 IsReturnValueUsed)
4697 .first;
4698
4699 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4700 // to end of call in order to ensure it isn't broken up from the call
4701 // sequence.
4702 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4703 Register SPReg = Regs.getStackPointerRegister();
4704 Chain = AllocaCall.getValue(1);
4705 SDValue Glue = AllocaCall.getValue(2);
4706 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4707 Chain = NewSPRegNode.getValue(1);
4708
4709 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4710 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4711 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4712
4713 // Dynamically realign if needed.
4714 if (ExtraAlignSpace) {
4715 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4716 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4717 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4718 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4719 }
4720
4721 SDValue Ops[2] = {Result, Chain};
4722 return DAG.getMergeValues(Ops, DL);
4723}
4724
4725SDValue
4726SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4727 SelectionDAG &DAG) const {
4728 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4730 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4731 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4732
4733 SDValue Chain = Op.getOperand(0);
4734 SDValue Size = Op.getOperand(1);
4735 SDValue Align = Op.getOperand(2);
4736 SDLoc DL(Op);
4737
4738 // If user has set the no alignment function attribute, ignore
4739 // alloca alignments.
4740 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4741
4742 uint64_t StackAlign = TFI->getStackAlignment();
4743 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4744 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4745
4747 SDValue NeededSpace = Size;
4748
4749 // Get a reference to the stack pointer.
4750 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4751
4752 // If we need a backchain, save it now.
4753 SDValue Backchain;
4754 if (StoreBackchain)
4755 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4756 MachinePointerInfo());
4757
4758 // Add extra space for alignment if needed.
4759 if (ExtraAlignSpace)
4760 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4761 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4762
4763 // Get the new stack pointer value.
4764 SDValue NewSP;
4765 if (hasInlineStackProbe(MF)) {
4766 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4767 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4768 Chain = NewSP.getValue(1);
4769 }
4770 else {
4771 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4772 // Copy the new stack pointer back.
4773 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4774 }
4775
4776 // The allocated data lives above the 160 bytes allocated for the standard
4777 // frame, plus any outgoing stack arguments. We don't know how much that
4778 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4779 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4780 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4781
4782 // Dynamically realign if needed.
4783 if (RequiredAlign > StackAlign) {
4784 Result =
4785 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4786 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4787 Result =
4788 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4789 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4790 }
4791
4792 if (StoreBackchain)
4793 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4794 MachinePointerInfo());
4795
4796 SDValue Ops[2] = { Result, Chain };
4797 return DAG.getMergeValues(Ops, DL);
4798}
4799
4800SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4801 SDValue Op, SelectionDAG &DAG) const {
4802 SDLoc DL(Op);
4803
4804 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4805}
4806
4807SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4808 SelectionDAG &DAG,
4809 unsigned Opcode) const {
4810 EVT VT = Op.getValueType();
4811 SDLoc DL(Op);
4812 SDValue Even, Odd;
4813
4814 // This custom expander is only used on z17 and later for 64-bit types.
4815 assert(!is32Bit(VT));
4816 assert(Subtarget.hasMiscellaneousExtensions2());
4817
4818 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4819 // the high result in the even register. Return the latter.
4820 lowerGR128Binary(DAG, DL, VT, Opcode,
4821 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4822 return Even;
4823}
4824
4825SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4826 SelectionDAG &DAG) const {
4827 EVT VT = Op.getValueType();
4828 SDLoc DL(Op);
4829 SDValue Ops[2];
4830 if (is32Bit(VT))
4831 // Just do a normal 64-bit multiplication and extract the results.
4832 // We define this so that it can be used for constant division.
4833 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4834 Op.getOperand(1), Ops[1], Ops[0]);
4835 else if (Subtarget.hasMiscellaneousExtensions2())
4836 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4837 // the high result in the even register. ISD::SMUL_LOHI is defined to
4838 // return the low half first, so the results are in reverse order.
4839 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4840 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4841 else {
4842 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4843 //
4844 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4845 //
4846 // but using the fact that the upper halves are either all zeros
4847 // or all ones:
4848 //
4849 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4850 //
4851 // and grouping the right terms together since they are quicker than the
4852 // multiplication:
4853 //
4854 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4855 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4856 SDValue LL = Op.getOperand(0);
4857 SDValue RL = Op.getOperand(1);
4858 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4859 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4860 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4861 // the high result in the even register. ISD::SMUL_LOHI is defined to
4862 // return the low half first, so the results are in reverse order.
4863 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4864 LL, RL, Ops[1], Ops[0]);
4865 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4866 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4867 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4868 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4869 }
4870 return DAG.getMergeValues(Ops, DL);
4871}
4872
4873SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4874 SelectionDAG &DAG) const {
4875 EVT VT = Op.getValueType();
4876 SDLoc DL(Op);
4877 SDValue Ops[2];
4878 if (is32Bit(VT))
4879 // Just do a normal 64-bit multiplication and extract the results.
4880 // We define this so that it can be used for constant division.
4881 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4882 Op.getOperand(1), Ops[1], Ops[0]);
4883 else
4884 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4885 // the high result in the even register. ISD::UMUL_LOHI is defined to
4886 // return the low half first, so the results are in reverse order.
4887 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4888 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4889 return DAG.getMergeValues(Ops, DL);
4890}
4891
4892SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4893 SelectionDAG &DAG) const {
4894 SDValue Op0 = Op.getOperand(0);
4895 SDValue Op1 = Op.getOperand(1);
4896 EVT VT = Op.getValueType();
4897 SDLoc DL(Op);
4898
4899 // We use DSGF for 32-bit division. This means the first operand must
4900 // always be 64-bit, and the second operand should be 32-bit whenever
4901 // that is possible, to improve performance.
4902 if (is32Bit(VT))
4903 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4904 else if (DAG.ComputeNumSignBits(Op1) > 32)
4905 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4906
4907 // DSG(F) returns the remainder in the even register and the
4908 // quotient in the odd register.
4909 SDValue Ops[2];
4910 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4911 return DAG.getMergeValues(Ops, DL);
4912}
4913
4914SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4915 SelectionDAG &DAG) const {
4916 EVT VT = Op.getValueType();
4917 SDLoc DL(Op);
4918
4919 // DL(G) returns the remainder in the even register and the
4920 // quotient in the odd register.
4921 SDValue Ops[2];
4922 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4923 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4924 return DAG.getMergeValues(Ops, DL);
4925}
4926
4927SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4928 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4929
4930 // Get the known-zero masks for each operand.
4931 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4932 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4933 DAG.computeKnownBits(Ops[1])};
4934
4935 // See if the upper 32 bits of one operand and the lower 32 bits of the
4936 // other are known zero. They are the low and high operands respectively.
4937 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4938 Known[1].Zero.getZExtValue() };
4939 unsigned High, Low;
4940 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4941 High = 1, Low = 0;
4942 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4943 High = 0, Low = 1;
4944 else
4945 return Op;
4946
4947 SDValue LowOp = Ops[Low];
4948 SDValue HighOp = Ops[High];
4949
4950 // If the high part is a constant, we're better off using IILH.
4951 if (HighOp.getOpcode() == ISD::Constant)
4952 return Op;
4953
4954 // If the low part is a constant that is outside the range of LHI,
4955 // then we're better off using IILF.
4956 if (LowOp.getOpcode() == ISD::Constant) {
4957 int64_t Value = int32_t(LowOp->getAsZExtVal());
4958 if (!isInt<16>(Value))
4959 return Op;
4960 }
4961
4962 // Check whether the high part is an AND that doesn't change the
4963 // high 32 bits and just masks out low bits. We can skip it if so.
4964 if (HighOp.getOpcode() == ISD::AND &&
4965 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4966 SDValue HighOp0 = HighOp.getOperand(0);
4968 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
4969 HighOp = HighOp0;
4970 }
4971
4972 // Take advantage of the fact that all GR32 operations only change the
4973 // low 32 bits by truncating Low to an i32 and inserting it directly
4974 // using a subreg. The interesting cases are those where the truncation
4975 // can be folded.
4976 SDLoc DL(Op);
4977 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
4978 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
4979 MVT::i64, HighOp, Low32);
4980}
4981
4982// Lower SADDO/SSUBO/UADDO/USUBO nodes.
4983SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
4984 SelectionDAG &DAG) const {
4985 SDNode *N = Op.getNode();
4986 SDValue LHS = N->getOperand(0);
4987 SDValue RHS = N->getOperand(1);
4988 SDLoc DL(N);
4989
4990 if (N->getValueType(0) == MVT::i128) {
4991 unsigned BaseOp = 0;
4992 unsigned FlagOp = 0;
4993 bool IsBorrow = false;
4994 switch (Op.getOpcode()) {
4995 default: llvm_unreachable("Unknown instruction!");
4996 case ISD::UADDO:
4997 BaseOp = ISD::ADD;
4998 FlagOp = SystemZISD::VACC;
4999 break;
5000 case ISD::USUBO:
5001 BaseOp = ISD::SUB;
5002 FlagOp = SystemZISD::VSCBI;
5003 IsBorrow = true;
5004 break;
5005 }
5006 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
5007 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
5008 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5009 DAG.getValueType(MVT::i1));
5010 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5011 if (IsBorrow)
5012 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5013 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5014 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5015 }
5016
5017 unsigned BaseOp = 0;
5018 unsigned CCValid = 0;
5019 unsigned CCMask = 0;
5020
5021 switch (Op.getOpcode()) {
5022 default: llvm_unreachable("Unknown instruction!");
5023 case ISD::SADDO:
5024 BaseOp = SystemZISD::SADDO;
5025 CCValid = SystemZ::CCMASK_ARITH;
5027 break;
5028 case ISD::SSUBO:
5029 BaseOp = SystemZISD::SSUBO;
5030 CCValid = SystemZ::CCMASK_ARITH;
5032 break;
5033 case ISD::UADDO:
5034 BaseOp = SystemZISD::UADDO;
5035 CCValid = SystemZ::CCMASK_LOGICAL;
5037 break;
5038 case ISD::USUBO:
5039 BaseOp = SystemZISD::USUBO;
5040 CCValid = SystemZ::CCMASK_LOGICAL;
5042 break;
5043 }
5044
5045 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
5046 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
5047
5048 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5049 if (N->getValueType(1) == MVT::i1)
5050 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5051
5052 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5053}
5054
5055static bool isAddCarryChain(SDValue Carry) {
5056 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
5057 Carry->getValueType(0) != MVT::i128)
5058 Carry = Carry.getOperand(2);
5059 return Carry.getOpcode() == ISD::UADDO &&
5060 Carry->getValueType(0) != MVT::i128;
5061}
5062
5063static bool isSubBorrowChain(SDValue Carry) {
5064 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
5065 Carry->getValueType(0) != MVT::i128)
5066 Carry = Carry.getOperand(2);
5067 return Carry.getOpcode() == ISD::USUBO &&
5068 Carry->getValueType(0) != MVT::i128;
5069}
5070
5071// Lower UADDO_CARRY/USUBO_CARRY nodes.
5072SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
5073 SelectionDAG &DAG) const {
5074
5075 SDNode *N = Op.getNode();
5076 MVT VT = N->getSimpleValueType(0);
5077
5078 // Let legalize expand this if it isn't a legal type yet.
5079 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5080 return SDValue();
5081
5082 SDValue LHS = N->getOperand(0);
5083 SDValue RHS = N->getOperand(1);
5084 SDValue Carry = Op.getOperand(2);
5085 SDLoc DL(N);
5086
5087 if (VT == MVT::i128) {
5088 unsigned BaseOp = 0;
5089 unsigned FlagOp = 0;
5090 bool IsBorrow = false;
5091 switch (Op.getOpcode()) {
5092 default: llvm_unreachable("Unknown instruction!");
5093 case ISD::UADDO_CARRY:
5094 BaseOp = SystemZISD::VAC;
5095 FlagOp = SystemZISD::VACCC;
5096 break;
5097 case ISD::USUBO_CARRY:
5098 BaseOp = SystemZISD::VSBI;
5099 FlagOp = SystemZISD::VSBCBI;
5100 IsBorrow = true;
5101 break;
5102 }
5103 if (IsBorrow)
5104 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5105 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5106 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5107 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5108 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5109 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5110 DAG.getValueType(MVT::i1));
5111 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5112 if (IsBorrow)
5113 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5114 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5115 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5116 }
5117
5118 unsigned BaseOp = 0;
5119 unsigned CCValid = 0;
5120 unsigned CCMask = 0;
5121
5122 switch (Op.getOpcode()) {
5123 default: llvm_unreachable("Unknown instruction!");
5124 case ISD::UADDO_CARRY:
5125 if (!isAddCarryChain(Carry))
5126 return SDValue();
5127
5128 BaseOp = SystemZISD::ADDCARRY;
5129 CCValid = SystemZ::CCMASK_LOGICAL;
5131 break;
5132 case ISD::USUBO_CARRY:
5133 if (!isSubBorrowChain(Carry))
5134 return SDValue();
5135
5136 BaseOp = SystemZISD::SUBCARRY;
5137 CCValid = SystemZ::CCMASK_LOGICAL;
5139 break;
5140 }
5141
5142 // Set the condition code from the carry flag.
5143 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5144 DAG.getConstant(CCValid, DL, MVT::i32),
5145 DAG.getConstant(CCMask, DL, MVT::i32));
5146
5147 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5148 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5149
5150 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5151 if (N->getValueType(1) == MVT::i1)
5152 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5153
5154 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5155}
5156
5157SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5158 SelectionDAG &DAG) const {
5159 EVT VT = Op.getValueType();
5160 SDLoc DL(Op);
5161 Op = Op.getOperand(0);
5162
5163 if (VT.getScalarSizeInBits() == 128) {
5164 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5165 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5166 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5167 DAG.getConstant(0, DL, MVT::i64));
5168 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5169 return Op;
5170 }
5171
5172 // Handle vector types via VPOPCT.
5173 if (VT.isVector()) {
5174 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5175 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5176 switch (VT.getScalarSizeInBits()) {
5177 case 8:
5178 break;
5179 case 16: {
5180 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5181 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5182 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5183 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5184 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5185 break;
5186 }
5187 case 32: {
5188 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5189 DAG.getConstant(0, DL, MVT::i32));
5190 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5191 break;
5192 }
5193 case 64: {
5194 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5195 DAG.getConstant(0, DL, MVT::i32));
5196 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5197 Tmp = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, Tmp);
5198 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5199 break;
5200 }
5201 default:
5202 llvm_unreachable("Unexpected type");
5203 }
5204 return Op;
5205 }
5206
5207 // Get the known-zero mask for the operand.
5208 KnownBits Known = DAG.computeKnownBits(Op);
5209 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5210 if (NumSignificantBits == 0)
5211 return DAG.getConstant(0, DL, VT);
5212
5213 // Skip known-zero high parts of the operand.
5214 int64_t OrigBitSize = VT.getSizeInBits();
5215 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5216 BitSize = std::min(BitSize, OrigBitSize);
5217
5218 // The POPCNT instruction counts the number of bits in each byte.
5219 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5220 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5221 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5222
5223 // Add up per-byte counts in a binary tree. All bits of Op at
5224 // position larger than BitSize remain zero throughout.
5225 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5226 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5227 if (BitSize != OrigBitSize)
5228 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5229 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5230 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5231 }
5232
5233 // Extract overall result from high byte.
5234 if (BitSize > 8)
5235 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5236 DAG.getConstant(BitSize - 8, DL, VT));
5237
5238 return Op;
5239}
5240
5241SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5242 SelectionDAG &DAG) const {
5243 SDLoc DL(Op);
5244 AtomicOrdering FenceOrdering =
5245 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5246 SyncScope::ID FenceSSID =
5247 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5248
5249 // The only fence that needs an instruction is a sequentially-consistent
5250 // cross-thread fence.
5251 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5252 FenceSSID == SyncScope::System) {
5253 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5254 Op.getOperand(0)),
5255 0);
5256 }
5257
5258 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5259 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5260}
5261
5262SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5263 SelectionDAG &DAG) const {
5264 EVT RegVT = Op.getValueType();
5265 if (RegVT.getSizeInBits() == 128)
5266 return lowerATOMIC_LDST_I128(Op, DAG);
5267 return lowerLoadF16(Op, DAG);
5268}
5269
5270SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5271 SelectionDAG &DAG) const {
5272 auto *Node = cast<AtomicSDNode>(Op.getNode());
5273 if (Node->getMemoryVT().getSizeInBits() == 128)
5274 return lowerATOMIC_LDST_I128(Op, DAG);
5275 return lowerStoreF16(Op, DAG);
5276}
5277
5278SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5279 SelectionDAG &DAG) const {
5280 auto *Node = cast<AtomicSDNode>(Op.getNode());
5281 assert(
5282 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5283 "Only custom lowering i128 or f128.");
5284 // Use same code to handle both legal and non-legal i128 types.
5286 LowerOperationWrapper(Node, Results, DAG);
5287 return DAG.getMergeValues(Results, SDLoc(Op));
5288}
5289
5290// Prepare for a Compare And Swap for a subword operation. This needs to be
5291// done in memory with 4 bytes at natural alignment.
5293 SDValue &AlignedAddr, SDValue &BitShift,
5294 SDValue &NegBitShift) {
5295 EVT PtrVT = Addr.getValueType();
5296 EVT WideVT = MVT::i32;
5297
5298 // Get the address of the containing word.
5299 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5300 DAG.getSignedConstant(-4, DL, PtrVT));
5301
5302 // Get the number of bits that the word must be rotated left in order
5303 // to bring the field to the top bits of a GR32.
5304 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5305 DAG.getConstant(3, DL, PtrVT));
5306 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5307
5308 // Get the complementing shift amount, for rotating a field in the top
5309 // bits back to its proper position.
5310 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5311 DAG.getConstant(0, DL, WideVT), BitShift);
5312
5313}
5314
5315// N is an 8- or 16-bit ATOMIC_LOAD_* operation. Lower it into the fullword
5316// ATOMIC_LOADW_* operation.
5317void SystemZTargetLowering::lowerATOMIC_LOAD_OP(
5319 unsigned Opcode) const {
5320 auto *Node = cast<AtomicSDNode>(N);
5321
5322 EVT NarrowVT = Node->getMemoryVT();
5323 EVT WideVT = MVT::i32;
5324 int64_t BitSize = NarrowVT.getSizeInBits();
5325 SDValue ChainIn = Node->getChain();
5326 SDValue Addr = Node->getBasePtr();
5327 SDValue Src2 = Node->getVal();
5328 MachineMemOperand *MMO = Node->getMemOperand();
5329 SDLoc DL(Node);
5330
5331 // Convert atomic subtracts of constants into additions.
5332 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5333 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5334 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5335 Src2 = DAG.getConstant(-Const->getAPIntValue(), DL, Src2.getValueType());
5336 }
5337
5338 SDValue AlignedAddr, BitShift, NegBitShift;
5339 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5340
5341 // Extend the source operand to 32 bits and prepare it for the inner loop.
5342 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5343 // operations require the source to be shifted in advance. (This shift
5344 // can be folded if the source is constant.) For AND and NAND, the lower
5345 // bits must be set, while for other opcodes they should be left clear.
5346 Src2 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Src2);
5347 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5348 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5349 DAG.getConstant(32 - BitSize, DL, WideVT));
5350 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5351 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5352 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5353 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5354
5355 // Construct the ATOMIC_LOADW_* node.
5356 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5357 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5358 DAG.getConstant(BitSize, DL, WideVT) };
5359 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5360 NarrowVT, MMO);
5361
5362 // Rotate the result of the final CS so that the field is in the lower
5363 // bits of a GR32, then truncate it.
5364 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5365 DAG.getConstant(BitSize, DL, WideVT));
5366 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5367 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, Result));
5368 Results.push_back(AtomicOp.getValue(1));
5369}
5370
5371// Op is a 32- or 64-bit ATOMIC_LOAD_SUB operation. Convert it into an
5372// addition.
5373SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5374 SelectionDAG &DAG) const {
5375 auto *Node = cast<AtomicSDNode>(Op.getNode());
5376 EVT MemVT = Node->getMemoryVT();
5377 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5378 assert(Subtarget.hasInterlockedAccess1() &&
5379 "Should have been expanded by AtomicExpand pass.");
5380 SDValue Src2 = Node->getVal();
5381 SDLoc DL(Src2);
5382 SDValue NegSrc2 =
5383 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5384 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT, Node->getChain(),
5385 Node->getBasePtr(), NegSrc2, Node->getMemOperand());
5386}
5387
5388// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5389SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5390 SelectionDAG &DAG) const {
5391 auto *Node = cast<AtomicSDNode>(Op.getNode());
5392 SDValue ChainIn = Node->getOperand(0);
5393 SDValue Addr = Node->getOperand(1);
5394 SDValue CmpVal = Node->getOperand(2);
5395 SDValue SwapVal = Node->getOperand(3);
5396 MachineMemOperand *MMO = Node->getMemOperand();
5397 SDLoc DL(Node);
5398
5399 if (Node->getMemoryVT() == MVT::i128) {
5400 // Use same code to handle both legal and non-legal i128 types.
5402 LowerOperationWrapper(Node, Results, DAG);
5403 return DAG.getMergeValues(Results, DL);
5404 }
5405
5406 // We have native support for 32-bit and 64-bit compare and swap, but we
5407 // still need to expand extracting the "success" result from the CC.
5408 EVT NarrowVT = Node->getMemoryVT();
5409 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5410 if (NarrowVT == WideVT) {
5411 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5412 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5413 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5414 DL, Tys, Ops, NarrowVT, MMO);
5415 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5417
5418 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5419 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5420 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5421 return SDValue();
5422 }
5423
5424 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5425 // via a fullword ATOMIC_CMP_SWAPW operation.
5426 int64_t BitSize = NarrowVT.getSizeInBits();
5427
5428 SDValue AlignedAddr, BitShift, NegBitShift;
5429 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5430
5431 // Construct the ATOMIC_CMP_SWAPW node.
5432 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5433 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5434 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5435 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5436 VTList, Ops, NarrowVT, MMO);
5437 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5439
5440 // emitAtomicCmpSwapW() will zero extend the result (original value).
5441 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5442 DAG.getValueType(NarrowVT));
5443 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5444 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5445 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5446 return SDValue();
5447}
5448
5450SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5451 // Because of how we convert atomic_load and atomic_store to normal loads and
5452 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5453 // since DAGCombine hasn't been updated to account for atomic, but non
5454 // volatile loads. (See D57601)
5455 if (auto *SI = dyn_cast<StoreInst>(&I))
5456 if (SI->isAtomic())
5458 if (auto *LI = dyn_cast<LoadInst>(&I))
5459 if (LI->isAtomic())
5461 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5462 if (AI->isAtomic())
5464 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5465 if (AI->isAtomic())
5468}
5469
5470SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5471 SelectionDAG &DAG) const {
5473 auto *Regs = Subtarget.getSpecialRegisters();
5475 report_fatal_error("Variable-sized stack allocations are not supported "
5476 "in GHC calling convention");
5477 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5478 Regs->getStackPointerRegister(), Op.getValueType());
5479}
5480
5481SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5482 SelectionDAG &DAG) const {
5484 auto *Regs = Subtarget.getSpecialRegisters();
5485 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5486
5488 report_fatal_error("Variable-sized stack allocations are not supported "
5489 "in GHC calling convention");
5490
5491 SDValue Chain = Op.getOperand(0);
5492 SDValue NewSP = Op.getOperand(1);
5493 SDValue Backchain;
5494 SDLoc DL(Op);
5495
5496 if (StoreBackchain) {
5497 SDValue OldSP = DAG.getCopyFromReg(
5498 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5499 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5500 MachinePointerInfo());
5501 }
5502
5503 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5504
5505 if (StoreBackchain)
5506 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5507 MachinePointerInfo());
5508
5509 return Chain;
5510}
5511
5512SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5513 SelectionDAG &DAG) const {
5514 bool IsData = Op.getConstantOperandVal(4);
5515 if (!IsData)
5516 // Just preserve the chain.
5517 return Op.getOperand(0);
5518
5519 SDLoc DL(Op);
5520 bool IsWrite = Op.getConstantOperandVal(2);
5521 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5522 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5523 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5524 Op.getOperand(1)};
5525 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5526 Node->getVTList(), Ops,
5527 Node->getMemoryVT(), Node->getMemOperand());
5528}
5529
5530SDValue
5531SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5532 SelectionDAG &DAG) const {
5533 unsigned Opcode, CCValid;
5534 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5535 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5536 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5537 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5538 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5539 return SDValue();
5540 }
5541
5542 return SDValue();
5543}
5544
5545SDValue
5546SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5547 SelectionDAG &DAG) const {
5548 unsigned Opcode, CCValid;
5549 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5550 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5551 if (Op->getNumValues() == 1)
5552 return getCCResult(DAG, SDValue(Node, 0));
5553 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5554 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5555 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5556 }
5557
5558 unsigned Id = Op.getConstantOperandVal(0);
5559 switch (Id) {
5560 case Intrinsic::thread_pointer:
5561 return lowerThreadPointer(SDLoc(Op), DAG);
5562
5563 case Intrinsic::s390_vpdi:
5564 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5565 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5566
5567 case Intrinsic::s390_vperm:
5568 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5569 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5570
5571 case Intrinsic::s390_vuphb:
5572 case Intrinsic::s390_vuphh:
5573 case Intrinsic::s390_vuphf:
5574 case Intrinsic::s390_vuphg:
5575 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5576 Op.getOperand(1));
5577
5578 case Intrinsic::s390_vuplhb:
5579 case Intrinsic::s390_vuplhh:
5580 case Intrinsic::s390_vuplhf:
5581 case Intrinsic::s390_vuplhg:
5582 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5583 Op.getOperand(1));
5584
5585 case Intrinsic::s390_vuplb:
5586 case Intrinsic::s390_vuplhw:
5587 case Intrinsic::s390_vuplf:
5588 case Intrinsic::s390_vuplg:
5589 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5590 Op.getOperand(1));
5591
5592 case Intrinsic::s390_vupllb:
5593 case Intrinsic::s390_vupllh:
5594 case Intrinsic::s390_vupllf:
5595 case Intrinsic::s390_vupllg:
5596 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5597 Op.getOperand(1));
5598
5599 case Intrinsic::s390_vsumb:
5600 case Intrinsic::s390_vsumh:
5601 case Intrinsic::s390_vsumgh:
5602 case Intrinsic::s390_vsumgf:
5603 case Intrinsic::s390_vsumqf:
5604 case Intrinsic::s390_vsumqg:
5605 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5606 Op.getOperand(1), Op.getOperand(2));
5607
5608 case Intrinsic::s390_vaq:
5609 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5610 Op.getOperand(1), Op.getOperand(2));
5611 case Intrinsic::s390_vaccb:
5612 case Intrinsic::s390_vacch:
5613 case Intrinsic::s390_vaccf:
5614 case Intrinsic::s390_vaccg:
5615 case Intrinsic::s390_vaccq:
5616 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5617 Op.getOperand(1), Op.getOperand(2));
5618 case Intrinsic::s390_vacq:
5619 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5620 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5621 case Intrinsic::s390_vacccq:
5622 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5623 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5624
5625 case Intrinsic::s390_vsq:
5626 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5627 Op.getOperand(1), Op.getOperand(2));
5628 case Intrinsic::s390_vscbib:
5629 case Intrinsic::s390_vscbih:
5630 case Intrinsic::s390_vscbif:
5631 case Intrinsic::s390_vscbig:
5632 case Intrinsic::s390_vscbiq:
5633 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5634 Op.getOperand(1), Op.getOperand(2));
5635 case Intrinsic::s390_vsbiq:
5636 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5637 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5638 case Intrinsic::s390_vsbcbiq:
5639 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5640 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5641
5642 case Intrinsic::s390_vmhb:
5643 case Intrinsic::s390_vmhh:
5644 case Intrinsic::s390_vmhf:
5645 case Intrinsic::s390_vmhg:
5646 case Intrinsic::s390_vmhq:
5647 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5648 Op.getOperand(1), Op.getOperand(2));
5649 case Intrinsic::s390_vmlhb:
5650 case Intrinsic::s390_vmlhh:
5651 case Intrinsic::s390_vmlhf:
5652 case Intrinsic::s390_vmlhg:
5653 case Intrinsic::s390_vmlhq:
5654 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5655 Op.getOperand(1), Op.getOperand(2));
5656
5657 case Intrinsic::s390_vmahb:
5658 case Intrinsic::s390_vmahh:
5659 case Intrinsic::s390_vmahf:
5660 case Intrinsic::s390_vmahg:
5661 case Intrinsic::s390_vmahq:
5662 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5663 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5664 case Intrinsic::s390_vmalhb:
5665 case Intrinsic::s390_vmalhh:
5666 case Intrinsic::s390_vmalhf:
5667 case Intrinsic::s390_vmalhg:
5668 case Intrinsic::s390_vmalhq:
5669 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5670 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5671
5672 case Intrinsic::s390_vmeb:
5673 case Intrinsic::s390_vmeh:
5674 case Intrinsic::s390_vmef:
5675 case Intrinsic::s390_vmeg:
5676 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5677 Op.getOperand(1), Op.getOperand(2));
5678 case Intrinsic::s390_vmleb:
5679 case Intrinsic::s390_vmleh:
5680 case Intrinsic::s390_vmlef:
5681 case Intrinsic::s390_vmleg:
5682 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5683 Op.getOperand(1), Op.getOperand(2));
5684 case Intrinsic::s390_vmob:
5685 case Intrinsic::s390_vmoh:
5686 case Intrinsic::s390_vmof:
5687 case Intrinsic::s390_vmog:
5688 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5689 Op.getOperand(1), Op.getOperand(2));
5690 case Intrinsic::s390_vmlob:
5691 case Intrinsic::s390_vmloh:
5692 case Intrinsic::s390_vmlof:
5693 case Intrinsic::s390_vmlog:
5694 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5695 Op.getOperand(1), Op.getOperand(2));
5696
5697 case Intrinsic::s390_vmaeb:
5698 case Intrinsic::s390_vmaeh:
5699 case Intrinsic::s390_vmaef:
5700 case Intrinsic::s390_vmaeg:
5701 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5702 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5703 Op.getOperand(1), Op.getOperand(2)),
5704 Op.getOperand(3));
5705 case Intrinsic::s390_vmaleb:
5706 case Intrinsic::s390_vmaleh:
5707 case Intrinsic::s390_vmalef:
5708 case Intrinsic::s390_vmaleg:
5709 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5710 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5711 Op.getOperand(1), Op.getOperand(2)),
5712 Op.getOperand(3));
5713 case Intrinsic::s390_vmaob:
5714 case Intrinsic::s390_vmaoh:
5715 case Intrinsic::s390_vmaof:
5716 case Intrinsic::s390_vmaog:
5717 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5718 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5719 Op.getOperand(1), Op.getOperand(2)),
5720 Op.getOperand(3));
5721 case Intrinsic::s390_vmalob:
5722 case Intrinsic::s390_vmaloh:
5723 case Intrinsic::s390_vmalof:
5724 case Intrinsic::s390_vmalog:
5725 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5726 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5727 Op.getOperand(1), Op.getOperand(2)),
5728 Op.getOperand(3));
5729 }
5730
5731 return SDValue();
5732}
5733
5734namespace {
5735// Says that SystemZISD operation Opcode can be used to perform the equivalent
5736// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5737// Operand is the constant third operand, otherwise it is the number of
5738// bytes in each element of the result.
5739struct Permute {
5740 unsigned Opcode;
5741 unsigned Operand;
5742 unsigned char Bytes[SystemZ::VectorBytes];
5743};
5744}
5745
5746static const Permute PermuteForms[] = {
5747 // VMRHG
5748 { SystemZISD::MERGE_HIGH, 8,
5749 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5750 // VMRHF
5751 { SystemZISD::MERGE_HIGH, 4,
5752 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5753 // VMRHH
5754 { SystemZISD::MERGE_HIGH, 2,
5755 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5756 // VMRHB
5757 { SystemZISD::MERGE_HIGH, 1,
5758 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5759 // VMRLG
5760 { SystemZISD::MERGE_LOW, 8,
5761 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5762 // VMRLF
5763 { SystemZISD::MERGE_LOW, 4,
5764 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5765 // VMRLH
5766 { SystemZISD::MERGE_LOW, 2,
5767 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5768 // VMRLB
5769 { SystemZISD::MERGE_LOW, 1,
5770 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5771 // VPKG
5772 { SystemZISD::PACK, 4,
5773 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5774 // VPKF
5775 { SystemZISD::PACK, 2,
5776 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5777 // VPKH
5778 { SystemZISD::PACK, 1,
5779 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5780 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5781 { SystemZISD::PERMUTE_DWORDS, 4,
5782 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5783 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5784 { SystemZISD::PERMUTE_DWORDS, 1,
5785 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5786};
5787
5788// Called after matching a vector shuffle against a particular pattern.
5789// Both the original shuffle and the pattern have two vector operands.
5790// OpNos[0] is the operand of the original shuffle that should be used for
5791// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5792// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5793// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5794// for operands 0 and 1 of the pattern.
5795static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5796 if (OpNos[0] < 0) {
5797 if (OpNos[1] < 0)
5798 return false;
5799 OpNo0 = OpNo1 = OpNos[1];
5800 } else if (OpNos[1] < 0) {
5801 OpNo0 = OpNo1 = OpNos[0];
5802 } else {
5803 OpNo0 = OpNos[0];
5804 OpNo1 = OpNos[1];
5805 }
5806 return true;
5807}
5808
5809// Bytes is a VPERM-like permute vector, except that -1 is used for
5810// undefined bytes. Return true if the VPERM can be implemented using P.
5811// When returning true set OpNo0 to the VPERM operand that should be
5812// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5813//
5814// For example, if swapping the VPERM operands allows P to match, OpNo0
5815// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5816// operand, but rewriting it to use two duplicated operands allows it to
5817// match P, then OpNo0 and OpNo1 will be the same.
5818static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5819 unsigned &OpNo0, unsigned &OpNo1) {
5820 int OpNos[] = { -1, -1 };
5821 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5822 int Elt = Bytes[I];
5823 if (Elt >= 0) {
5824 // Make sure that the two permute vectors use the same suboperand
5825 // byte number. Only the operand numbers (the high bits) are
5826 // allowed to differ.
5827 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5828 return false;
5829 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5830 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5831 // Make sure that the operand mappings are consistent with previous
5832 // elements.
5833 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5834 return false;
5835 OpNos[ModelOpNo] = RealOpNo;
5836 }
5837 }
5838 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5839}
5840
5841// As above, but search for a matching permute.
5842static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5843 unsigned &OpNo0, unsigned &OpNo1) {
5844 for (auto &P : PermuteForms)
5845 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5846 return &P;
5847 return nullptr;
5848}
5849
5850// Bytes is a VPERM-like permute vector, except that -1 is used for
5851// undefined bytes. This permute is an operand of an outer permute.
5852// See whether redistributing the -1 bytes gives a shuffle that can be
5853// implemented using P. If so, set Transform to a VPERM-like permute vector
5854// that, when applied to the result of P, gives the original permute in Bytes.
5856 const Permute &P,
5857 SmallVectorImpl<int> &Transform) {
5858 unsigned To = 0;
5859 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5860 int Elt = Bytes[From];
5861 if (Elt < 0)
5862 // Byte number From of the result is undefined.
5863 Transform[From] = -1;
5864 else {
5865 while (P.Bytes[To] != Elt) {
5866 To += 1;
5867 if (To == SystemZ::VectorBytes)
5868 return false;
5869 }
5870 Transform[From] = To;
5871 }
5872 }
5873 return true;
5874}
5875
5876// As above, but search for a matching permute.
5877static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
5878 SmallVectorImpl<int> &Transform) {
5879 for (auto &P : PermuteForms)
5880 if (matchDoublePermute(Bytes, P, Transform))
5881 return &P;
5882 return nullptr;
5883}
5884
5885// Convert the mask of the given shuffle op into a byte-level mask,
5886// as if it had type vNi8.
5887static bool getVPermMask(SDValue ShuffleOp,
5888 SmallVectorImpl<int> &Bytes) {
5889 EVT VT = ShuffleOp.getValueType();
5890 unsigned NumElements = VT.getVectorNumElements();
5891 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
5892
5893 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
5894 Bytes.resize(NumElements * BytesPerElement, -1);
5895 for (unsigned I = 0; I < NumElements; ++I) {
5896 int Index = VSN->getMaskElt(I);
5897 if (Index >= 0)
5898 for (unsigned J = 0; J < BytesPerElement; ++J)
5899 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5900 }
5901 return true;
5902 }
5903 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
5904 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
5905 unsigned Index = ShuffleOp.getConstantOperandVal(1);
5906 Bytes.resize(NumElements * BytesPerElement, -1);
5907 for (unsigned I = 0; I < NumElements; ++I)
5908 for (unsigned J = 0; J < BytesPerElement; ++J)
5909 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5910 return true;
5911 }
5912 return false;
5913}
5914
5915// Bytes is a VPERM-like permute vector, except that -1 is used for
5916// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
5917// the result come from a contiguous sequence of bytes from one input.
5918// Set Base to the selector for the first byte if so.
5919static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
5920 unsigned BytesPerElement, int &Base) {
5921 Base = -1;
5922 for (unsigned I = 0; I < BytesPerElement; ++I) {
5923 if (Bytes[Start + I] >= 0) {
5924 unsigned Elem = Bytes[Start + I];
5925 if (Base < 0) {
5926 Base = Elem - I;
5927 // Make sure the bytes would come from one input operand.
5928 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
5929 return false;
5930 } else if (unsigned(Base) != Elem - I)
5931 return false;
5932 }
5933 }
5934 return true;
5935}
5936
5937// Bytes is a VPERM-like permute vector, except that -1 is used for
5938// undefined bytes. Return true if it can be performed using VSLDB.
5939// When returning true, set StartIndex to the shift amount and OpNo0
5940// and OpNo1 to the VPERM operands that should be used as the first
5941// and second shift operand respectively.
5943 unsigned &StartIndex, unsigned &OpNo0,
5944 unsigned &OpNo1) {
5945 int OpNos[] = { -1, -1 };
5946 int Shift = -1;
5947 for (unsigned I = 0; I < 16; ++I) {
5948 int Index = Bytes[I];
5949 if (Index >= 0) {
5950 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
5951 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
5952 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
5953 if (Shift < 0)
5954 Shift = ExpectedShift;
5955 else if (Shift != ExpectedShift)
5956 return false;
5957 // Make sure that the operand mappings are consistent with previous
5958 // elements.
5959 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5960 return false;
5961 OpNos[ModelOpNo] = RealOpNo;
5962 }
5963 }
5964 StartIndex = Shift;
5965 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5966}
5967
5968// Create a node that performs P on operands Op0 and Op1, casting the
5969// operands to the appropriate type. The type of the result is determined by P.
5971 const Permute &P, SDValue Op0, SDValue Op1) {
5972 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
5973 // elements of a PACK are twice as wide as the outputs.
5974 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
5975 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
5976 P.Operand);
5977 // Cast both operands to the appropriate type.
5978 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
5979 SystemZ::VectorBytes / InBytes);
5980 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
5981 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
5982 SDValue Op;
5983 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
5984 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
5985 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
5986 } else if (P.Opcode == SystemZISD::PACK) {
5987 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
5988 SystemZ::VectorBytes / P.Operand);
5989 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
5990 } else {
5991 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
5992 }
5993 return Op;
5994}
5995
5996static bool isZeroVector(SDValue N) {
5997 if (N->getOpcode() == ISD::BITCAST)
5998 N = N->getOperand(0);
5999 if (N->getOpcode() == ISD::SPLAT_VECTOR)
6000 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
6001 return Op->getZExtValue() == 0;
6002 return ISD::isBuildVectorAllZeros(N.getNode());
6003}
6004
6005// Return the index of the zero/undef vector, or UINT32_MAX if not found.
6006static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
6007 for (unsigned I = 0; I < Num ; I++)
6008 if (isZeroVector(Ops[I]))
6009 return I;
6010 return UINT32_MAX;
6011}
6012
6013// Bytes is a VPERM-like permute vector, except that -1 is used for
6014// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
6015// VSLDB or VPERM.
6017 SDValue *Ops,
6018 const SmallVectorImpl<int> &Bytes) {
6019 for (unsigned I = 0; I < 2; ++I)
6020 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
6021
6022 // First see whether VSLDB can be used.
6023 unsigned StartIndex, OpNo0, OpNo1;
6024 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
6025 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
6026 Ops[OpNo1],
6027 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
6028
6029 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
6030 // eliminate a zero vector by reusing any zero index in the permute vector.
6031 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
6032 if (ZeroVecIdx != UINT32_MAX) {
6033 bool MaskFirst = true;
6034 int ZeroIdx = -1;
6035 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6036 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6037 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6038 if (OpNo == ZeroVecIdx && I == 0) {
6039 // If the first byte is zero, use mask as first operand.
6040 ZeroIdx = 0;
6041 break;
6042 }
6043 if (OpNo != ZeroVecIdx && Byte == 0) {
6044 // If mask contains a zero, use it by placing that vector first.
6045 ZeroIdx = I + SystemZ::VectorBytes;
6046 MaskFirst = false;
6047 break;
6048 }
6049 }
6050 if (ZeroIdx != -1) {
6051 SDValue IndexNodes[SystemZ::VectorBytes];
6052 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6053 if (Bytes[I] >= 0) {
6054 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6055 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6056 if (OpNo == ZeroVecIdx)
6057 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
6058 else {
6059 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
6060 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
6061 }
6062 } else
6063 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6064 }
6065 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6066 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
6067 if (MaskFirst)
6068 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
6069 Mask);
6070 else
6071 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
6072 Mask);
6073 }
6074 }
6075
6076 SDValue IndexNodes[SystemZ::VectorBytes];
6077 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6078 if (Bytes[I] >= 0)
6079 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
6080 else
6081 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6082 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6083 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
6084 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
6085}
6086
6087namespace {
6088// Describes a general N-operand vector shuffle.
6089struct GeneralShuffle {
6090 GeneralShuffle(EVT vt)
6091 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
6092 void addUndef();
6093 bool add(SDValue, unsigned);
6094 SDValue getNode(SelectionDAG &, const SDLoc &);
6095 void tryPrepareForUnpack();
6096 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6097 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6098
6099 // The operands of the shuffle.
6101
6102 // Index I is -1 if byte I of the result is undefined. Otherwise the
6103 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6104 // Bytes[I] / SystemZ::VectorBytes.
6106
6107 // The type of the shuffle result.
6108 EVT VT;
6109
6110 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6111 unsigned UnpackFromEltSize;
6112 // True if the final unpack uses the low half.
6113 bool UnpackLow;
6114};
6115} // namespace
6116
6117// Add an extra undefined element to the shuffle.
6118void GeneralShuffle::addUndef() {
6119 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6120 for (unsigned I = 0; I < BytesPerElement; ++I)
6121 Bytes.push_back(-1);
6122}
6123
6124// Add an extra element to the shuffle, taking it from element Elem of Op.
6125// A null Op indicates a vector input whose value will be calculated later;
6126// there is at most one such input per shuffle and it always has the same
6127// type as the result. Aborts and returns false if the source vector elements
6128// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6129// LLVM they become implicitly extended, but this is rare and not optimized.
6130bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6131 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6132
6133 // The source vector can have wider elements than the result,
6134 // either through an explicit TRUNCATE or because of type legalization.
6135 // We want the least significant part.
6136 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6137 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6138
6139 // Return false if the source elements are smaller than their destination
6140 // elements.
6141 if (FromBytesPerElement < BytesPerElement)
6142 return false;
6143
6144 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6145 (FromBytesPerElement - BytesPerElement));
6146
6147 // Look through things like shuffles and bitcasts.
6148 while (Op.getNode()) {
6149 if (Op.getOpcode() == ISD::BITCAST)
6150 Op = Op.getOperand(0);
6151 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6152 // See whether the bytes we need come from a contiguous part of one
6153 // operand.
6155 if (!getVPermMask(Op, OpBytes))
6156 break;
6157 int NewByte;
6158 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6159 break;
6160 if (NewByte < 0) {
6161 addUndef();
6162 return true;
6163 }
6164 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6165 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6166 } else if (Op.isUndef()) {
6167 addUndef();
6168 return true;
6169 } else
6170 break;
6171 }
6172
6173 // Make sure that the source of the extraction is in Ops.
6174 unsigned OpNo = 0;
6175 for (; OpNo < Ops.size(); ++OpNo)
6176 if (Ops[OpNo] == Op)
6177 break;
6178 if (OpNo == Ops.size())
6179 Ops.push_back(Op);
6180
6181 // Add the element to Bytes.
6182 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6183 for (unsigned I = 0; I < BytesPerElement; ++I)
6184 Bytes.push_back(Base + I);
6185
6186 return true;
6187}
6188
6189// Return SDNodes for the completed shuffle.
6190SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6191 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6192
6193 if (Ops.size() == 0)
6194 return DAG.getUNDEF(VT);
6195
6196 // Use a single unpack if possible as the last operation.
6197 tryPrepareForUnpack();
6198
6199 // Make sure that there are at least two shuffle operands.
6200 if (Ops.size() == 1)
6201 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6202
6203 // Create a tree of shuffles, deferring root node until after the loop.
6204 // Try to redistribute the undefined elements of non-root nodes so that
6205 // the non-root shuffles match something like a pack or merge, then adjust
6206 // the parent node's permute vector to compensate for the new order.
6207 // Among other things, this copes with vectors like <2 x i16> that were
6208 // padded with undefined elements during type legalization.
6209 //
6210 // In the best case this redistribution will lead to the whole tree
6211 // using packs and merges. It should rarely be a loss in other cases.
6212 unsigned Stride = 1;
6213 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6214 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6215 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6216
6217 // Create a mask for just these two operands.
6219 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6220 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6221 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6222 if (OpNo == I)
6223 NewBytes[J] = Byte;
6224 else if (OpNo == I + Stride)
6225 NewBytes[J] = SystemZ::VectorBytes + Byte;
6226 else
6227 NewBytes[J] = -1;
6228 }
6229 // See if it would be better to reorganize NewMask to avoid using VPERM.
6231 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6232 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6233 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6234 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6235 if (NewBytes[J] >= 0) {
6236 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6237 "Invalid double permute");
6238 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6239 } else
6240 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6241 }
6242 } else {
6243 // Just use NewBytes on the operands.
6244 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6245 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6246 if (NewBytes[J] >= 0)
6247 Bytes[J] = I * SystemZ::VectorBytes + J;
6248 }
6249 }
6250 }
6251
6252 // Now we just have 2 inputs. Put the second operand in Ops[1].
6253 if (Stride > 1) {
6254 Ops[1] = Ops[Stride];
6255 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6256 if (Bytes[I] >= int(SystemZ::VectorBytes))
6257 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6258 }
6259
6260 // Look for an instruction that can do the permute without resorting
6261 // to VPERM.
6262 unsigned OpNo0, OpNo1;
6263 SDValue Op;
6264 if (unpackWasPrepared() && Ops[1].isUndef())
6265 Op = Ops[0];
6266 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6267 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6268 else
6269 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6270
6271 Op = insertUnpackIfPrepared(DAG, DL, Op);
6272
6273 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6274}
6275
6276#ifndef NDEBUG
6277static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6278 dbgs() << Msg.c_str() << " { ";
6279 for (unsigned I = 0; I < Bytes.size(); I++)
6280 dbgs() << Bytes[I] << " ";
6281 dbgs() << "}\n";
6282}
6283#endif
6284
6285// If the Bytes vector matches an unpack operation, prepare to do the unpack
6286// after all else by removing the zero vector and the effect of the unpack on
6287// Bytes.
6288void GeneralShuffle::tryPrepareForUnpack() {
6289 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6290 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6291 return;
6292
6293 // Only do this if removing the zero vector reduces the depth, otherwise
6294 // the critical path will increase with the final unpack.
6295 if (Ops.size() > 2 &&
6296 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6297 return;
6298
6299 // Find an unpack that would allow removing the zero vector from Ops.
6300 UnpackFromEltSize = 1;
6301 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6302 bool MatchUnpack = true;
6304 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6305 unsigned ToEltSize = UnpackFromEltSize * 2;
6306 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6307 if (!IsZextByte)
6308 SrcBytes.push_back(Bytes[Elt]);
6309 if (Bytes[Elt] != -1) {
6310 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6311 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6312 MatchUnpack = false;
6313 break;
6314 }
6315 }
6316 }
6317 if (MatchUnpack) {
6318 if (Ops.size() == 2) {
6319 // Don't use unpack if a single source operand needs rearrangement.
6320 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6321 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6322 if (SrcBytes[i] == -1)
6323 continue;
6324 if (SrcBytes[i] % 16 != int(i))
6325 CanUseUnpackHigh = false;
6326 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6327 CanUseUnpackLow = false;
6328 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6329 UnpackFromEltSize = UINT_MAX;
6330 return;
6331 }
6332 }
6333 if (!CanUseUnpackHigh)
6334 UnpackLow = true;
6335 }
6336 break;
6337 }
6338 }
6339 if (UnpackFromEltSize > 4)
6340 return;
6341
6342 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6343 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6344 << ".\n";
6345 dumpBytes(Bytes, "Original Bytes vector:"););
6346
6347 // Apply the unpack in reverse to the Bytes array.
6348 unsigned B = 0;
6349 if (UnpackLow) {
6350 while (B < SystemZ::VectorBytes / 2)
6351 Bytes[B++] = -1;
6352 }
6353 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6354 Elt += UnpackFromEltSize;
6355 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6356 Bytes[B] = Bytes[Elt];
6357 }
6358 if (!UnpackLow) {
6359 while (B < SystemZ::VectorBytes)
6360 Bytes[B++] = -1;
6361 }
6362
6363 // Remove the zero vector from Ops
6364 Ops.erase(&Ops[ZeroVecOpNo]);
6365 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6366 if (Bytes[I] >= 0) {
6367 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6368 if (OpNo > ZeroVecOpNo)
6369 Bytes[I] -= SystemZ::VectorBytes;
6370 }
6371
6372 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6373 dbgs() << "\n";);
6374}
6375
6376SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6377 const SDLoc &DL,
6378 SDValue Op) {
6379 if (!unpackWasPrepared())
6380 return Op;
6381 unsigned InBits = UnpackFromEltSize * 8;
6382 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6383 SystemZ::VectorBits / InBits);
6384 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6385 unsigned OutBits = InBits * 2;
6386 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6387 SystemZ::VectorBits / OutBits);
6388 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6389 : SystemZISD::UNPACKL_HIGH,
6390 DL, OutVT, PackedOp);
6391}
6392
6393// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6395 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6396 if (!Op.getOperand(I).isUndef())
6397 return false;
6398 return true;
6399}
6400
6401// Return a vector of type VT that contains Value in the first element.
6402// The other elements don't matter.
6404 SDValue Value) {
6405 // If we have a constant, replicate it to all elements and let the
6406 // BUILD_VECTOR lowering take care of it.
6407 if (Value.getOpcode() == ISD::Constant ||
6408 Value.getOpcode() == ISD::ConstantFP) {
6410 return DAG.getBuildVector(VT, DL, Ops);
6411 }
6412 if (Value.isUndef())
6413 return DAG.getUNDEF(VT);
6414 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6415}
6416
6417// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6418// element 1. Used for cases in which replication is cheap.
6420 SDValue Op0, SDValue Op1) {
6421 if (Op0.isUndef()) {
6422 if (Op1.isUndef())
6423 return DAG.getUNDEF(VT);
6424 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6425 }
6426 if (Op1.isUndef())
6427 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6428 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6429 buildScalarToVector(DAG, DL, VT, Op0),
6430 buildScalarToVector(DAG, DL, VT, Op1));
6431}
6432
6433// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6434// vector for them.
6436 SDValue Op1) {
6437 if (Op0.isUndef() && Op1.isUndef())
6438 return DAG.getUNDEF(MVT::v2i64);
6439 // If one of the two inputs is undefined then replicate the other one,
6440 // in order to avoid using another register unnecessarily.
6441 if (Op0.isUndef())
6442 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6443 else if (Op1.isUndef())
6444 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6445 else {
6446 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6447 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6448 }
6449 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6450}
6451
6452// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6453// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6454// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6455// would benefit from this representation and return it if so.
6457 BuildVectorSDNode *BVN) {
6458 EVT VT = BVN->getValueType(0);
6459 unsigned NumElements = VT.getVectorNumElements();
6460
6461 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6462 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6463 // need a BUILD_VECTOR, add an additional placeholder operand for that
6464 // BUILD_VECTOR and store its operands in ResidueOps.
6465 GeneralShuffle GS(VT);
6467 bool FoundOne = false;
6468 for (unsigned I = 0; I < NumElements; ++I) {
6469 SDValue Op = BVN->getOperand(I);
6470 if (Op.getOpcode() == ISD::TRUNCATE)
6471 Op = Op.getOperand(0);
6472 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6473 Op.getOperand(1).getOpcode() == ISD::Constant) {
6474 unsigned Elem = Op.getConstantOperandVal(1);
6475 if (!GS.add(Op.getOperand(0), Elem))
6476 return SDValue();
6477 FoundOne = true;
6478 } else if (Op.isUndef()) {
6479 GS.addUndef();
6480 } else {
6481 if (!GS.add(SDValue(), ResidueOps.size()))
6482 return SDValue();
6483 ResidueOps.push_back(BVN->getOperand(I));
6484 }
6485 }
6486
6487 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6488 if (!FoundOne)
6489 return SDValue();
6490
6491 // Create the BUILD_VECTOR for the remaining elements, if any.
6492 if (!ResidueOps.empty()) {
6493 while (ResidueOps.size() < NumElements)
6494 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6495 for (auto &Op : GS.Ops) {
6496 if (!Op.getNode()) {
6497 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6498 break;
6499 }
6500 }
6501 }
6502 return GS.getNode(DAG, SDLoc(BVN));
6503}
6504
6505bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6506 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6507 return true;
6508 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6509 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6510 return true;
6511 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6512 return true;
6513 return false;
6514}
6515
6517 unsigned MergedBits, EVT VT, SDValue Op0,
6518 SDValue Op1) {
6519 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6520 SystemZ::VectorBits / MergedBits);
6521 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6522 "Handling full vectors only.");
6523 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6524 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6525 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6526 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6527}
6528
6530 EVT VT, SmallVectorImpl<SDValue> &Elems,
6531 unsigned Pos) {
6532 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6533 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6534 // Avoid unnecessary undefs by reusing the other operand.
6535 if (Op01.isUndef()) {
6536 if (Op23.isUndef())
6537 return Op01;
6538 Op01 = Op23;
6539 } else if (Op23.isUndef())
6540 Op23 = Op01;
6541 // Merging identical replications is a no-op.
6542 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6543 return Op01;
6544 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6545 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6546}
6547
6548// Combine GPR scalar values Elems into a vector of type VT.
6549SDValue
6550SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6551 SmallVectorImpl<SDValue> &Elems) const {
6552 // See whether there is a single replicated value.
6554 unsigned int NumElements = Elems.size();
6555 unsigned int Count = 0;
6556 for (auto Elem : Elems) {
6557 if (!Elem.isUndef()) {
6558 if (!Single.getNode())
6559 Single = Elem;
6560 else if (Elem != Single) {
6561 Single = SDValue();
6562 break;
6563 }
6564 Count += 1;
6565 }
6566 }
6567 // There are three cases here:
6568 //
6569 // - if the only defined element is a loaded one, the best sequence
6570 // is a replicating load.
6571 //
6572 // - otherwise, if the only defined element is an i64 value, we will
6573 // end up with the same VLVGP sequence regardless of whether we short-cut
6574 // for replication or fall through to the later code.
6575 //
6576 // - otherwise, if the only defined element is an i32 or smaller value,
6577 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6578 // This is only a win if the single defined element is used more than once.
6579 // In other cases we're better off using a single VLVGx.
6580 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6581 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6582
6583 // If all elements are loads, use VLREP/VLEs (below).
6584 bool AllLoads = true;
6585 for (auto Elem : Elems)
6586 if (!isVectorElementLoad(Elem)) {
6587 AllLoads = false;
6588 break;
6589 }
6590
6591 // The best way of building a v2i64 from two i64s is to use VLVGP.
6592 if (VT == MVT::v2i64 && !AllLoads)
6593 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6594
6595 // Use a 64-bit merge high to combine two doubles.
6596 if (VT == MVT::v2f64 && !AllLoads)
6597 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6598
6599 // Build v4f32 values directly from the FPRs:
6600 //
6601 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6602 // V V VMRHF
6603 // <ABxx> <CDxx>
6604 // V VMRHG
6605 // <ABCD>
6606 if (VT == MVT::v4f32 && !AllLoads)
6607 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6608
6609 // Same for v8f16.
6610 if (VT == MVT::v8f16 && !AllLoads) {
6611 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6612 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6613 // Avoid unnecessary undefs by reusing the other operand.
6614 if (Op0123.isUndef())
6615 Op0123 = Op4567;
6616 else if (Op4567.isUndef())
6617 Op4567 = Op0123;
6618 // Merging identical replications is a no-op.
6619 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6620 return Op0123;
6621 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6622 }
6623
6624 // Collect the constant terms.
6627
6628 unsigned NumConstants = 0;
6629 for (unsigned I = 0; I < NumElements; ++I) {
6630 SDValue Elem = Elems[I];
6631 if (Elem.getOpcode() == ISD::Constant ||
6632 Elem.getOpcode() == ISD::ConstantFP) {
6633 NumConstants += 1;
6634 Constants[I] = Elem;
6635 Done[I] = true;
6636 }
6637 }
6638 // If there was at least one constant, fill in the other elements of
6639 // Constants with undefs to get a full vector constant and use that
6640 // as the starting point.
6642 SDValue ReplicatedVal;
6643 if (NumConstants > 0) {
6644 for (unsigned I = 0; I < NumElements; ++I)
6645 if (!Constants[I].getNode())
6646 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6647 Result = DAG.getBuildVector(VT, DL, Constants);
6648 } else {
6649 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6650 // avoid a false dependency on any previous contents of the vector
6651 // register.
6652
6653 // Use a VLREP if at least one element is a load. Make sure to replicate
6654 // the load with the most elements having its value.
6655 std::map<const SDNode*, unsigned> UseCounts;
6656 SDNode *LoadMaxUses = nullptr;
6657 for (unsigned I = 0; I < NumElements; ++I)
6658 if (isVectorElementLoad(Elems[I])) {
6659 SDNode *Ld = Elems[I].getNode();
6660 unsigned Count = ++UseCounts[Ld];
6661 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6662 LoadMaxUses = Ld;
6663 }
6664 if (LoadMaxUses != nullptr) {
6665 ReplicatedVal = SDValue(LoadMaxUses, 0);
6666 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6667 } else {
6668 // Try to use VLVGP.
6669 unsigned I1 = NumElements / 2 - 1;
6670 unsigned I2 = NumElements - 1;
6671 bool Def1 = !Elems[I1].isUndef();
6672 bool Def2 = !Elems[I2].isUndef();
6673 if (Def1 || Def2) {
6674 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6675 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6676 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6677 joinDwords(DAG, DL, Elem1, Elem2));
6678 Done[I1] = true;
6679 Done[I2] = true;
6680 } else
6681 Result = DAG.getUNDEF(VT);
6682 }
6683 }
6684
6685 // Use VLVGx to insert the other elements.
6686 for (unsigned I = 0; I < NumElements; ++I)
6687 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6688 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6689 DAG.getConstant(I, DL, MVT::i32));
6690 return Result;
6691}
6692
6693SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6694 SelectionDAG &DAG) const {
6695 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6696 SDLoc DL(Op);
6697 EVT VT = Op.getValueType();
6698
6699 if (BVN->isConstant()) {
6700 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6701 return Op;
6702
6703 // Fall back to loading it from memory.
6704 return SDValue();
6705 }
6706
6707 // See if we should use shuffles to construct the vector from other vectors.
6708 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6709 return Res;
6710
6711 // Detect SCALAR_TO_VECTOR conversions.
6713 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6714
6715 // Otherwise use buildVector to build the vector up from GPRs.
6716 unsigned NumElements = Op.getNumOperands();
6718 for (unsigned I = 0; I < NumElements; ++I)
6719 Ops[I] = Op.getOperand(I);
6720 return buildVector(DAG, DL, VT, Ops);
6721}
6722
6723SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6724 SelectionDAG &DAG) const {
6725 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6726 SDLoc DL(Op);
6727 EVT VT = Op.getValueType();
6728 unsigned NumElements = VT.getVectorNumElements();
6729
6730 if (VSN->isSplat()) {
6731 SDValue Op0 = Op.getOperand(0);
6732 unsigned Index = VSN->getSplatIndex();
6733 assert(Index < VT.getVectorNumElements() &&
6734 "Splat index should be defined and in first operand");
6735 // See whether the value we're splatting is directly available as a scalar.
6736 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6738 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6739 // Otherwise keep it as a vector-to-vector operation.
6740 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6741 DAG.getTargetConstant(Index, DL, MVT::i32));
6742 }
6743
6744 GeneralShuffle GS(VT);
6745 for (unsigned I = 0; I < NumElements; ++I) {
6746 int Elt = VSN->getMaskElt(I);
6747 if (Elt < 0)
6748 GS.addUndef();
6749 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6750 unsigned(Elt) % NumElements))
6751 return SDValue();
6752 }
6753 return GS.getNode(DAG, SDLoc(VSN));
6754}
6755
6756SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6757 SelectionDAG &DAG) const {
6758 SDLoc DL(Op);
6759 // Just insert the scalar into element 0 of an undefined vector.
6760 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6761 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6762 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6763}
6764
6765// Shift the lower 2 bytes of Op to the left in order to insert into the
6766// upper 2 bytes of the FP register.
6768 assert(Op.getSimpleValueType() == MVT::i64 &&
6769 "Expexted to convert i64 to f16.");
6770 SDLoc DL(Op);
6771 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6772 DAG.getConstant(48, DL, MVT::i64));
6773 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6774 SDValue F16Val =
6775 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6776 return F16Val;
6777}
6778
6779// Extract Op into GPR and shift the 2 f16 bytes to the right.
6781 assert(Op.getSimpleValueType() == MVT::f16 &&
6782 "Expected to convert f16 to i64.");
6783 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6784 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6785 SDValue(U32, 0), Op);
6786 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6787 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6788 DAG.getConstant(48, DL, MVT::i32));
6789 return Shft;
6790}
6791
6793 auto *CIdx = dyn_cast<ConstantSDNode>(Idx);
6794 return CIdx && CIdx->getZExtValue() < VecVT.getVectorNumElements();
6795}
6796
6797SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6798 SelectionDAG &DAG) const {
6799 // Handle insertions of floating-point values.
6800 SDLoc DL(Op);
6801 SDValue Op0 = Op.getOperand(0);
6802 SDValue Op1 = Op.getOperand(1);
6803 SDValue Op2 = Op.getOperand(2);
6804 EVT VT = Op.getValueType();
6805
6806 // A constant index selects a GR128 subregister.
6807 if (!Subtarget.hasVector())
6808 return isInBoundsConstantVectorIndex(VT, Op2) ? Op : SDValue();
6809
6810 // Insertions into constant indices of a v2f64 can be done using VPDI.
6811 // However, if the inserted value is a bitcast or a constant then it's
6812 // better to use GPRs, as below.
6813 if (VT == MVT::v2f64 && Op1.getOpcode() != ISD::BITCAST &&
6814 Op1.getOpcode() != ISD::ConstantFP &&
6816 return Op;
6817
6818 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6819 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6820 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6821 SDValue IntOp1 =
6822 VT == MVT::v8f16
6823 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6824 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6825 SDValue Res =
6826 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6827 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6828 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6829}
6830
6831SDValue
6832SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6833 SelectionDAG &DAG) const {
6834 // Handle extractions of floating-point values.
6835 SDLoc DL(Op);
6836 SDValue Op0 = Op.getOperand(0);
6837 SDValue Op1 = Op.getOperand(1);
6838 EVT VT = Op.getValueType();
6839 EVT VecVT = Op0.getValueType();
6840
6841 // Extractions of constant indices can be done directly.
6842 if (isInBoundsConstantVectorIndex(VecVT, Op1))
6843 return Op;
6844
6845 if (!Subtarget.hasVector())
6846 return SDValue();
6847
6848 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6849 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6850 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6851 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6852 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6853 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6854 if (VT == MVT::f16)
6855 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6856 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6857}
6858
6859SDValue SystemZTargetLowering::
6860lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6861 SDValue PackedOp = Op.getOperand(0);
6862 EVT OutVT = Op.getValueType();
6863 EVT InVT = PackedOp.getValueType();
6864 unsigned ToBits = OutVT.getScalarSizeInBits();
6865 unsigned FromBits = InVT.getScalarSizeInBits();
6866 unsigned StartOffset = 0;
6867
6868 // If the input is a VECTOR_SHUFFLE, there are a number of important
6869 // cases where we can directly implement the sign-extension of the
6870 // original input lanes of the shuffle.
6871 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
6872 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
6873 ArrayRef<int> ShuffleMask = SVN->getMask();
6874 int OutNumElts = OutVT.getVectorNumElements();
6875
6876 // Recognize the special case where the sign-extension can be done
6877 // by the VSEG instruction. Handled via the default expander.
6878 if (ToBits == 64 && OutNumElts == 2) {
6879 int NumElem = ToBits / FromBits;
6880 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
6881 return SDValue();
6882 }
6883
6884 // Recognize the special case where we can fold the shuffle by
6885 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
6886 int StartOffsetCandidate = -1;
6887 for (int Elt = 0; Elt < OutNumElts; Elt++) {
6888 if (ShuffleMask[Elt] == -1)
6889 continue;
6890 if (ShuffleMask[Elt] % OutNumElts == Elt) {
6891 if (StartOffsetCandidate == -1)
6892 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
6893 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
6894 continue;
6895 }
6896 StartOffsetCandidate = -1;
6897 break;
6898 }
6899 if (StartOffsetCandidate != -1) {
6900 StartOffset = StartOffsetCandidate;
6901 PackedOp = PackedOp.getOperand(0);
6902 }
6903 }
6904
6905 do {
6906 FromBits *= 2;
6907 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
6908 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
6909 unsigned Opcode = SystemZISD::UNPACK_HIGH;
6910 if (StartOffset >= OutNumElts) {
6911 Opcode = SystemZISD::UNPACK_LOW;
6912 StartOffset -= OutNumElts;
6913 }
6914 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
6915 } while (FromBits != ToBits);
6916 return PackedOp;
6917}
6918
6919// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
6920SDValue SystemZTargetLowering::
6921lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6922 SDValue PackedOp = Op.getOperand(0);
6923 SDLoc DL(Op);
6924 EVT OutVT = Op.getValueType();
6925 EVT InVT = PackedOp.getValueType();
6926 unsigned InNumElts = InVT.getVectorNumElements();
6927 unsigned OutNumElts = OutVT.getVectorNumElements();
6928 unsigned NumInPerOut = InNumElts / OutNumElts;
6929
6930 SDValue ZeroVec =
6931 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
6932
6933 SmallVector<int, 16> Mask(InNumElts);
6934 unsigned ZeroVecElt = InNumElts;
6935 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
6936 unsigned MaskElt = PackedElt * NumInPerOut;
6937 unsigned End = MaskElt + NumInPerOut - 1;
6938 for (; MaskElt < End; MaskElt++)
6939 Mask[MaskElt] = ZeroVecElt++;
6940 Mask[MaskElt] = PackedElt;
6941 }
6942 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
6943 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
6944}
6945
6946SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
6947 unsigned ByScalar) const {
6948 // Look for cases where a vector shift can use the *_BY_SCALAR form.
6949 SDValue Op0 = Op.getOperand(0);
6950 SDValue Op1 = Op.getOperand(1);
6951 SDLoc DL(Op);
6952 EVT VT = Op.getValueType();
6953 unsigned ElemBitSize = VT.getScalarSizeInBits();
6954
6955 // See whether the shift vector is a splat represented as BUILD_VECTOR.
6956 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
6957 APInt SplatBits, SplatUndef;
6958 unsigned SplatBitSize;
6959 bool HasAnyUndefs;
6960 // Check for constant splats. Use ElemBitSize as the minimum element
6961 // width and reject splats that need wider elements.
6962 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6963 ElemBitSize, true) &&
6964 SplatBitSize == ElemBitSize) {
6965 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
6966 DL, MVT::i32);
6967 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6968 }
6969 // Check for variable splats.
6970 BitVector UndefElements;
6971 SDValue Splat = BVN->getSplatValue(&UndefElements);
6972 if (Splat) {
6973 // Since i32 is the smallest legal type, we either need a no-op
6974 // or a truncation.
6975 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
6976 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6977 }
6978 }
6979
6980 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
6981 // and the shift amount is directly available in a GPR.
6982 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
6983 if (VSN->isSplat()) {
6984 SDValue VSNOp0 = VSN->getOperand(0);
6985 unsigned Index = VSN->getSplatIndex();
6986 assert(Index < VT.getVectorNumElements() &&
6987 "Splat index should be defined and in first operand");
6988 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6989 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
6990 // Since i32 is the smallest legal type, we either need a no-op
6991 // or a truncation.
6992 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
6993 VSNOp0.getOperand(Index));
6994 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6995 }
6996 }
6997 }
6998
6999 // Otherwise just treat the current form as legal.
7000 return Op;
7001}
7002
7003SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
7004 SDLoc DL(Op);
7005
7006 // i128 FSHL with a constant amount that is a multiple of 8 can be
7007 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7008 // facility, FSHL with a constant amount less than 8 can be implemented
7009 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
7010 // combination of the two.
7011 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7012 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7013 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7014 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7015 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7016 if (ShiftAmt > 120) {
7017 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
7018 // SHR_DOUBLE_BIT emits fewer instructions.
7019 SDValue Val =
7020 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7021 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7022 return DAG.getBitcast(MVT::i128, Val);
7023 }
7024 SmallVector<int, 16> Mask(16);
7025 for (unsigned Elt = 0; Elt < 16; Elt++)
7026 Mask[Elt] = (ShiftAmt >> 3) + Elt;
7027 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7028 if ((ShiftAmt & 7) == 0)
7029 return DAG.getBitcast(MVT::i128, Shuf1);
7030 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
7031 SDValue Val =
7032 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
7033 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7034 return DAG.getBitcast(MVT::i128, Val);
7035 }
7036 }
7037
7038 return SDValue();
7039}
7040
7041SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
7042 SDLoc DL(Op);
7043
7044 // i128 FSHR with a constant amount that is a multiple of 8 can be
7045 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7046 // facility, FSHR with a constant amount less than 8 can be implemented
7047 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
7048 // combination of the two.
7049 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7050 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7051 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7052 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7053 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7054 if (ShiftAmt > 120) {
7055 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
7056 // SHL_DOUBLE_BIT emits fewer instructions.
7057 SDValue Val =
7058 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7059 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7060 return DAG.getBitcast(MVT::i128, Val);
7061 }
7062 SmallVector<int, 16> Mask(16);
7063 for (unsigned Elt = 0; Elt < 16; Elt++)
7064 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
7065 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7066 if ((ShiftAmt & 7) == 0)
7067 return DAG.getBitcast(MVT::i128, Shuf1);
7068 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
7069 SDValue Val =
7070 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
7071 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7072 return DAG.getBitcast(MVT::i128, Val);
7073 }
7074 }
7075
7076 return SDValue();
7077}
7078
7080 SDLoc DL(Op);
7081 SDValue Src = Op.getOperand(0);
7082 MVT DstVT = Op.getSimpleValueType();
7083
7085 unsigned SrcAS = N->getSrcAddressSpace();
7086
7087 assert(SrcAS != N->getDestAddressSpace() &&
7088 "addrspacecast must be between different address spaces");
7089
7090 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
7091 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
7092 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
7093 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
7094 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7095 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7096 } else if (DstVT == MVT::i32) {
7097 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7098 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7099 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7100 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7101 } else {
7102 report_fatal_error("Bad address space in addrspacecast");
7103 }
7104 return Op;
7105}
7106
7107SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7108 SelectionDAG &DAG) const {
7109 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7110 if (In.getSimpleValueType() != MVT::f16)
7111 return Op; // Legal
7112 return SDValue(); // Let legalizer emit the libcall.
7113}
7114
7116 MVT VT, SDValue Arg, SDLoc DL,
7117 SDValue Chain, bool IsStrict) const {
7118 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7119 MakeLibCallOptions CallOptions;
7120 SDValue Result;
7121 std::tie(Result, Chain) =
7122 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7123 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7124}
7125
7126SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7127 SelectionDAG &DAG) const {
7128 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7129 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7130 bool IsStrict = Op->isStrictFPOpcode();
7131 SDLoc DL(Op);
7132 MVT VT = Op.getSimpleValueType();
7133 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7134 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7135 EVT InVT = InOp.getValueType();
7136
7137 // FP to unsigned is not directly supported on z10. Promoting an i32
7138 // result to (signed) i64 doesn't generate an inexact condition (fp
7139 // exception) for values that are outside the i32 range but in the i64
7140 // range, so use the default expansion.
7141 if (!Subtarget.hasFPExtension() && !IsSigned)
7142 // Expand i32/i64. F16 values will be recognized to fit and extended.
7143 return SDValue();
7144
7145 // Conversion from f16 is done via f32.
7146 if (InOp.getSimpleValueType() == MVT::f16) {
7148 LowerOperationWrapper(Op.getNode(), Results, DAG);
7149 return DAG.getMergeValues(Results, DL);
7150 }
7151
7152 if (VT == MVT::i128) {
7153 RTLIB::Libcall LC =
7154 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7155 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7156 }
7157
7158 return Op; // Legal
7159}
7160
7161SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7162 SelectionDAG &DAG) const {
7163 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7164 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7165 bool IsStrict = Op->isStrictFPOpcode();
7166 SDLoc DL(Op);
7167 MVT VT = Op.getSimpleValueType();
7168 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7169 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7170 EVT InVT = InOp.getValueType();
7171
7172 // Conversion to f16 is done via f32.
7173 if (VT == MVT::f16) {
7175 LowerOperationWrapper(Op.getNode(), Results, DAG);
7176 return DAG.getMergeValues(Results, DL);
7177 }
7178
7179 // Unsigned to fp is not directly supported on z10.
7180 if (!Subtarget.hasFPExtension() && !IsSigned)
7181 return SDValue(); // Expand i64.
7182
7183 if (InVT == MVT::i128) {
7184 RTLIB::Libcall LC =
7185 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7186 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7187 }
7188
7189 return Op; // Legal
7190}
7191
7192// Lower an f16 LOAD in case of no vector support.
7193SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7194 SelectionDAG &DAG) const {
7195 EVT RegVT = Op.getValueType();
7196 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7197 (void)RegVT;
7198
7199 // Load as integer.
7200 SDLoc DL(Op);
7201 SDValue NewLd;
7202 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7203 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7204 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7205 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7206 AtomicLd->getMemOperand());
7207 } else {
7208 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7209 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7210 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7211 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7212 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7213 }
7214 SDValue F16Val = convertToF16(NewLd, DAG);
7215 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7216}
7217
7218// Lower an f16 STORE in case of no vector support.
7219SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7220 SelectionDAG &DAG) const {
7221 SDLoc DL(Op);
7222 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7223
7224 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7225 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7226 Shft, AtomicSt->getBasePtr(),
7227 AtomicSt->getMemOperand());
7228
7229 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7230 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7231 St->getMemOperand());
7232}
7233
7234SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7235 SelectionDAG &DAG) const {
7236 SDLoc DL(Op);
7237 MVT ResultVT = Op.getSimpleValueType();
7238 SDValue Arg = Op.getOperand(0);
7239 unsigned Check = Op.getConstantOperandVal(1);
7240
7241 unsigned TDCMask = 0;
7242 if (Check & fcSNan)
7244 if (Check & fcQNan)
7246 if (Check & fcPosInf)
7248 if (Check & fcNegInf)
7250 if (Check & fcPosNormal)
7252 if (Check & fcNegNormal)
7254 if (Check & fcPosSubnormal)
7256 if (Check & fcNegSubnormal)
7258 if (Check & fcPosZero)
7259 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7260 if (Check & fcNegZero)
7261 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7262 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7263
7264 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7265 return getCCResult(DAG, Intr);
7266}
7267
7268SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7269 SelectionDAG &DAG) const {
7270 SDLoc DL(Op);
7271 SDValue Chain = Op.getOperand(0);
7272
7273 // STCKF only supports a memory operand, so we have to use a temporary.
7274 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7275 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7276 MachinePointerInfo MPI =
7278
7279 // Use STCFK to store the TOD clock into the temporary.
7280 SDValue StoreOps[] = {Chain, StackPtr};
7281 Chain = DAG.getMemIntrinsicNode(
7282 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7283 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7284
7285 // And read it back from there.
7286 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7287}
7288
7290 SelectionDAG &DAG) const {
7291 switch (Op.getOpcode()) {
7292 case ISD::FRAMEADDR:
7293 return lowerFRAMEADDR(Op, DAG);
7294 case ISD::RETURNADDR:
7295 return lowerRETURNADDR(Op, DAG);
7296 case ISD::BR_CC:
7297 return lowerBR_CC(Op, DAG);
7298 case ISD::SELECT_CC:
7299 return lowerSELECT_CC(Op, DAG);
7300 case ISD::SETCC:
7301 return lowerSETCC(Op, DAG);
7302 case ISD::STRICT_FSETCC:
7303 return lowerSTRICT_FSETCC(Op, DAG, false);
7305 return lowerSTRICT_FSETCC(Op, DAG, true);
7306 case ISD::GlobalAddress:
7307 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7309 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7310 case ISD::BlockAddress:
7311 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7312 case ISD::JumpTable:
7313 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7314 case ISD::ConstantPool:
7315 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7316 case ISD::BITCAST:
7317 return lowerBITCAST(Op, DAG);
7318 case ISD::VASTART:
7319 return lowerVASTART(Op, DAG);
7320 case ISD::VACOPY:
7321 return lowerVACOPY(Op, DAG);
7323 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7325 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7326 case ISD::MULHS:
7327 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7328 case ISD::MULHU:
7329 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7330 case ISD::SMUL_LOHI:
7331 return lowerSMUL_LOHI(Op, DAG);
7332 case ISD::UMUL_LOHI:
7333 return lowerUMUL_LOHI(Op, DAG);
7334 case ISD::SDIVREM:
7335 return lowerSDIVREM(Op, DAG);
7336 case ISD::UDIVREM:
7337 return lowerUDIVREM(Op, DAG);
7338 case ISD::SADDO:
7339 case ISD::SSUBO:
7340 case ISD::UADDO:
7341 case ISD::USUBO:
7342 return lowerXALUO(Op, DAG);
7343 case ISD::UADDO_CARRY:
7344 case ISD::USUBO_CARRY:
7345 return lowerUADDSUBO_CARRY(Op, DAG);
7346 case ISD::OR:
7347 return lowerOR(Op, DAG);
7348 case ISD::CTPOP:
7349 return lowerCTPOP(Op, DAG);
7350 case ISD::VECREDUCE_ADD:
7351 return lowerVECREDUCE_ADD(Op, DAG);
7352 case ISD::ATOMIC_FENCE:
7353 return lowerATOMIC_FENCE(Op, DAG);
7354 case ISD::ATOMIC_STORE:
7355 return lowerATOMIC_STORE(Op, DAG);
7356 case ISD::ATOMIC_LOAD:
7357 return lowerATOMIC_LOAD(Op, DAG);
7359 return lowerATOMIC_LOAD_SUB(Op, DAG);
7361 return lowerATOMIC_CMP_SWAP(Op, DAG);
7362 case ISD::STACKSAVE:
7363 return lowerSTACKSAVE(Op, DAG);
7364 case ISD::STACKRESTORE:
7365 return lowerSTACKRESTORE(Op, DAG);
7366 case ISD::PREFETCH:
7367 return lowerPREFETCH(Op, DAG);
7369 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7371 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7372 case ISD::BUILD_VECTOR:
7373 return lowerBUILD_VECTOR(Op, DAG);
7375 return lowerVECTOR_SHUFFLE(Op, DAG);
7377 return lowerSCALAR_TO_VECTOR(Op, DAG);
7379 return lowerINSERT_VECTOR_ELT(Op, DAG);
7381 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7383 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7385 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7386 case ISD::SHL:
7387 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7388 case ISD::SRL:
7389 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7390 case ISD::SRA:
7391 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7392 case ISD::ADDRSPACECAST:
7393 return lowerAddrSpaceCast(Op, DAG);
7394 case ISD::ROTL:
7395 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7396 case ISD::FSHL:
7397 return lowerFSHL(Op, DAG);
7398 case ISD::FSHR:
7399 return lowerFSHR(Op, DAG);
7400 case ISD::FP_EXTEND:
7402 return lowerFP_EXTEND(Op, DAG);
7403 case ISD::FP_TO_UINT:
7404 case ISD::FP_TO_SINT:
7407 return lower_FP_TO_INT(Op, DAG);
7408 case ISD::UINT_TO_FP:
7409 case ISD::SINT_TO_FP:
7412 return lower_INT_TO_FP(Op, DAG);
7413 case ISD::LOAD:
7414 return lowerLoadF16(Op, DAG);
7415 case ISD::STORE:
7416 return lowerStoreF16(Op, DAG);
7417 case ISD::IS_FPCLASS:
7418 return lowerIS_FPCLASS(Op, DAG);
7419 case ISD::GET_ROUNDING:
7420 return lowerGET_ROUNDING(Op, DAG);
7422 return lowerREADCYCLECOUNTER(Op, DAG);
7425 // These operations are legal on our platform, but we cannot actually
7426 // set the operation action to Legal as common code would treat this
7427 // as equivalent to Expand. Instead, we keep the operation action to
7428 // Custom and just leave them unchanged here.
7429 return Op;
7430
7431 default:
7432 llvm_unreachable("Unexpected node to lower");
7433 }
7434}
7435
7437 const SDLoc &SL) {
7438 // If i128 is legal, just use a normal bitcast.
7439 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7440 return DAG.getBitcast(MVT::f128, Src);
7441
7442 // Otherwise, f128 must live in FP128, so do a partwise move.
7444 &SystemZ::FP128BitRegClass);
7445
7446 SDValue Hi, Lo;
7447 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7448
7449 Hi = DAG.getBitcast(MVT::f64, Hi);
7450 Lo = DAG.getBitcast(MVT::f64, Lo);
7451
7452 SDNode *Pair = DAG.getMachineNode(
7453 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7454 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7455 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7456 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7457 return SDValue(Pair, 0);
7458}
7459
7461 const SDLoc &SL) {
7462 // If i128 is legal, just use a normal bitcast.
7463 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7464 return DAG.getBitcast(MVT::i128, Src);
7465
7466 // Otherwise, f128 must live in FP128, so do a partwise move.
7468 &SystemZ::FP128BitRegClass);
7469
7470 SDValue LoFP =
7471 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7472 SDValue HiFP =
7473 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7474 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7475 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7476
7477 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7478}
7479
7480// Lower operations with invalid operand or result types.
7481void
7484 SelectionDAG &DAG) const {
7485 switch (N->getOpcode()) {
7486 case ISD::ATOMIC_LOAD: {
7487 SDLoc DL(N);
7488 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7489 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7490 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7491 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7492 DL, Tys, Ops, MVT::i128, MMO);
7493
7494 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7495 if (N->getValueType(0) == MVT::f128)
7496 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7497 Results.push_back(Lowered);
7498 Results.push_back(Res.getValue(1));
7499 break;
7500 }
7501 case ISD::ATOMIC_STORE: {
7502 SDLoc DL(N);
7503 SDVTList Tys = DAG.getVTList(MVT::Other);
7504 SDValue Val = N->getOperand(1);
7505 if (Val.getValueType() == MVT::f128)
7506 Val = expandBitCastF128ToI128(DAG, Val, DL);
7507 Val = lowerI128ToGR128(DAG, Val);
7508
7509 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7510 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7511 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7512 DL, Tys, Ops, MVT::i128, MMO);
7513 // We have to enforce sequential consistency by performing a
7514 // serialization operation after the store.
7515 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7517 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7518 MVT::Other, Res), 0);
7519 Results.push_back(Res);
7520 break;
7521 }
7523 SDLoc DL(N);
7524 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
7525 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7526 lowerI128ToGR128(DAG, N->getOperand(2)),
7527 lowerI128ToGR128(DAG, N->getOperand(3)) };
7528 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7529 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7530 DL, Tys, Ops, MVT::i128, MMO);
7531 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7533 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7534 Results.push_back(lowerGR128ToI128(DAG, Res));
7535 Results.push_back(Success);
7536 Results.push_back(Res.getValue(2));
7537 break;
7538 }
7539 case ISD::BITCAST: {
7540 if (useSoftFloat())
7541 return;
7542 SDLoc DL(N);
7543 SDValue Src = N->getOperand(0);
7544 EVT SrcVT = Src.getValueType();
7545 EVT ResVT = N->getValueType(0);
7546 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7547 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7548 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7549 if (Subtarget.hasVector()) {
7550 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7551 Results.push_back(SDValue(
7552 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7553 } else {
7554 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7555 Results.push_back(convertToF16(In64, DAG));
7556 }
7557 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7558 SDValue ExtractedVal =
7559 Subtarget.hasVector()
7560 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7561 0)
7562 : convertFromF16(Src, DL, DAG);
7563 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7564 }
7565 break;
7566 }
7567 case ISD::UINT_TO_FP:
7568 case ISD::SINT_TO_FP:
7571 if (useSoftFloat())
7572 return;
7573 bool IsStrict = N->isStrictFPOpcode();
7574 SDLoc DL(N);
7575 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7576 EVT ResVT = N->getValueType(0);
7577 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7578 if (ResVT == MVT::f16) {
7579 if (!IsStrict) {
7580 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7581 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7582 } else {
7583 SDValue OpF32 =
7584 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7585 {Chain, InOp});
7586 SDValue F16Res;
7587 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7588 OpF32, OpF32.getValue(1), DL, MVT::f16);
7589 Results.push_back(F16Res);
7590 Results.push_back(Chain);
7591 }
7592 }
7593 break;
7594 }
7595 case ISD::FP_TO_UINT:
7596 case ISD::FP_TO_SINT:
7599 if (useSoftFloat())
7600 return;
7601 bool IsStrict = N->isStrictFPOpcode();
7602 SDLoc DL(N);
7603 EVT ResVT = N->getValueType(0);
7604 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7605 EVT InVT = InOp->getValueType(0);
7606 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7607 if (InVT == MVT::f16) {
7608 if (!IsStrict) {
7609 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7610 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7611 } else {
7612 SDValue InF32;
7613 std::tie(InF32, Chain) =
7614 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7615 SDValue OpF32 =
7616 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7617 {Chain, InF32});
7618 Results.push_back(OpF32);
7619 Results.push_back(OpF32.getValue(1));
7620 }
7621 }
7622 break;
7623 }
7624 case ISD::ATOMIC_SWAP:
7625 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_SWAPW);
7626 break;
7628 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7629 break;
7631 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_SUB);
7632 break;
7634 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_AND);
7635 break;
7637 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_OR);
7638 break;
7640 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7641 break;
7643 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7644 break;
7646 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7647 break;
7649 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7650 break;
7652 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7653 break;
7655 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7656 break;
7657 default:
7658 llvm_unreachable("Unexpected node to lower");
7659 }
7660}
7661
7662void
7668
7669// Return true if VT is a vector whose elements are a whole number of bytes
7670// in width. Also check for presence of vector support.
7671bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7672 if (!Subtarget.hasVector())
7673 return false;
7674
7675 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7676}
7677
7678// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7679// producing a result of type ResVT. Op is a possibly bitcast version
7680// of the input vector and Index is the index (based on type VecVT) that
7681// should be extracted. Return the new extraction if a simplification
7682// was possible or if Force is true.
7683SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7684 EVT VecVT, SDValue Op,
7685 unsigned Index,
7686 DAGCombinerInfo &DCI,
7687 bool Force) const {
7688 SelectionDAG &DAG = DCI.DAG;
7689
7690 // The number of bytes being extracted.
7691 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7692
7693 for (;;) {
7694 unsigned Opcode = Op.getOpcode();
7695 if (Opcode == ISD::BITCAST)
7696 // Look through bitcasts.
7697 Op = Op.getOperand(0);
7698 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7699 canTreatAsByteVector(Op.getValueType())) {
7700 // Get a VPERM-like permute mask and see whether the bytes covered
7701 // by the extracted element are a contiguous sequence from one
7702 // source operand.
7704 if (!getVPermMask(Op, Bytes))
7705 break;
7706 int First;
7707 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7708 BytesPerElement, First))
7709 break;
7710 if (First < 0)
7711 return DAG.getUNDEF(ResVT);
7712 // Make sure the contiguous sequence starts at a multiple of the
7713 // original element size.
7714 unsigned Byte = unsigned(First) % Bytes.size();
7715 if (Byte % BytesPerElement != 0)
7716 break;
7717 // We can get the extracted value directly from an input.
7718 Index = Byte / BytesPerElement;
7719 Op = Op.getOperand(unsigned(First) / Bytes.size());
7720 Force = true;
7721 } else if (Opcode == ISD::BUILD_VECTOR &&
7722 canTreatAsByteVector(Op.getValueType())) {
7723 // We can only optimize this case if the BUILD_VECTOR elements are
7724 // at least as wide as the extracted value.
7725 EVT OpVT = Op.getValueType();
7726 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7727 if (OpBytesPerElement < BytesPerElement)
7728 break;
7729 // Make sure that the least-significant bit of the extracted value
7730 // is the least significant bit of an input.
7731 unsigned End = (Index + 1) * BytesPerElement;
7732 if (End % OpBytesPerElement != 0)
7733 break;
7734 // We're extracting the low part of one operand of the BUILD_VECTOR.
7735 Op = Op.getOperand(End / OpBytesPerElement - 1);
7736 EVT ResIntVT = MVT::getIntegerVT(ResVT.getSizeInBits());
7737 if (!isTypeLegal(ResIntVT))
7738 break;
7739 if (!Op.getValueType().isInteger()) {
7740 EVT OpIntVT = MVT::getIntegerVT(Op.getValueSizeInBits());
7741 if (!isTypeLegal(OpIntVT))
7742 break;
7743 Op = DAG.getNode(ISD::BITCAST, DL, OpIntVT, Op);
7744 DCI.AddToWorklist(Op.getNode());
7745 }
7746 Op = DAG.getNode(ISD::TRUNCATE, DL, ResIntVT, Op);
7747 if (ResIntVT != ResVT) {
7748 DCI.AddToWorklist(Op.getNode());
7749 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7750 }
7751 return Op;
7752 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7754 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7755 canTreatAsByteVector(Op.getValueType()) &&
7756 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7757 // Make sure that only the unextended bits are significant.
7758 EVT ExtVT = Op.getValueType();
7759 EVT OpVT = Op.getOperand(0).getValueType();
7760 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7761 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7762 unsigned Byte = Index * BytesPerElement;
7763 unsigned SubByte = Byte % ExtBytesPerElement;
7764 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7765 if (SubByte < MinSubByte ||
7766 SubByte + BytesPerElement > ExtBytesPerElement)
7767 break;
7768 // Get the byte offset of the unextended element
7769 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7770 // ...then add the byte offset relative to that element.
7771 Byte += SubByte - MinSubByte;
7772 if (Byte % BytesPerElement != 0)
7773 break;
7774 Op = Op.getOperand(0);
7775 Index = Byte / BytesPerElement;
7776 Force = true;
7777 } else
7778 break;
7779 }
7780 if (Force) {
7781 if (Op.getValueType() != VecVT) {
7782 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7783 DCI.AddToWorklist(Op.getNode());
7784 }
7785 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7786 DAG.getConstant(Index, DL, MVT::i32));
7787 }
7788 return SDValue();
7789}
7790
7791// Optimize vector operations in scalar value Op on the basis that Op
7792// is truncated to TruncVT.
7793SDValue SystemZTargetLowering::combineTruncateExtract(
7794 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7795 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7796 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7797 // of type TruncVT.
7798 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7799 TruncVT.getSizeInBits() % 8 == 0) {
7800 SDValue Vec = Op.getOperand(0);
7801 EVT VecVT = Vec.getValueType();
7802 if (canTreatAsByteVector(VecVT)) {
7803 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7804 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7805 unsigned TruncBytes = TruncVT.getStoreSize();
7806 if (BytesPerElement % TruncBytes == 0) {
7807 // Calculate the value of Y' in the above description. We are
7808 // splitting the original elements into Scale equal-sized pieces
7809 // and for truncation purposes want the last (least-significant)
7810 // of these pieces for IndexN. This is easiest to do by calculating
7811 // the start index of the following element and then subtracting 1.
7812 unsigned Scale = BytesPerElement / TruncBytes;
7813 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7814
7815 // Defer the creation of the bitcast from X to combineExtract,
7816 // which might be able to optimize the extraction.
7817 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7818 MVT::getIntegerVT(TruncBytes * 8),
7819 VecVT.getStoreSize() / TruncBytes);
7820 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7821 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7822 }
7823 }
7824 }
7825 }
7826 return SDValue();
7827}
7828
7829SDValue SystemZTargetLowering::combineZERO_EXTEND(
7830 SDNode *N, DAGCombinerInfo &DCI) const {
7831 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7832 SelectionDAG &DAG = DCI.DAG;
7833 SDValue N0 = N->getOperand(0);
7834 EVT VT = N->getValueType(0);
7835 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7836 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7837 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7838 if (TrueOp && FalseOp) {
7839 SDLoc DL(N0);
7840 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7841 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7842 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7843 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7844 // If N0 has multiple uses, change other uses as well.
7845 if (!N0.hasOneUse()) {
7846 SDValue TruncSelect =
7847 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7848 DCI.CombineTo(N0.getNode(), TruncSelect);
7849 }
7850 return NewSelect;
7851 }
7852 }
7853 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7854 // of the result is smaller than the size of X and all the truncated bits
7855 // of X are already zero.
7856 if (N0.getOpcode() == ISD::XOR &&
7857 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7858 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7859 N0.getOperand(1).getOpcode() == ISD::Constant) {
7860 SDValue X = N0.getOperand(0).getOperand(0);
7861 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
7862 KnownBits Known = DAG.computeKnownBits(X);
7863 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
7864 N0.getValueSizeInBits(),
7865 VT.getSizeInBits());
7866 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7867 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7868 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
7869 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
7870 X, DAG.getConstant(Mask, SDLoc(N0), VT));
7871 }
7872 }
7873 }
7874 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
7875 // and VECTOR ADD COMPUTE CARRY for i128:
7876 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
7877 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
7878 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
7879 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
7880 // For vector types, these patterns are recognized in the .td file.
7881 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
7882 N0.getOperand(0).getValueType() == VT) {
7883 SDValue Op0 = N0.getOperand(0);
7884 SDValue Op1 = N0.getOperand(1);
7885 const ISD::CondCode CC = N0.getOperandCondCode(2);
7886 switch (CC) {
7887 case ISD::SETULE:
7888 std::swap(Op0, Op1);
7889 [[fallthrough]];
7890 case ISD::SETUGE:
7891 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
7892 case ISD::SETUGT:
7893 std::swap(Op0, Op1);
7894 [[fallthrough]];
7895 case ISD::SETULT:
7896 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
7897 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
7898 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
7899 Op0->getOperand(1));
7900 break;
7901 default:
7902 break;
7903 }
7904 }
7905
7906 return SDValue();
7907}
7908
7909SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
7910 SDNode *N, DAGCombinerInfo &DCI) const {
7911 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
7912 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
7913 // into (select_cc LHS, RHS, -1, 0, COND)
7914 SelectionDAG &DAG = DCI.DAG;
7915 SDValue N0 = N->getOperand(0);
7916 EVT VT = N->getValueType(0);
7917 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7918 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
7919 N0 = N0.getOperand(0);
7920 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
7921 SDLoc DL(N0);
7922 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
7923 DAG.getAllOnesConstant(DL, VT),
7924 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
7925 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
7926 }
7927 return SDValue();
7928}
7929
7930SDValue SystemZTargetLowering::combineSIGN_EXTEND(
7931 SDNode *N, DAGCombinerInfo &DCI) const {
7932 // Convert (sext (ashr (shl X, C1), C2)) to
7933 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
7934 // cheap as narrower ones.
7935 SelectionDAG &DAG = DCI.DAG;
7936 SDValue N0 = N->getOperand(0);
7937 EVT VT = N->getValueType(0);
7938 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
7939 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7940 SDValue Inner = N0.getOperand(0);
7941 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
7942 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
7943 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
7944 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
7945 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
7946 EVT ShiftVT = N0.getOperand(1).getValueType();
7947 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
7948 Inner.getOperand(0));
7949 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
7950 DAG.getConstant(NewShlAmt, SDLoc(Inner),
7951 ShiftVT));
7952 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
7953 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
7954 }
7955 }
7956 }
7957
7958 return SDValue();
7959}
7960
7961SDValue SystemZTargetLowering::combineMERGE(
7962 SDNode *N, DAGCombinerInfo &DCI) const {
7963 SelectionDAG &DAG = DCI.DAG;
7964 unsigned Opcode = N->getOpcode();
7965 SDValue Op0 = N->getOperand(0);
7966 SDValue Op1 = N->getOperand(1);
7967 if (Op0.getOpcode() == ISD::BITCAST)
7968 Op0 = Op0.getOperand(0);
7970 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
7971 // for v4f32.
7972 if (Op1 == N->getOperand(0))
7973 return Op1;
7974 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
7975 EVT VT = Op1.getValueType();
7976 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
7977 if (ElemBytes <= 4) {
7978 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
7979 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
7980 EVT InVT = VT.changeVectorElementTypeToInteger();
7981 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
7982 SystemZ::VectorBytes / ElemBytes / 2);
7983 if (VT != InVT) {
7984 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
7985 DCI.AddToWorklist(Op1.getNode());
7986 }
7987 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
7988 DCI.AddToWorklist(Op.getNode());
7989 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7990 }
7991 }
7992 return SDValue();
7993}
7994
7995static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
7996 SDNode *&HiPart) {
7997 LoPart = HiPart = nullptr;
7998
7999 // Scan through all users.
8000 for (SDUse &Use : LD->uses()) {
8001 // Skip the uses of the chain.
8002 if (Use.getResNo() != 0)
8003 continue;
8004
8005 // Verify every user is a TRUNCATE to i64 of the low or high half.
8006 SDNode *User = Use.getUser();
8007 bool IsLoPart = true;
8008 if (User->getOpcode() == ISD::SRL &&
8009 User->getOperand(1).getOpcode() == ISD::Constant &&
8010 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
8011 User = *User->user_begin();
8012 IsLoPart = false;
8013 }
8014 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
8015 return false;
8016
8017 if (IsLoPart) {
8018 if (LoPart)
8019 return false;
8020 LoPart = User;
8021 } else {
8022 if (HiPart)
8023 return false;
8024 HiPart = User;
8025 }
8026 }
8027 return true;
8028}
8029
8030static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8031 SDNode *&HiPart) {
8032 LoPart = HiPart = nullptr;
8033
8034 // Scan through all users.
8035 for (SDUse &Use : LD->uses()) {
8036 // Skip the uses of the chain.
8037 if (Use.getResNo() != 0)
8038 continue;
8039
8040 // Verify every user is an EXTRACT_SUBREG of the low or high half.
8041 SDNode *User = Use.getUser();
8042 if (!User->hasOneUse() || !User->isMachineOpcode() ||
8043 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
8044 return false;
8045
8046 switch (User->getConstantOperandVal(1)) {
8047 case SystemZ::subreg_l64:
8048 if (LoPart)
8049 return false;
8050 LoPart = User;
8051 break;
8052 case SystemZ::subreg_h64:
8053 if (HiPart)
8054 return false;
8055 HiPart = User;
8056 break;
8057 default:
8058 return false;
8059 }
8060 }
8061 return true;
8062}
8063
8064SDValue SystemZTargetLowering::combineLOAD(
8065 SDNode *N, DAGCombinerInfo &DCI) const {
8066 SelectionDAG &DAG = DCI.DAG;
8067 EVT LdVT = N->getValueType(0);
8068 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
8069 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
8070 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8071 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
8072 if (PtrVT != LoadNodeVT) {
8073 SDLoc DL(LN);
8074 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
8075 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
8076 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
8077 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
8078 LN->getMemOperand());
8079 }
8080 }
8081 }
8082 SDLoc DL(N);
8083
8084 // Replace a 128-bit load that is used solely to move its value into GPRs
8085 // by separate loads of both halves.
8086 LoadSDNode *LD = cast<LoadSDNode>(N);
8087 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
8088 SDNode *LoPart, *HiPart;
8089 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
8090 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
8091 // Rewrite each extraction as an independent load.
8092 SmallVector<SDValue, 2> ArgChains;
8093 if (HiPart) {
8094 SDValue EltLoad = DAG.getLoad(
8095 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
8096 LD->getPointerInfo(), LD->getBaseAlign(),
8097 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8098
8099 DCI.CombineTo(HiPart, EltLoad, true);
8100 ArgChains.push_back(EltLoad.getValue(1));
8101 }
8102 if (LoPart) {
8103 SDValue EltLoad = DAG.getLoad(
8104 LoPart->getValueType(0), DL, LD->getChain(),
8105 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
8106 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
8107 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8108
8109 DCI.CombineTo(LoPart, EltLoad, true);
8110 ArgChains.push_back(EltLoad.getValue(1));
8111 }
8112
8113 // Collect all chains via TokenFactor.
8114 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8115 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8116 DCI.AddToWorklist(Chain.getNode());
8117 return SDValue(N, 0);
8118 }
8119 }
8120
8121 if (LdVT.isVector() || LdVT.isInteger())
8122 return SDValue();
8123 // Transform a scalar load that is REPLICATEd as well as having other
8124 // use(s) to the form where the other use(s) use the first element of the
8125 // REPLICATE instead of the load. Otherwise instruction selection will not
8126 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8127 // point loads.
8128
8129 SDValue Replicate;
8130 SmallVector<SDNode*, 8> OtherUses;
8131 for (SDUse &Use : N->uses()) {
8132 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8133 if (Replicate)
8134 return SDValue(); // Should never happen
8135 Replicate = SDValue(Use.getUser(), 0);
8136 } else if (Use.getResNo() == 0)
8137 OtherUses.push_back(Use.getUser());
8138 }
8139 if (!Replicate || OtherUses.empty())
8140 return SDValue();
8141
8142 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8143 Replicate, DAG.getConstant(0, DL, MVT::i32));
8144 // Update uses of the loaded Value while preserving old chains.
8145 for (SDNode *U : OtherUses) {
8147 for (SDValue Op : U->ops())
8148 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8149 DAG.UpdateNodeOperands(U, Ops);
8150 }
8151 return SDValue(N, 0);
8152}
8153
8154bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8155 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8156 return true;
8157 if (Subtarget.hasVectorEnhancements2())
8158 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8159 return true;
8160 return false;
8161}
8162
8164 if (!VT.isVector() || !VT.isSimple() ||
8165 VT.getSizeInBits() != 128 ||
8166 VT.getScalarSizeInBits() % 8 != 0)
8167 return false;
8168
8169 unsigned NumElts = VT.getVectorNumElements();
8170 for (unsigned i = 0; i < NumElts; ++i) {
8171 if (M[i] < 0) continue; // ignore UNDEF indices
8172 if ((unsigned) M[i] != NumElts - 1 - i)
8173 return false;
8174 }
8175
8176 return true;
8177}
8178
8179static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8180 for (auto *U : StoredVal->users()) {
8181 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8182 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8183 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8184 continue;
8185 } else if (isa<BuildVectorSDNode>(U)) {
8186 SDValue BuildVector = SDValue(U, 0);
8187 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8188 isOnlyUsedByStores(BuildVector, DAG))
8189 continue;
8190 }
8191 return false;
8192 }
8193 return true;
8194}
8195
8196static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8197 SDValue &HiPart) {
8198 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8199 return false;
8200
8201 SDValue Op0 = Val.getOperand(0);
8202 SDValue Op1 = Val.getOperand(1);
8203
8204 if (Op0.getOpcode() == ISD::SHL)
8205 std::swap(Op0, Op1);
8206 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8207 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8208 Op1.getConstantOperandVal(1) != 64)
8209 return false;
8210 Op1 = Op1.getOperand(0);
8211
8212 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8213 Op0.getOperand(0).getValueType() != MVT::i64)
8214 return false;
8215 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8216 Op1.getOperand(0).getValueType() != MVT::i64)
8217 return false;
8218
8219 LoPart = Op0.getOperand(0);
8220 HiPart = Op1.getOperand(0);
8221 return true;
8222}
8223
8224static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8225 SDValue &HiPart) {
8226 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8227 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8228 return false;
8229
8230 if (Val->getNumOperands() != 5 ||
8231 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8232 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8233 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8234 return false;
8235
8236 LoPart = Val->getOperand(1);
8237 HiPart = Val->getOperand(3);
8238 return true;
8239}
8240
8241SDValue SystemZTargetLowering::combineSTORE(
8242 SDNode *N, DAGCombinerInfo &DCI) const {
8243 SelectionDAG &DAG = DCI.DAG;
8244 auto *SN = cast<StoreSDNode>(N);
8245 auto &Op1 = N->getOperand(1);
8246 EVT MemVT = SN->getMemoryVT();
8247
8248 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8249 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8250 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8251 if (PtrVT != StoreNodeVT) {
8252 SDLoc DL(SN);
8253 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8254 SYSTEMZAS::PTR32, 0);
8255 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8256 SN->getPointerInfo(), SN->getBaseAlign(),
8257 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8258 }
8259 }
8260
8261 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8262 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8263 // If X has wider elements then convert it to:
8264 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8265 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8266 if (SDValue Value =
8267 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8268 DCI.AddToWorklist(Value.getNode());
8269
8270 // Rewrite the store with the new form of stored value.
8271 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8272 SN->getBasePtr(), SN->getMemoryVT(),
8273 SN->getMemOperand());
8274 }
8275 }
8276
8277 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8278 if (Op1->isMachineOpcode() &&
8279 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8280 // Obtain the frame index the store was targeting.
8281 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8282 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8283 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8284 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8285 }
8286
8287 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8288 if (!SN->isTruncatingStore() &&
8289 Op1.getOpcode() == ISD::BSWAP &&
8290 Op1.getNode()->hasOneUse() &&
8291 canLoadStoreByteSwapped(Op1.getValueType())) {
8292
8293 SDValue BSwapOp = Op1.getOperand(0);
8294
8295 if (BSwapOp.getValueType() == MVT::i16)
8296 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8297
8298 SDValue Ops[] = {
8299 N->getOperand(0), BSwapOp, N->getOperand(2)
8300 };
8301
8302 return
8303 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8304 Ops, MemVT, SN->getMemOperand());
8305 }
8306 // Combine STORE (element-swap) into VSTER
8307 if (!SN->isTruncatingStore() &&
8308 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8309 Op1.getNode()->hasOneUse() &&
8310 Subtarget.hasVectorEnhancements2()) {
8311 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8312 ArrayRef<int> ShuffleMask = SVN->getMask();
8313 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8314 SDValue Ops[] = {
8315 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8316 };
8317
8318 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8319 DAG.getVTList(MVT::Other),
8320 Ops, MemVT, SN->getMemOperand());
8321 }
8322 }
8323
8324 // Combine STORE (READCYCLECOUNTER) into STCKF.
8325 if (!SN->isTruncatingStore() &&
8327 Op1.hasOneUse() &&
8328 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8329 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8330 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8331 DAG.getVTList(MVT::Other),
8332 Ops, MemVT, SN->getMemOperand());
8333 }
8334
8335 // Transform a store of a 128-bit value moved from parts into two stores.
8336 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8337 SDValue LoPart, HiPart;
8338 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8339 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8340 SDLoc DL(SN);
8341 SDValue Chain0 = DAG.getStore(
8342 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8343 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8344 SDValue Chain1 = DAG.getStore(
8345 SN->getChain(), DL, LoPart,
8346 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8347 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8348 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8349
8350 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8351 }
8352 }
8353
8354 // Replicate a reg or immediate with VREP instead of scalar multiply or
8355 // immediate load. It seems best to do this during the first DAGCombine as
8356 // it is straight-forward to handle the zero-extend node in the initial
8357 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8358 // extracting an i16 element from a v16i8 vector).
8359 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8360 isOnlyUsedByStores(Op1, DAG)) {
8361 SDValue Word = SDValue();
8362 EVT WordVT;
8363
8364 // Find a replicated immediate and return it if found in Word and its
8365 // type in WordVT.
8366 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8367 // Some constants are better handled with a scalar store.
8368 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8369 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8370 return;
8371
8372 APInt Val = C->getAPIntValue();
8373 // Truncate Val in case of a truncating store.
8374 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8375 assert(SN->isTruncatingStore() &&
8376 "Non-truncating store and immediate value does not fit?");
8377 Val = Val.trunc(TotBytes * 8);
8378 }
8379
8380 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8381 if (VCI.isVectorConstantLegal(Subtarget) &&
8382 VCI.Opcode == SystemZISD::REPLICATE) {
8383 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8384 WordVT = VCI.VecVT.getScalarType();
8385 }
8386 };
8387
8388 // Find a replicated register and return it if found in Word and its type
8389 // in WordVT.
8390 auto FindReplicatedReg = [&](SDValue MulOp) {
8391 EVT MulVT = MulOp.getValueType();
8392 if (MulOp->getOpcode() == ISD::MUL &&
8393 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8394 // Find a zero extended value and its type.
8395 SDValue LHS = MulOp->getOperand(0);
8396 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8397 WordVT = LHS->getOperand(0).getValueType();
8398 else if (LHS->getOpcode() == ISD::AssertZext)
8399 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8400 else
8401 return;
8402 // Find a replicating constant, e.g. 0x00010001.
8403 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8404 SystemZVectorConstantInfo VCI(
8405 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8406 if (VCI.isVectorConstantLegal(Subtarget) &&
8407 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8408 WordVT == VCI.VecVT.getScalarType())
8409 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8410 }
8411 }
8412 };
8413
8414 if (isa<BuildVectorSDNode>(Op1) &&
8415 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8416 SDValue SplatVal = Op1->getOperand(0);
8417 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8418 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8419 else
8420 FindReplicatedReg(SplatVal);
8421 } else {
8422 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8423 FindReplicatedImm(C, MemVT.getStoreSize());
8424 else
8425 FindReplicatedReg(Op1);
8426 }
8427
8428 if (Word != SDValue()) {
8429 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8430 "Bad type handling");
8431 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8432 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8433 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8434 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8435 SN->getBasePtr(), SN->getMemOperand());
8436 }
8437 }
8438
8439 return SDValue();
8440}
8441
8442SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8443 SDNode *N, DAGCombinerInfo &DCI) const {
8444 SelectionDAG &DAG = DCI.DAG;
8445 // Combine element-swap (LOAD) into VLER
8446 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8447 N->getOperand(0).hasOneUse() &&
8448 Subtarget.hasVectorEnhancements2()) {
8449 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8450 ArrayRef<int> ShuffleMask = SVN->getMask();
8451 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8452 SDValue Load = N->getOperand(0);
8453 LoadSDNode *LD = cast<LoadSDNode>(Load);
8454
8455 // Create the element-swapping load.
8456 SDValue Ops[] = {
8457 LD->getChain(), // Chain
8458 LD->getBasePtr() // Ptr
8459 };
8460 SDValue ESLoad =
8461 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8462 DAG.getVTList(LD->getValueType(0), MVT::Other),
8463 Ops, LD->getMemoryVT(), LD->getMemOperand());
8464
8465 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8466 // by the load dead.
8467 DCI.CombineTo(N, ESLoad);
8468
8469 // Next, combine the load away, we give it a bogus result value but a real
8470 // chain result. The result value is dead because the shuffle is dead.
8471 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8472
8473 // Return N so it doesn't get rechecked!
8474 return SDValue(N, 0);
8475 }
8476 }
8477
8478 return SDValue();
8479}
8480
8481SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8482 SDNode *N, DAGCombinerInfo &DCI) const {
8483 SelectionDAG &DAG = DCI.DAG;
8484
8485 if (!Subtarget.hasVector())
8486 return SDValue();
8487
8488 // Look through bitcasts that retain the number of vector elements.
8489 SDValue Op = N->getOperand(0);
8490 if (Op.getOpcode() == ISD::BITCAST &&
8491 Op.getValueType().isVector() &&
8492 Op.getOperand(0).getValueType().isVector() &&
8493 Op.getValueType().getVectorNumElements() ==
8494 Op.getOperand(0).getValueType().getVectorNumElements())
8495 Op = Op.getOperand(0);
8496
8497 // Pull BSWAP out of a vector extraction.
8498 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8499 EVT VecVT = Op.getValueType();
8500 EVT EltVT = VecVT.getVectorElementType();
8501 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8502 Op.getOperand(0), N->getOperand(1));
8503 DCI.AddToWorklist(Op.getNode());
8504 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8505 if (EltVT != N->getValueType(0)) {
8506 DCI.AddToWorklist(Op.getNode());
8507 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8508 }
8509 return Op;
8510 }
8511
8512 // Try to simplify a vector extraction.
8513 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8514 SDValue Op0 = N->getOperand(0);
8515 EVT VecVT = Op0.getValueType();
8516 if (canTreatAsByteVector(VecVT))
8517 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8518 IndexN->getZExtValue(), DCI, false);
8519 }
8520 return SDValue();
8521}
8522
8523SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8524 SDNode *N, DAGCombinerInfo &DCI) const {
8525 SelectionDAG &DAG = DCI.DAG;
8526 // (join_dwords X, X) == (replicate X)
8527 if (N->getOperand(0) == N->getOperand(1))
8528 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8529 N->getOperand(0));
8530 return SDValue();
8531}
8532
8534 SDValue Chain1 = N1->getOperand(0);
8535 SDValue Chain2 = N2->getOperand(0);
8536
8537 // Trivial case: both nodes take the same chain.
8538 if (Chain1 == Chain2)
8539 return Chain1;
8540
8541 // FIXME - we could handle more complex cases via TokenFactor,
8542 // assuming we can verify that this would not create a cycle.
8543 return SDValue();
8544}
8545
8546SDValue SystemZTargetLowering::combineFP_ROUND(
8547 SDNode *N, DAGCombinerInfo &DCI) const {
8548
8549 if (!Subtarget.hasVector())
8550 return SDValue();
8551
8552 // (fpround (extract_vector_elt X 0))
8553 // (fpround (extract_vector_elt X 1)) ->
8554 // (extract_vector_elt (VROUND X) 0)
8555 // (extract_vector_elt (VROUND X) 2)
8556 //
8557 // This is a special case since the target doesn't really support v2f32s.
8558 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8559 SelectionDAG &DAG = DCI.DAG;
8560 SDValue Op0 = N->getOperand(OpNo);
8561 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8563 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8564 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8565 Op0.getConstantOperandVal(1) == 0) {
8566 SDValue Vec = Op0.getOperand(0);
8567 for (auto *U : Vec->users()) {
8568 if (U != Op0.getNode() && U->hasOneUse() &&
8569 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8570 U->getOperand(0) == Vec &&
8571 U->getOperand(1).getOpcode() == ISD::Constant &&
8572 U->getConstantOperandVal(1) == 1) {
8573 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8574 if (OtherRound.getOpcode() == N->getOpcode() &&
8575 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8576 OtherRound.getValueType() == MVT::f32) {
8577 SDValue VRound, Chain;
8578 if (N->isStrictFPOpcode()) {
8579 Chain = MergeInputChains(N, OtherRound.getNode());
8580 if (!Chain)
8581 continue;
8582 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8583 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8584 Chain = VRound.getValue(1);
8585 } else
8586 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8587 MVT::v4f32, Vec);
8588 DCI.AddToWorklist(VRound.getNode());
8589 SDValue Extract1 =
8590 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8591 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8592 DCI.AddToWorklist(Extract1.getNode());
8593 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8594 if (Chain)
8595 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8596 SDValue Extract0 =
8597 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8598 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8599 if (Chain)
8600 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8601 N->getVTList(), Extract0, Chain);
8602 return Extract0;
8603 }
8604 }
8605 }
8606 }
8607 return SDValue();
8608}
8609
8610SDValue SystemZTargetLowering::combineFP_EXTEND(
8611 SDNode *N, DAGCombinerInfo &DCI) const {
8612
8613 if (!Subtarget.hasVector())
8614 return SDValue();
8615
8616 // (fpextend (extract_vector_elt X 0))
8617 // (fpextend (extract_vector_elt X 2)) ->
8618 // (extract_vector_elt (VEXTEND X) 0)
8619 // (extract_vector_elt (VEXTEND X) 1)
8620 //
8621 // This is a special case since the target doesn't really support v2f32s.
8622 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8623 SelectionDAG &DAG = DCI.DAG;
8624 SDValue Op0 = N->getOperand(OpNo);
8625 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8627 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8628 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8629 Op0.getConstantOperandVal(1) == 0) {
8630 SDValue Vec = Op0.getOperand(0);
8631 for (auto *U : Vec->users()) {
8632 if (U != Op0.getNode() && U->hasOneUse() &&
8633 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8634 U->getOperand(0) == Vec &&
8635 U->getOperand(1).getOpcode() == ISD::Constant &&
8636 U->getConstantOperandVal(1) == 2) {
8637 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8638 if (OtherExtend.getOpcode() == N->getOpcode() &&
8639 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8640 OtherExtend.getValueType() == MVT::f64) {
8641 SDValue VExtend, Chain;
8642 if (N->isStrictFPOpcode()) {
8643 Chain = MergeInputChains(N, OtherExtend.getNode());
8644 if (!Chain)
8645 continue;
8646 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8647 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8648 Chain = VExtend.getValue(1);
8649 } else
8650 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8651 MVT::v2f64, Vec);
8652 DCI.AddToWorklist(VExtend.getNode());
8653 SDValue Extract1 =
8654 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8655 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8656 DCI.AddToWorklist(Extract1.getNode());
8657 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8658 if (Chain)
8659 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8660 SDValue Extract0 =
8661 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8662 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8663 if (Chain)
8664 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8665 N->getVTList(), Extract0, Chain);
8666 return Extract0;
8667 }
8668 }
8669 }
8670 }
8671 return SDValue();
8672}
8673
8674SDValue SystemZTargetLowering::combineINT_TO_FP(
8675 SDNode *N, DAGCombinerInfo &DCI) const {
8676 if (DCI.Level != BeforeLegalizeTypes)
8677 return SDValue();
8678 SelectionDAG &DAG = DCI.DAG;
8679 LLVMContext &Ctx = *DAG.getContext();
8680 unsigned Opcode = N->getOpcode();
8681 EVT OutVT = N->getValueType(0);
8682 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8683 SDValue Op = N->getOperand(0);
8684 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8685 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8686
8687 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8688 // v2f64 = uint_to_fp v2i16
8689 // =>
8690 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8691 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8692 OutScalarBits <= 64) {
8693 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8694 EVT ExtVT = EVT::getVectorVT(
8695 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8696 unsigned ExtOpcode =
8698 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8699 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8700 }
8701 return SDValue();
8702}
8703
8704SDValue SystemZTargetLowering::combineFCOPYSIGN(
8705 SDNode *N, DAGCombinerInfo &DCI) const {
8706 SelectionDAG &DAG = DCI.DAG;
8707 EVT VT = N->getValueType(0);
8708 SDValue ValOp = N->getOperand(0);
8709 SDValue SignOp = N->getOperand(1);
8710
8711 // Remove the rounding which is not needed.
8712 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8713 SDValue WideOp = SignOp.getOperand(0);
8714 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8715 }
8716
8717 return SDValue();
8718}
8719
8720SDValue SystemZTargetLowering::combineBSWAP(
8721 SDNode *N, DAGCombinerInfo &DCI) const {
8722 SelectionDAG &DAG = DCI.DAG;
8723 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8724 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8725 N->getOperand(0).hasOneUse() &&
8726 canLoadStoreByteSwapped(N->getValueType(0))) {
8727 SDValue Load = N->getOperand(0);
8728 LoadSDNode *LD = cast<LoadSDNode>(Load);
8729
8730 // Create the byte-swapping load.
8731 SDValue Ops[] = {
8732 LD->getChain(), // Chain
8733 LD->getBasePtr() // Ptr
8734 };
8735 EVT LoadVT = N->getValueType(0);
8736 if (LoadVT == MVT::i16)
8737 LoadVT = MVT::i32;
8738 SDValue BSLoad =
8739 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8740 DAG.getVTList(LoadVT, MVT::Other),
8741 Ops, LD->getMemoryVT(), LD->getMemOperand());
8742
8743 // If this is an i16 load, insert the truncate.
8744 SDValue ResVal = BSLoad;
8745 if (N->getValueType(0) == MVT::i16)
8746 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8747
8748 // First, combine the bswap away. This makes the value produced by the
8749 // load dead.
8750 DCI.CombineTo(N, ResVal);
8751
8752 // Next, combine the load away, we give it a bogus result value but a real
8753 // chain result. The result value is dead because the bswap is dead.
8754 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8755
8756 // Return N so it doesn't get rechecked!
8757 return SDValue(N, 0);
8758 }
8759
8760 // Look through bitcasts that retain the number of vector elements.
8761 SDValue Op = N->getOperand(0);
8762 if (Op.getOpcode() == ISD::BITCAST &&
8763 Op.getValueType().isVector() &&
8764 Op.getOperand(0).getValueType().isVector() &&
8765 Op.getValueType().getVectorNumElements() ==
8766 Op.getOperand(0).getValueType().getVectorNumElements())
8767 Op = Op.getOperand(0);
8768
8769 // Push BSWAP into a vector insertion if at least one side then simplifies.
8770 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8771 SDValue Vec = Op.getOperand(0);
8772 SDValue Elt = Op.getOperand(1);
8773 SDValue Idx = Op.getOperand(2);
8774
8776 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8778 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8779 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8780 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8781 EVT VecVT = N->getValueType(0);
8782 EVT EltVT = N->getValueType(0).getVectorElementType();
8783 if (VecVT != Vec.getValueType()) {
8784 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8785 DCI.AddToWorklist(Vec.getNode());
8786 }
8787 if (EltVT != Elt.getValueType()) {
8788 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8789 DCI.AddToWorklist(Elt.getNode());
8790 }
8791 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8792 DCI.AddToWorklist(Vec.getNode());
8793 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8794 DCI.AddToWorklist(Elt.getNode());
8795 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8796 Vec, Elt, Idx);
8797 }
8798 }
8799
8800 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8801 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8802 if (SV && Op.hasOneUse()) {
8803 SDValue Op0 = Op.getOperand(0);
8804 SDValue Op1 = Op.getOperand(1);
8805
8807 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8809 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8810 EVT VecVT = N->getValueType(0);
8811 if (VecVT != Op0.getValueType()) {
8812 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8813 DCI.AddToWorklist(Op0.getNode());
8814 }
8815 if (VecVT != Op1.getValueType()) {
8816 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8817 DCI.AddToWorklist(Op1.getNode());
8818 }
8819 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8820 DCI.AddToWorklist(Op0.getNode());
8821 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8822 DCI.AddToWorklist(Op1.getNode());
8823 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8824 }
8825 }
8826
8827 return SDValue();
8828}
8829
8830SDValue SystemZTargetLowering::combineSETCC(
8831 SDNode *N, DAGCombinerInfo &DCI) const {
8832 SelectionDAG &DAG = DCI.DAG;
8833 const ISD::CondCode CC = N->getOperandCondCode(2);
8834 const SDValue LHS = N->getOperand(0);
8835 const SDValue RHS = N->getOperand(1);
8836 bool CmpNull = isNullConstant(RHS);
8837 bool CmpAllOnes = isAllOnesConstant(RHS);
8838 EVT VT = N->getValueType(0);
8839 SDLoc DL(N);
8840
8841 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8842 // change the outer compare to a i128 compare. This will normally
8843 // allow the reduction to be recognized in adjustICmp128, and even if
8844 // not, the i128 compare will still generate better code.
8845 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8847 if (Src.getOpcode() == ISD::SETCC &&
8848 Src.getValueType().isFixedLengthVector() &&
8849 Src.getValueType().getScalarType() == MVT::i1) {
8850 EVT CmpVT = Src.getOperand(0).getValueType();
8851 if (CmpVT.getSizeInBits() == 128) {
8852 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8853 SDValue LHS =
8854 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8855 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8856 : DAG.getAllOnesConstant(DL, MVT::i128);
8857 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8858 N->getFlags());
8859 }
8860 }
8861 }
8862
8863 return SDValue();
8864}
8865
8866static std::pair<SDValue, int> findCCUse(const SDValue &Val,
8867 unsigned Depth = 0) {
8868 // Limit depth of potentially exponential walk.
8869 if (Depth > 5)
8870 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8871
8872 switch (Val.getOpcode()) {
8873 default:
8874 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8875 case SystemZISD::IPM:
8876 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
8877 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
8878 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
8879 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
8880 case SystemZISD::SELECT_CCMASK: {
8881 SDValue Op4CCReg = Val.getOperand(4);
8882 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
8883 Op4CCReg.getOpcode() == SystemZISD::TM) {
8884 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
8885 if (OpCC != SDValue())
8886 return std::make_pair(OpCC, OpCCValid);
8887 }
8888 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8889 if (!CCValid)
8890 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8891 int CCValidVal = CCValid->getZExtValue();
8892 return std::make_pair(Op4CCReg, CCValidVal);
8893 }
8894 case ISD::ADD:
8895 case ISD::AND:
8896 case ISD::OR:
8897 case ISD::XOR:
8898 case ISD::SHL:
8899 case ISD::SRA:
8900 case ISD::SRL:
8901 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
8902 if (Op0CC != SDValue())
8903 return std::make_pair(Op0CC, Op0CCValid);
8904 return findCCUse(Val.getOperand(1), Depth + 1);
8905 }
8906}
8907
8908static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8909 SelectionDAG &DAG);
8910
8912 SelectionDAG &DAG) {
8913 SDLoc DL(Val);
8914 auto Opcode = Val.getOpcode();
8915 switch (Opcode) {
8916 default:
8917 return {};
8918 case ISD::Constant:
8919 return {Val, Val, Val, Val};
8920 case SystemZISD::IPM: {
8921 SDValue IPMOp0 = Val.getOperand(0);
8922 if (IPMOp0 != CC)
8923 return {};
8924 SmallVector<SDValue, 4> ShiftedCCVals;
8925 for (auto CC : {0, 1, 2, 3})
8926 ShiftedCCVals.emplace_back(
8927 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
8928 return ShiftedCCVals;
8929 }
8930 case SystemZISD::SELECT_CCMASK: {
8931 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
8932 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8933 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
8934 if (!CCValid || !CCMask)
8935 return {};
8936
8937 int CCValidVal = CCValid->getZExtValue();
8938 int CCMaskVal = CCMask->getZExtValue();
8939 // Pruning search tree early - Moving CC test and combineCCMask ahead of
8940 // recursive call to simplifyAssumingCCVal.
8941 SDValue Op4CCReg = Val.getOperand(4);
8942 if (Op4CCReg != CC)
8943 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
8944 if (Op4CCReg != CC)
8945 return {};
8946 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
8947 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
8948 if (TrueSDVals.empty() || FalseSDVals.empty())
8949 return {};
8950 SmallVector<SDValue, 4> MergedSDVals;
8951 for (auto &CCVal : {0, 1, 2, 3})
8952 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
8953 ? TrueSDVals[CCVal]
8954 : FalseSDVals[CCVal]);
8955 return MergedSDVals;
8956 }
8957 case ISD::ADD:
8958 case ISD::AND:
8959 case ISD::OR:
8960 case ISD::XOR:
8961 case ISD::SRA:
8962 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
8963 // would clobber CC).
8964 if (!Val.hasOneUse())
8965 return {};
8966 [[fallthrough]];
8967 case ISD::SHL:
8968 case ISD::SRL:
8969 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
8970 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
8971 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
8972 if (Op0SDVals.empty() || Op1SDVals.empty())
8973 return {};
8974 SmallVector<SDValue, 4> BinaryOpSDVals;
8975 for (auto CCVal : {0, 1, 2, 3})
8976 BinaryOpSDVals.emplace_back(DAG.getNode(
8977 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
8978 return BinaryOpSDVals;
8979 }
8980}
8981
8982static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8983 SelectionDAG &DAG) {
8984 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
8985 // set by the CCReg instruction using the CCValid / CCMask masks,
8986 // If the CCReg instruction is itself a ICMP / TM testing the condition
8987 // code set by some other instruction, see whether we can directly
8988 // use that condition code.
8989 auto *CCNode = CCReg.getNode();
8990 if (!CCNode)
8991 return false;
8992
8993 if (CCNode->getOpcode() == SystemZISD::TM) {
8994 if (CCValid != SystemZ::CCMASK_TM)
8995 return false;
8996 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
8997 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
8998 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
8999 if (!Op0Node || !Op1Node)
9000 return -1;
9001 auto Op0APVal = Op0Node->getAPIntValue();
9002 auto Op1APVal = Op1Node->getAPIntValue();
9003 auto Result = Op0APVal & Op1APVal;
9004 bool AllOnes = Result == Op1APVal;
9005 bool AllZeros = Result == 0;
9006 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
9007 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
9008 };
9009 SDValue Op0 = CCNode->getOperand(0);
9010 SDValue Op1 = CCNode->getOperand(1);
9011 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
9012 if (Op0CC == SDValue())
9013 return false;
9014 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
9015 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
9016 if (Op0SDVals.empty() || Op1SDVals.empty())
9017 return false;
9018 int NewCCMask = 0;
9019 for (auto CC : {0, 1, 2, 3}) {
9020 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
9021 if (CCVal < 0)
9022 return false;
9023 NewCCMask <<= 1;
9024 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9025 }
9026 NewCCMask &= Op0CCValid;
9027 CCReg = Op0CC;
9028 CCMask = NewCCMask;
9029 CCValid = Op0CCValid;
9030 return true;
9031 }
9032 if (CCNode->getOpcode() != SystemZISD::ICMP ||
9033 CCValid != SystemZ::CCMASK_ICMP)
9034 return false;
9035
9036 SDValue CmpOp0 = CCNode->getOperand(0);
9037 SDValue CmpOp1 = CCNode->getOperand(1);
9038 SDValue CmpOp2 = CCNode->getOperand(2);
9039 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
9040 if (Op0CC != SDValue()) {
9041 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
9042 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
9043 if (Op0SDVals.empty() || Op1SDVals.empty())
9044 return false;
9045
9046 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
9047 auto CmpTypeVal = CmpType->getZExtValue();
9048 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
9049 const SDValue &Op1Val) {
9050 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9051 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9052 if (!Op0Node || !Op1Node)
9053 return -1;
9054 auto Op0APVal = Op0Node->getAPIntValue();
9055 auto Op1APVal = Op1Node->getAPIntValue();
9056 if (CmpTypeVal == SystemZICMP::SignedOnly)
9057 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
9058 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
9059 };
9060 int NewCCMask = 0;
9061 for (auto CC : {0, 1, 2, 3}) {
9062 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
9063 if (CCVal < 0)
9064 return false;
9065 NewCCMask <<= 1;
9066 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9067 }
9068 NewCCMask &= Op0CCValid;
9069 CCMask = NewCCMask;
9070 CCReg = Op0CC;
9071 CCValid = Op0CCValid;
9072 return true;
9073 }
9074
9075 return false;
9076}
9077
9078// Merging versus split in multiple branches cost.
9081 const Value *Lhs,
9082 const Value *Rhs,
9083 const Function *) const {
9084 const auto isFlagOutOpCC = [](const Value *V) {
9085 using namespace llvm::PatternMatch;
9086 const Value *RHSVal;
9087 const APInt *RHSC;
9088 if (const auto *I = dyn_cast<Instruction>(V)) {
9089 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
9090 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
9091 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
9092 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
9093 if (CB->isInlineAsm()) {
9094 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
9095 return IA && IA->getConstraintString().contains("{@cc}");
9096 }
9097 }
9098 }
9099 }
9100 return false;
9101 };
9102 // Pattern (ICmp %asm) or (ICmp (And %asm)).
9103 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
9104 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
9105 // conditionals will be merged or else conditionals will be split.
9106 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
9107 return {3, 0, -1};
9108 // Default.
9109 return {-1, -1, -1};
9110}
9111
9112SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
9113 DAGCombinerInfo &DCI) const {
9114 SelectionDAG &DAG = DCI.DAG;
9115
9116 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9117 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9118 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9119 if (!CCValid || !CCMask)
9120 return SDValue();
9121
9122 int CCValidVal = CCValid->getZExtValue();
9123 int CCMaskVal = CCMask->getZExtValue();
9124 SDValue Chain = N->getOperand(0);
9125 SDValue CCReg = N->getOperand(4);
9126 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9127 // the modified BR_CCMASK with the new values.
9128 // In order to avoid conditional branches with full or empty cc masks, do not
9129 // do this if ccmask is 0 or equal to ccvalid.
9130 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9131 CCMaskVal != CCValidVal)
9132 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9133 Chain,
9134 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9135 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9136 N->getOperand(3), CCReg);
9137 return SDValue();
9138}
9139
9140SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9141 SDNode *N, DAGCombinerInfo &DCI) const {
9142 SelectionDAG &DAG = DCI.DAG;
9143
9144 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9145 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9146 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9147 if (!CCValid || !CCMask)
9148 return SDValue();
9149
9150 int CCValidVal = CCValid->getZExtValue();
9151 int CCMaskVal = CCMask->getZExtValue();
9152 SDValue CCReg = N->getOperand(4);
9153
9154 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9155
9156 // Populate SDVals vector for each condition code ccval for given Val, which
9157 // can again be another nested select_ccmask with the same CC.
9158 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9159 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9161 if (Val.getOperand(4) != CCReg)
9162 return SmallVector<SDValue, 4>{};
9163 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9164 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9165 if (!CCMask)
9166 return SmallVector<SDValue, 4>{};
9167
9168 int CCMaskVal = CCMask->getZExtValue();
9169 for (auto &CC : {0, 1, 2, 3})
9170 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9171 : FalseVal);
9172 return Res;
9173 }
9174 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9175 };
9176 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9177 // with CCReg found by combineCCMask or original CCReg.
9178 SDValue TrueVal = N->getOperand(0);
9179 SDValue FalseVal = N->getOperand(1);
9180 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9181 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9182 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9183 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9184 if (TrueSDVals.empty())
9185 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9186 if (FalseSDVals.empty())
9187 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9188 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9189 SmallSet<SDValue, 4> MergedSDValsSet;
9190 // Ignoring CC values outside CCValiid.
9191 for (auto CC : {0, 1, 2, 3}) {
9192 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9193 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9194 ? TrueSDVals[CC]
9195 : FalseSDVals[CC]);
9196 }
9197 if (MergedSDValsSet.size() == 1)
9198 return *MergedSDValsSet.begin();
9199 if (MergedSDValsSet.size() == 2) {
9200 auto BeginIt = MergedSDValsSet.begin();
9201 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9202 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9203 std::swap(NewTrueVal, NewFalseVal);
9204 int NewCCMask = 0;
9205 for (auto CC : {0, 1, 2, 3}) {
9206 NewCCMask <<= 1;
9207 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9208 ? (TrueSDVals[CC] == NewTrueVal)
9209 : (FalseSDVals[CC] == NewTrueVal);
9210 }
9211 CCMaskVal = NewCCMask;
9212 CCMaskVal &= CCValidVal;
9213 TrueVal = NewTrueVal;
9214 FalseVal = NewFalseVal;
9215 IsCombinedCCReg = true;
9216 }
9217 }
9218 // If the condition is trivially false or trivially true after
9219 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9220 // (possibly modified by constructCCSDValsFromSELECT).
9221 if (CCMaskVal == 0)
9222 return FalseVal;
9223 if (CCMaskVal == CCValidVal)
9224 return TrueVal;
9225
9226 if (IsCombinedCCReg)
9227 return DAG.getNode(
9228 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9229 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9230 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9231
9232 return SDValue();
9233}
9234
9235SDValue SystemZTargetLowering::combineGET_CCMASK(
9236 SDNode *N, DAGCombinerInfo &DCI) const {
9237
9238 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9239 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9240 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9241 if (!CCValid || !CCMask)
9242 return SDValue();
9243 int CCValidVal = CCValid->getZExtValue();
9244 int CCMaskVal = CCMask->getZExtValue();
9245
9246 SDValue Select = N->getOperand(0);
9247 if (Select->getOpcode() == ISD::TRUNCATE)
9248 Select = Select->getOperand(0);
9249 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9250 return SDValue();
9251
9252 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9253 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9254 if (!SelectCCValid || !SelectCCMask)
9255 return SDValue();
9256 int SelectCCValidVal = SelectCCValid->getZExtValue();
9257 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9258
9259 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9260 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9261 if (!TrueVal || !FalseVal)
9262 return SDValue();
9263 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9264 ;
9265 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9266 SelectCCMaskVal ^= SelectCCValidVal;
9267 else
9268 return SDValue();
9269
9270 if (SelectCCValidVal & ~CCValidVal)
9271 return SDValue();
9272 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9273 return SDValue();
9274
9275 return Select->getOperand(4);
9276}
9277
9278SDValue SystemZTargetLowering::combineIntDIVREM(
9279 SDNode *N, DAGCombinerInfo &DCI) const {
9280 SelectionDAG &DAG = DCI.DAG;
9281 EVT VT = N->getValueType(0);
9282 // In the case where the divisor is a vector of constants a cheaper
9283 // sequence of instructions can replace the divide. BuildSDIV is called to
9284 // do this during DAG combining, but it only succeeds when it can build a
9285 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9286 // since it is not Legal but Custom it can only happen before
9287 // legalization. Therefore we must scalarize this early before Combine
9288 // 1. For widened vectors, this is already the result of type legalization.
9289 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9290 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9291 return DAG.UnrollVectorOp(N);
9292 return SDValue();
9293}
9294
9295
9296// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9297// This is closely modeled after the common-code combineShiftToMULH.
9298SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9299 SDNode *N, DAGCombinerInfo &DCI) const {
9300 SelectionDAG &DAG = DCI.DAG;
9301 SDLoc DL(N);
9302
9303 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9304 "SRL or SRA node is required here!");
9305
9306 if (!Subtarget.hasVector())
9307 return SDValue();
9308
9309 // Check the shift amount. Proceed with the transformation if the shift
9310 // amount is constant.
9311 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9312 if (!ShiftAmtSrc)
9313 return SDValue();
9314
9315 // The operation feeding into the shift must be an add.
9316 SDValue ShiftOperand = N->getOperand(0);
9317 if (ShiftOperand.getOpcode() != ISD::ADD)
9318 return SDValue();
9319
9320 // One operand of the add must be a multiply.
9321 SDValue MulOp = ShiftOperand.getOperand(0);
9322 SDValue AddOp = ShiftOperand.getOperand(1);
9323 if (MulOp.getOpcode() != ISD::MUL) {
9324 if (AddOp.getOpcode() != ISD::MUL)
9325 return SDValue();
9326 std::swap(MulOp, AddOp);
9327 }
9328
9329 // All operands must be equivalent extend nodes.
9330 SDValue LeftOp = MulOp.getOperand(0);
9331 SDValue RightOp = MulOp.getOperand(1);
9332
9333 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9334 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9335
9336 if (!IsSignExt && !IsZeroExt)
9337 return SDValue();
9338
9339 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9340 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9341
9342 SDValue MulhRightOp;
9343 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9344 unsigned ActiveBits = IsSignExt
9345 ? Constant->getAPIntValue().getSignificantBits()
9346 : Constant->getAPIntValue().getActiveBits();
9347 if (ActiveBits > NarrowVTSize)
9348 return SDValue();
9349 MulhRightOp = DAG.getConstant(
9350 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9351 NarrowVT);
9352 } else {
9353 if (LeftOp.getOpcode() != RightOp.getOpcode())
9354 return SDValue();
9355 // Check that the two extend nodes are the same type.
9356 if (NarrowVT != RightOp.getOperand(0).getValueType())
9357 return SDValue();
9358 MulhRightOp = RightOp.getOperand(0);
9359 }
9360
9361 SDValue MulhAddOp;
9362 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9363 unsigned ActiveBits = IsSignExt
9364 ? Constant->getAPIntValue().getSignificantBits()
9365 : Constant->getAPIntValue().getActiveBits();
9366 if (ActiveBits > NarrowVTSize)
9367 return SDValue();
9368 MulhAddOp = DAG.getConstant(
9369 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9370 NarrowVT);
9371 } else {
9372 if (LeftOp.getOpcode() != AddOp.getOpcode())
9373 return SDValue();
9374 // Check that the two extend nodes are the same type.
9375 if (NarrowVT != AddOp.getOperand(0).getValueType())
9376 return SDValue();
9377 MulhAddOp = AddOp.getOperand(0);
9378 }
9379
9380 EVT WideVT = LeftOp.getValueType();
9381 // Proceed with the transformation if the wide types match.
9382 assert((WideVT == RightOp.getValueType()) &&
9383 "Cannot have a multiply node with two different operand types.");
9384 assert((WideVT == AddOp.getValueType()) &&
9385 "Cannot have an add node with two different operand types.");
9386
9387 // Proceed with the transformation if the wide type is twice as large
9388 // as the narrow type.
9389 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9390 return SDValue();
9391
9392 // Check the shift amount with the narrow type size.
9393 // Proceed with the transformation if the shift amount is the width
9394 // of the narrow type.
9395 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9396 if (ShiftAmt != NarrowVTSize)
9397 return SDValue();
9398
9399 // Proceed if we support the multiply-and-add-high operation.
9400 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9401 NarrowVT == MVT::v4i32 ||
9402 (Subtarget.hasVectorEnhancements3() &&
9403 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9404 return SDValue();
9405
9406 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9407 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9408 DL, NarrowVT, LeftOp.getOperand(0),
9409 MulhRightOp, MulhAddOp);
9410 bool IsSigned = N->getOpcode() == ISD::SRA;
9411 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9412}
9413
9414// Op is an operand of a multiplication. Check whether this can be folded
9415// into an even/odd widening operation; if so, return the opcode to be used
9416// and update Op to the appropriate sub-operand. Note that the caller must
9417// verify that *both* operands of the multiplication support the operation.
9420 SDValue &Op) {
9421 EVT VT = Op.getValueType();
9422
9423 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9424 // to selecting the even or odd vector elements.
9425 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9426 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9427 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9428 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9429 unsigned NumElts = VT.getVectorNumElements();
9430 Op = Op.getOperand(0);
9431 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9432 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9434 ArrayRef<int> ShuffleMask = SVN->getMask();
9435 bool CanUseEven = true, CanUseOdd = true;
9436 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9437 if (ShuffleMask[Elt] == -1)
9438 continue;
9439 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9440 CanUseEven = false;
9441 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9442 CanUseOdd = false;
9443 }
9444 Op = Op.getOperand(0);
9445 if (CanUseEven)
9446 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9447 if (CanUseOdd)
9448 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9449 }
9450 }
9451
9452 // For z17, we can also support the v2i64->i128 case, which looks like
9453 // (sign/zero_extend (extract_vector_elt X 0/1))
9454 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9455 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9456 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9457 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9458 Op = Op.getOperand(0);
9459 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9460 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9461 Op.getOperand(1).getOpcode() == ISD::Constant) {
9462 unsigned Elem = Op.getConstantOperandVal(1);
9463 Op = Op.getOperand(0);
9464 if (Elem == 0)
9465 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9466 if (Elem == 1)
9467 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9468 }
9469 }
9470
9471 return 0;
9472}
9473
9474SDValue SystemZTargetLowering::combineMUL(
9475 SDNode *N, DAGCombinerInfo &DCI) const {
9476 SelectionDAG &DAG = DCI.DAG;
9477
9478 // Detect even/odd widening multiplication.
9479 SDValue Op0 = N->getOperand(0);
9480 SDValue Op1 = N->getOperand(1);
9481 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9482 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9483 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9484 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9485
9486 return SDValue();
9487}
9488
9489SDValue SystemZTargetLowering::combineINTRINSIC(
9490 SDNode *N, DAGCombinerInfo &DCI) const {
9491 SelectionDAG &DAG = DCI.DAG;
9492
9493 unsigned Id = N->getConstantOperandVal(1);
9494 switch (Id) {
9495 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9496 // or larger is simply a vector load.
9497 case Intrinsic::s390_vll:
9498 case Intrinsic::s390_vlrl:
9499 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9500 if (C->getZExtValue() >= 15)
9501 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9502 N->getOperand(3), MachinePointerInfo());
9503 break;
9504 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9505 case Intrinsic::s390_vstl:
9506 case Intrinsic::s390_vstrl:
9507 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9508 if (C->getZExtValue() >= 15)
9509 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9510 N->getOperand(4), MachinePointerInfo());
9511 break;
9512 }
9513
9514 return SDValue();
9515}
9516
9517SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9518 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9519 return N->getOperand(0);
9520 return N;
9521}
9522
9524 DAGCombinerInfo &DCI) const {
9525 switch(N->getOpcode()) {
9526 default: break;
9527 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9528 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9529 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9530 case SystemZISD::MERGE_HIGH:
9531 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9532 case ISD::LOAD: return combineLOAD(N, DCI);
9533 case ISD::STORE: return combineSTORE(N, DCI);
9534 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9535 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9536 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9538 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9540 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9541 case ISD::SINT_TO_FP:
9542 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9543 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9544 case ISD::BSWAP: return combineBSWAP(N, DCI);
9545 case ISD::SETCC: return combineSETCC(N, DCI);
9546 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9547 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9548 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9549 case ISD::SRL:
9550 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9551 case ISD::MUL: return combineMUL(N, DCI);
9552 case ISD::SDIV:
9553 case ISD::UDIV:
9554 case ISD::SREM:
9555 case ISD::UREM: return combineIntDIVREM(N, DCI);
9557 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9558 }
9559
9560 return SDValue();
9561}
9562
9563// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9564// are for Op.
9565static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9566 unsigned OpNo) {
9567 EVT VT = Op.getValueType();
9568 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9569 APInt SrcDemE;
9570 unsigned Opcode = Op.getOpcode();
9571 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9572 unsigned Id = Op.getConstantOperandVal(0);
9573 switch (Id) {
9574 case Intrinsic::s390_vpksh: // PACKS
9575 case Intrinsic::s390_vpksf:
9576 case Intrinsic::s390_vpksg:
9577 case Intrinsic::s390_vpkshs: // PACKS_CC
9578 case Intrinsic::s390_vpksfs:
9579 case Intrinsic::s390_vpksgs:
9580 case Intrinsic::s390_vpklsh: // PACKLS
9581 case Intrinsic::s390_vpklsf:
9582 case Intrinsic::s390_vpklsg:
9583 case Intrinsic::s390_vpklshs: // PACKLS_CC
9584 case Intrinsic::s390_vpklsfs:
9585 case Intrinsic::s390_vpklsgs:
9586 // VECTOR PACK truncates the elements of two source vectors into one.
9587 SrcDemE = DemandedElts;
9588 if (OpNo == 2)
9589 SrcDemE.lshrInPlace(NumElts / 2);
9590 SrcDemE = SrcDemE.trunc(NumElts / 2);
9591 break;
9592 // VECTOR UNPACK extends half the elements of the source vector.
9593 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9594 case Intrinsic::s390_vuphh:
9595 case Intrinsic::s390_vuphf:
9596 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9597 case Intrinsic::s390_vuplhh:
9598 case Intrinsic::s390_vuplhf:
9599 SrcDemE = APInt(NumElts * 2, 0);
9600 SrcDemE.insertBits(DemandedElts, 0);
9601 break;
9602 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9603 case Intrinsic::s390_vuplhw:
9604 case Intrinsic::s390_vuplf:
9605 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9606 case Intrinsic::s390_vupllh:
9607 case Intrinsic::s390_vupllf:
9608 SrcDemE = APInt(NumElts * 2, 0);
9609 SrcDemE.insertBits(DemandedElts, NumElts);
9610 break;
9611 case Intrinsic::s390_vpdi: {
9612 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9613 SrcDemE = APInt(NumElts, 0);
9614 if (!DemandedElts[OpNo - 1])
9615 break;
9616 unsigned Mask = Op.getConstantOperandVal(3);
9617 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9618 // Demand input element 0 or 1, given by the mask bit value.
9619 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9620 break;
9621 }
9622 case Intrinsic::s390_vsldb: {
9623 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9624 assert(VT == MVT::v16i8 && "Unexpected type.");
9625 unsigned FirstIdx = Op.getConstantOperandVal(3);
9626 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9627 unsigned NumSrc0Els = 16 - FirstIdx;
9628 SrcDemE = APInt(NumElts, 0);
9629 if (OpNo == 1) {
9630 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9631 SrcDemE.insertBits(DemEls, FirstIdx);
9632 } else {
9633 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9634 SrcDemE.insertBits(DemEls, 0);
9635 }
9636 break;
9637 }
9638 case Intrinsic::s390_vperm:
9639 SrcDemE = APInt::getAllOnes(NumElts);
9640 break;
9641 default:
9642 llvm_unreachable("Unhandled intrinsic.");
9643 break;
9644 }
9645 } else {
9646 switch (Opcode) {
9647 case SystemZISD::JOIN_DWORDS:
9648 // Scalar operand.
9649 SrcDemE = APInt(1, 1);
9650 break;
9651 case SystemZISD::SELECT_CCMASK:
9652 SrcDemE = DemandedElts;
9653 break;
9654 default:
9655 llvm_unreachable("Unhandled opcode.");
9656 break;
9657 }
9658 }
9659 return SrcDemE;
9660}
9661
9663 const APInt &DemandedElts,
9664 const SelectionDAG &DAG, unsigned Depth,
9665 unsigned OpNo) {
9666 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9667 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9668 KnownBits LHSKnown =
9669 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9670 KnownBits RHSKnown =
9671 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9672 Known = LHSKnown.intersectWith(RHSKnown);
9673}
9674
9675void
9678 const APInt &DemandedElts,
9679 const SelectionDAG &DAG,
9680 unsigned Depth) const {
9681 Known.resetAll();
9682
9683 // Intrinsic CC result is returned in the two low bits.
9684 unsigned Tmp0, Tmp1; // not used
9685 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9686 Known.Zero.setBitsFrom(2);
9687 return;
9688 }
9689 [[maybe_unused]] EVT VT = Op.getValueType();
9690 if (Op.getResNo() != 0)
9691 return;
9692 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9693 "KnownBits does not match VT in bitwidth");
9694 assert ((!VT.isVector() ||
9695 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9696 "DemandedElts does not match VT number of elements");
9697 unsigned BitWidth = Known.getBitWidth();
9698 unsigned Opcode = Op.getOpcode();
9699 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9700 bool IsLogical = false;
9701 unsigned Id = Op.getConstantOperandVal(0);
9702 switch (Id) {
9703 case Intrinsic::s390_vpksh: // PACKS
9704 case Intrinsic::s390_vpksf:
9705 case Intrinsic::s390_vpksg:
9706 case Intrinsic::s390_vpkshs: // PACKS_CC
9707 case Intrinsic::s390_vpksfs:
9708 case Intrinsic::s390_vpksgs:
9709 case Intrinsic::s390_vpklsh: // PACKLS
9710 case Intrinsic::s390_vpklsf:
9711 case Intrinsic::s390_vpklsg:
9712 case Intrinsic::s390_vpklshs: // PACKLS_CC
9713 case Intrinsic::s390_vpklsfs:
9714 case Intrinsic::s390_vpklsgs:
9715 case Intrinsic::s390_vpdi:
9716 case Intrinsic::s390_vsldb:
9717 case Intrinsic::s390_vperm:
9718 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9719 break;
9720 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9721 case Intrinsic::s390_vuplhh:
9722 case Intrinsic::s390_vuplhf:
9723 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9724 case Intrinsic::s390_vupllh:
9725 case Intrinsic::s390_vupllf:
9726 IsLogical = true;
9727 [[fallthrough]];
9728 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9729 case Intrinsic::s390_vuphh:
9730 case Intrinsic::s390_vuphf:
9731 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9732 case Intrinsic::s390_vuplhw:
9733 case Intrinsic::s390_vuplf: {
9734 SDValue SrcOp = Op.getOperand(1);
9735 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9736 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9737 if (IsLogical) {
9738 Known = Known.zext(BitWidth);
9739 } else
9740 Known = Known.sext(BitWidth);
9741 break;
9742 }
9743 default:
9744 break;
9745 }
9746 } else {
9747 switch (Opcode) {
9748 case SystemZISD::JOIN_DWORDS:
9749 case SystemZISD::SELECT_CCMASK:
9750 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9751 break;
9752 case SystemZISD::REPLICATE: {
9753 SDValue SrcOp = Op.getOperand(0);
9754 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9755 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9756 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9757 break;
9758 }
9759 default:
9760 break;
9761 }
9762 }
9763
9764 // Known has the width of the source operand(s). Adjust if needed to match
9765 // the passed bitwidth.
9766 if (Known.getBitWidth() != BitWidth)
9767 Known = Known.anyextOrTrunc(BitWidth);
9768}
9769
9770static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9771 const SelectionDAG &DAG, unsigned Depth,
9772 unsigned OpNo) {
9773 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9774 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9775 if (LHS == 1) return 1; // Early out.
9776 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9777 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9778 if (RHS == 1) return 1; // Early out.
9779 unsigned Common = std::min(LHS, RHS);
9780 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9781 EVT VT = Op.getValueType();
9782 unsigned VTBits = VT.getScalarSizeInBits();
9783 if (SrcBitWidth > VTBits) { // PACK
9784 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9785 if (Common > SrcExtraBits)
9786 return (Common - SrcExtraBits);
9787 return 1;
9788 }
9789 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9790 return Common;
9791}
9792
9793unsigned
9795 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9796 unsigned Depth) const {
9797 if (Op.getResNo() != 0)
9798 return 1;
9799 unsigned Opcode = Op.getOpcode();
9800 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9801 unsigned Id = Op.getConstantOperandVal(0);
9802 switch (Id) {
9803 case Intrinsic::s390_vpksh: // PACKS
9804 case Intrinsic::s390_vpksf:
9805 case Intrinsic::s390_vpksg:
9806 case Intrinsic::s390_vpkshs: // PACKS_CC
9807 case Intrinsic::s390_vpksfs:
9808 case Intrinsic::s390_vpksgs:
9809 case Intrinsic::s390_vpklsh: // PACKLS
9810 case Intrinsic::s390_vpklsf:
9811 case Intrinsic::s390_vpklsg:
9812 case Intrinsic::s390_vpklshs: // PACKLS_CC
9813 case Intrinsic::s390_vpklsfs:
9814 case Intrinsic::s390_vpklsgs:
9815 case Intrinsic::s390_vpdi:
9816 case Intrinsic::s390_vsldb:
9817 case Intrinsic::s390_vperm:
9818 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9819 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9820 case Intrinsic::s390_vuphh:
9821 case Intrinsic::s390_vuphf:
9822 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9823 case Intrinsic::s390_vuplhw:
9824 case Intrinsic::s390_vuplf: {
9825 SDValue PackedOp = Op.getOperand(1);
9826 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9827 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9828 EVT VT = Op.getValueType();
9829 unsigned VTBits = VT.getScalarSizeInBits();
9830 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9831 return Tmp;
9832 }
9833 default:
9834 break;
9835 }
9836 } else {
9837 switch (Opcode) {
9838 case SystemZISD::SELECT_CCMASK:
9839 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9840 default:
9841 break;
9842 }
9843 }
9844
9845 return 1;
9846}
9847
9849 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9850 UndefPoisonKind Kind, unsigned Depth) const {
9851 switch (Op->getOpcode()) {
9852 case SystemZISD::PCREL_WRAPPER:
9853 case SystemZISD::PCREL_OFFSET:
9854 return true;
9855 }
9856 return false;
9857}
9858
9859unsigned
9861 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
9862 unsigned StackAlign = TFI->getStackAlignment();
9863 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
9864 "Unexpected stack alignment");
9865 // The default stack probe size is 4096 if the function has no
9866 // stack-probe-size attribute.
9867 unsigned StackProbeSize =
9868 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
9869 // Round down to the stack alignment.
9870 StackProbeSize &= ~(StackAlign - 1);
9871 return StackProbeSize ? StackProbeSize : StackAlign;
9872}
9873
9874//===----------------------------------------------------------------------===//
9875// Custom insertion
9876//===----------------------------------------------------------------------===//
9877
9878// Force base value Base into a register before MI. Return the register.
9880 const SystemZInstrInfo *TII) {
9881 MachineBasicBlock *MBB = MI.getParent();
9882 MachineFunction &MF = *MBB->getParent();
9884
9885 if (Base.isReg()) {
9886 // Copy Base into a new virtual register to help register coalescing in
9887 // cases with multiple uses.
9888 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9889 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
9890 .add(Base);
9891 return Reg;
9892 }
9893
9894 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9895 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
9896 .add(Base)
9897 .addImm(0)
9898 .addReg(0);
9899 return Reg;
9900}
9901
9902// The CC operand of MI might be missing a kill marker because there
9903// were multiple uses of CC, and ISel didn't know which to mark.
9904// Figure out whether MI should have had a kill marker.
9906 // Scan forward through BB for a use/def of CC.
9908 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
9909 const MachineInstr &MI = *miI;
9910 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
9911 return false;
9912 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
9913 break; // Should have kill-flag - update below.
9914 }
9915
9916 // If we hit the end of the block, check whether CC is live into a
9917 // successor.
9918 if (miI == MBB->end()) {
9919 for (const MachineBasicBlock *Succ : MBB->successors())
9920 if (Succ->isLiveIn(SystemZ::CC))
9921 return false;
9922 }
9923
9924 return true;
9925}
9926
9927// Return true if it is OK for this Select pseudo-opcode to be cascaded
9928// together with other Select pseudo-opcodes into a single basic-block with
9929// a conditional jump around it.
9931 switch (MI.getOpcode()) {
9932 case SystemZ::Select32:
9933 case SystemZ::Select64:
9934 case SystemZ::Select128:
9935 case SystemZ::SelectF32:
9936 case SystemZ::SelectF64:
9937 case SystemZ::SelectF128:
9938 case SystemZ::SelectVR32:
9939 case SystemZ::SelectVR64:
9940 case SystemZ::SelectVR128:
9941 return true;
9942
9943 default:
9944 return false;
9945 }
9946}
9947
9948// Helper function, which inserts PHI functions into SinkMBB:
9949// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
9950// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
9952 MachineBasicBlock *TrueMBB,
9953 MachineBasicBlock *FalseMBB,
9954 MachineBasicBlock *SinkMBB) {
9955 MachineFunction *MF = TrueMBB->getParent();
9957
9958 MachineInstr *FirstMI = Selects.front();
9959 unsigned CCValid = FirstMI->getOperand(3).getImm();
9960 unsigned CCMask = FirstMI->getOperand(4).getImm();
9961
9962 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
9963
9964 // As we are creating the PHIs, we have to be careful if there is more than
9965 // one. Later Selects may reference the results of earlier Selects, but later
9966 // PHIs have to reference the individual true/false inputs from earlier PHIs.
9967 // That also means that PHI construction must work forward from earlier to
9968 // later, and that the code must maintain a mapping from earlier PHI's
9969 // destination registers, and the registers that went into the PHI.
9971
9972 for (auto *MI : Selects) {
9973 Register DestReg = MI->getOperand(0).getReg();
9974 Register TrueReg = MI->getOperand(1).getReg();
9975 Register FalseReg = MI->getOperand(2).getReg();
9976
9977 // If this Select we are generating is the opposite condition from
9978 // the jump we generated, then we have to swap the operands for the
9979 // PHI that is going to be generated.
9980 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
9981 std::swap(TrueReg, FalseReg);
9982
9983 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
9984 TrueReg = It->second.first;
9985
9986 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
9987 FalseReg = It->second.second;
9988
9989 DebugLoc DL = MI->getDebugLoc();
9990 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
9991 .addReg(TrueReg).addMBB(TrueMBB)
9992 .addReg(FalseReg).addMBB(FalseMBB);
9993
9994 // Add this PHI to the rewrite table.
9995 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
9996 }
9997
9998 MF->getProperties().resetNoPHIs();
9999}
10000
10002SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
10003 MachineBasicBlock *BB) const {
10004 MachineFunction &MF = *BB->getParent();
10005 MachineFrameInfo &MFI = MF.getFrameInfo();
10006 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
10007 assert(TFL->hasReservedCallFrame(MF) &&
10008 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
10009 (void)TFL;
10010 // Get the MaxCallFrameSize value and erase MI since it serves no further
10011 // purpose as the call frame is statically reserved in the prolog. Set
10012 // AdjustsStack as MI is *not* mapped as a frame instruction.
10013 uint32_t NumBytes = MI.getOperand(0).getImm();
10014 if (NumBytes > MFI.getMaxCallFrameSize())
10015 MFI.setMaxCallFrameSize(NumBytes);
10016 MFI.setAdjustsStack(true);
10017
10018 MI.eraseFromParent();
10019 return BB;
10020}
10021
10022// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
10024SystemZTargetLowering::emitSelect(MachineInstr &MI,
10025 MachineBasicBlock *MBB) const {
10026 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
10027 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10028
10029 unsigned CCValid = MI.getOperand(3).getImm();
10030 unsigned CCMask = MI.getOperand(4).getImm();
10031
10032 // If we have a sequence of Select* pseudo instructions using the
10033 // same condition code value, we want to expand all of them into
10034 // a single pair of basic blocks using the same condition.
10035 SmallVector<MachineInstr*, 8> Selects;
10036 SmallVector<MachineInstr*, 8> DbgValues;
10037 Selects.push_back(&MI);
10038 unsigned Count = 0;
10039 for (MachineInstr &NextMI : llvm::make_range(
10040 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
10041 if (isSelectPseudo(NextMI)) {
10042 assert(NextMI.getOperand(3).getImm() == CCValid &&
10043 "Bad CCValid operands since CC was not redefined.");
10044 if (NextMI.getOperand(4).getImm() == CCMask ||
10045 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
10046 Selects.push_back(&NextMI);
10047 continue;
10048 }
10049 break;
10050 }
10051 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10052 NextMI.usesCustomInsertionHook())
10053 break;
10054 bool User = false;
10055 for (auto *SelMI : Selects)
10056 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
10057 User = true;
10058 break;
10059 }
10060 if (NextMI.isDebugInstr()) {
10061 if (User) {
10062 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
10063 DbgValues.push_back(&NextMI);
10064 }
10065 } else if (User || ++Count > 20)
10066 break;
10067 }
10068
10069 MachineInstr *LastMI = Selects.back();
10070 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10071 checkCCKill(*LastMI, MBB));
10072 MachineBasicBlock *StartMBB = MBB;
10073 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
10074 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10075
10076 // Unless CC was killed in the last Select instruction, mark it as
10077 // live-in to both FalseMBB and JoinMBB.
10078 if (!CCKilled) {
10079 FalseMBB->addLiveIn(SystemZ::CC);
10080 JoinMBB->addLiveIn(SystemZ::CC);
10081 }
10082
10083 // StartMBB:
10084 // BRC CCMask, JoinMBB
10085 // # fallthrough to FalseMBB
10086 MBB = StartMBB;
10087 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10088 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10089 MBB->addSuccessor(JoinMBB);
10090 MBB->addSuccessor(FalseMBB);
10091
10092 // FalseMBB:
10093 // # fallthrough to JoinMBB
10094 MBB = FalseMBB;
10095 MBB->addSuccessor(JoinMBB);
10096
10097 // JoinMBB:
10098 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
10099 // ...
10100 MBB = JoinMBB;
10101 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
10102 for (auto *SelMI : Selects)
10103 SelMI->eraseFromParent();
10104
10106 for (auto *DbgMI : DbgValues)
10107 MBB->splice(InsertPos, StartMBB, DbgMI);
10108
10109 return JoinMBB;
10110}
10111
10112// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
10113// StoreOpcode is the store to use and Invert says whether the store should
10114// happen when the condition is false rather than true. If a STORE ON
10115// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10116MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10118 unsigned StoreOpcode,
10119 unsigned STOCOpcode,
10120 bool Invert) const {
10121 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10122
10123 Register SrcReg = MI.getOperand(0).getReg();
10124 MachineOperand Base = MI.getOperand(1);
10125 int64_t Disp = MI.getOperand(2).getImm();
10126 Register IndexReg = MI.getOperand(3).getReg();
10127 unsigned CCValid = MI.getOperand(4).getImm();
10128 unsigned CCMask = MI.getOperand(5).getImm();
10129 DebugLoc DL = MI.getDebugLoc();
10130
10131 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10132
10133 // ISel pattern matching also adds a load memory operand of the same
10134 // address, so take special care to find the storing memory operand.
10135 MachineMemOperand *MMO = nullptr;
10136 for (auto *I : MI.memoperands())
10137 if (I->isStore()) {
10138 MMO = I;
10139 break;
10140 }
10141
10142 // Use STOCOpcode if possible. We could use different store patterns in
10143 // order to avoid matching the index register, but the performance trade-offs
10144 // might be more complicated in that case.
10145 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10146 if (Invert)
10147 CCMask ^= CCValid;
10148
10149 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10150 .addReg(SrcReg)
10151 .add(Base)
10152 .addImm(Disp)
10153 .addImm(CCValid)
10154 .addImm(CCMask)
10155 .addMemOperand(MMO);
10156
10157 MI.eraseFromParent();
10158 return MBB;
10159 }
10160
10161 // Get the condition needed to branch around the store.
10162 if (!Invert)
10163 CCMask ^= CCValid;
10164
10165 MachineBasicBlock *StartMBB = MBB;
10166 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10167 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10168
10169 // Unless CC was killed in the CondStore instruction, mark it as
10170 // live-in to both FalseMBB and JoinMBB.
10171 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10172 !checkCCKill(MI, JoinMBB)) {
10173 FalseMBB->addLiveIn(SystemZ::CC);
10174 JoinMBB->addLiveIn(SystemZ::CC);
10175 }
10176
10177 // StartMBB:
10178 // BRC CCMask, JoinMBB
10179 // # fallthrough to FalseMBB
10180 MBB = StartMBB;
10181 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10182 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10183 MBB->addSuccessor(JoinMBB);
10184 MBB->addSuccessor(FalseMBB);
10185
10186 // FalseMBB:
10187 // store %SrcReg, %Disp(%Index,%Base)
10188 // # fallthrough to JoinMBB
10189 MBB = FalseMBB;
10190 BuildMI(MBB, DL, TII->get(StoreOpcode))
10191 .addReg(SrcReg)
10192 .add(Base)
10193 .addImm(Disp)
10194 .addReg(IndexReg)
10195 .addMemOperand(MMO);
10196 MBB->addSuccessor(JoinMBB);
10197
10198 MI.eraseFromParent();
10199 return JoinMBB;
10200}
10201
10202// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10204SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10206 bool Unsigned) const {
10207 MachineFunction &MF = *MBB->getParent();
10208 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10209 MachineRegisterInfo &MRI = MF.getRegInfo();
10210
10211 // Synthetic instruction to compare 128-bit values.
10212 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10213 Register Op0 = MI.getOperand(0).getReg();
10214 Register Op1 = MI.getOperand(1).getReg();
10215
10216 MachineBasicBlock *StartMBB = MBB;
10217 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10218 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10219
10220 // StartMBB:
10221 //
10222 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10223 // Swap the inputs to get:
10224 // CC 1 if high(Op0) > high(Op1)
10225 // CC 2 if high(Op0) < high(Op1)
10226 // CC 0 if high(Op0) == high(Op1)
10227 //
10228 // If CC != 0, we'd done, so jump over the next instruction.
10229 //
10230 // VEC[L]G Op1, Op0
10231 // JNE JoinMBB
10232 // # fallthrough to HiEqMBB
10233 MBB = StartMBB;
10234 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10235 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10236 .addReg(Op1).addReg(Op0);
10237 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10239 MBB->addSuccessor(JoinMBB);
10240 MBB->addSuccessor(HiEqMBB);
10241
10242 // HiEqMBB:
10243 //
10244 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10245 // Since we already know the high parts are equal, the CC
10246 // result will only depend on the low parts:
10247 // CC 1 if low(Op0) > low(Op1)
10248 // CC 3 if low(Op0) <= low(Op1)
10249 //
10250 // VCHLGS Tmp, Op0, Op1
10251 // # fallthrough to JoinMBB
10252 MBB = HiEqMBB;
10253 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10254 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10255 .addReg(Op0).addReg(Op1);
10256 MBB->addSuccessor(JoinMBB);
10257
10258 // Mark CC as live-in to JoinMBB.
10259 JoinMBB->addLiveIn(SystemZ::CC);
10260
10261 MI.eraseFromParent();
10262 return JoinMBB;
10263}
10264
10265// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10266// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10267// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10268// whether the field should be inverted after performing BinOpcode (e.g. for
10269// NAND).
10270MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10271 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10272 bool Invert) const {
10273 MachineFunction &MF = *MBB->getParent();
10274 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10275 MachineRegisterInfo &MRI = MF.getRegInfo();
10276
10277 // Extract the operands. Base can be a register or a frame index.
10278 // Src2 can be a register or immediate.
10279 Register Dest = MI.getOperand(0).getReg();
10280 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10281 int64_t Disp = MI.getOperand(2).getImm();
10282 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10283 Register BitShift = MI.getOperand(4).getReg();
10284 Register NegBitShift = MI.getOperand(5).getReg();
10285 unsigned BitSize = MI.getOperand(6).getImm();
10286 DebugLoc DL = MI.getDebugLoc();
10287
10288 // Get the right opcodes for the displacement.
10289 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10290 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10291 assert(LOpcode && CSOpcode && "Displacement out of range");
10292
10293 // Create virtual registers for temporary results.
10294 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10295 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10296 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10297 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10298 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10299
10300 // Insert a basic block for the main loop.
10301 MachineBasicBlock *StartMBB = MBB;
10302 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10303 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10304
10305 // StartMBB:
10306 // ...
10307 // %OrigVal = L Disp(%Base)
10308 // # fall through to LoopMBB
10309 MBB = StartMBB;
10310 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10311 MBB->addSuccessor(LoopMBB);
10312
10313 // LoopMBB:
10314 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10315 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10316 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10317 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10318 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10319 // JNE LoopMBB
10320 // # fall through to DoneMBB
10321 MBB = LoopMBB;
10322 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10323 .addReg(OrigVal).addMBB(StartMBB)
10324 .addReg(Dest).addMBB(LoopMBB);
10325 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10326 .addReg(OldVal).addReg(BitShift).addImm(0);
10327 if (Invert) {
10328 // Perform the operation normally and then invert every bit of the field.
10329 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10330 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
10331 .addReg(RotatedOldVal)
10332 .add(Src2)
10333 .setOperandDead(3);
10334 // XILF with the upper BitSize bits set.
10335 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10336 .addReg(Tmp)
10337 .addImm(-1U << (32 - BitSize))
10338 .setOperandDead(3);
10339 } else if (BinOpcode)
10340 // A simply binary operation.
10341 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10342 .addReg(RotatedOldVal)
10343 .add(Src2)
10344 .setOperandDead(3);
10345 else
10346 // Use RISBG to rotate Src2 into position and use it to replace the
10347 // field in RotatedOldVal.
10348 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10349 .addReg(RotatedOldVal)
10350 .addReg(Src2.getReg())
10351 .addImm(32)
10352 .addImm(31 + BitSize)
10353 .addImm(32 - BitSize)
10354 .setOperandDead(6);
10355 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10356 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10357 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10358 .addReg(OldVal)
10359 .addReg(NewVal)
10360 .add(Base)
10361 .addImm(Disp);
10362 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10364 MBB->addSuccessor(LoopMBB);
10365 MBB->addSuccessor(DoneMBB);
10366
10367 MI.eraseFromParent();
10368 return DoneMBB;
10369}
10370
10371// Implement EmitInstrWithCustomInserter for subword pseudo
10372// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10373// instruction that should be used to compare the current field with the
10374// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10375// for when the current field should be kept.
10376MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10377 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10378 unsigned KeepOldMask) const {
10379 MachineFunction &MF = *MBB->getParent();
10380 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10381 MachineRegisterInfo &MRI = MF.getRegInfo();
10382
10383 // Extract the operands. Base can be a register or a frame index.
10384 Register Dest = MI.getOperand(0).getReg();
10385 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10386 int64_t Disp = MI.getOperand(2).getImm();
10387 Register Src2 = MI.getOperand(3).getReg();
10388 Register BitShift = MI.getOperand(4).getReg();
10389 Register NegBitShift = MI.getOperand(5).getReg();
10390 unsigned BitSize = MI.getOperand(6).getImm();
10391 DebugLoc DL = MI.getDebugLoc();
10392
10393 // Get the right opcodes for the displacement.
10394 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10395 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10396 assert(LOpcode && CSOpcode && "Displacement out of range");
10397
10398 // Create virtual registers for temporary results.
10399 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10400 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10401 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10402 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10403 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10404 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10405
10406 // Insert 3 basic blocks for the loop.
10407 MachineBasicBlock *StartMBB = MBB;
10408 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10409 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10410 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10411 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10412
10413 // StartMBB:
10414 // ...
10415 // %OrigVal = L Disp(%Base)
10416 // # fall through to LoopMBB
10417 MBB = StartMBB;
10418 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10419 MBB->addSuccessor(LoopMBB);
10420
10421 // LoopMBB:
10422 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10423 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10424 // CompareOpcode %RotatedOldVal, %Src2
10425 // BRC KeepOldMask, UpdateMBB
10426 MBB = LoopMBB;
10427 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10428 .addReg(OrigVal).addMBB(StartMBB)
10429 .addReg(Dest).addMBB(UpdateMBB);
10430 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10431 .addReg(OldVal).addReg(BitShift).addImm(0);
10432 BuildMI(MBB, DL, TII->get(CompareOpcode))
10433 .addReg(RotatedOldVal).addReg(Src2);
10434 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10435 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10436 MBB->addSuccessor(UpdateMBB);
10437 MBB->addSuccessor(UseAltMBB);
10438
10439 // UseAltMBB:
10440 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10441 // # fall through to UpdateMBB
10442 MBB = UseAltMBB;
10443 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10444 .addReg(RotatedOldVal)
10445 .addReg(Src2)
10446 .addImm(32)
10447 .addImm(31 + BitSize)
10448 .addImm(0)
10449 .setOperandDead(6);
10450 MBB->addSuccessor(UpdateMBB);
10451
10452 // UpdateMBB:
10453 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10454 // [ %RotatedAltVal, UseAltMBB ]
10455 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10456 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10457 // JNE LoopMBB
10458 // # fall through to DoneMBB
10459 MBB = UpdateMBB;
10460 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10461 .addReg(RotatedOldVal).addMBB(LoopMBB)
10462 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10463 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10464 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10465 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10466 .addReg(OldVal)
10467 .addReg(NewVal)
10468 .add(Base)
10469 .addImm(Disp);
10470 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10472 MBB->addSuccessor(LoopMBB);
10473 MBB->addSuccessor(DoneMBB);
10474
10475 MI.eraseFromParent();
10476 return DoneMBB;
10477}
10478
10479// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10480// instruction MI.
10482SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10483 MachineBasicBlock *MBB) const {
10484 MachineFunction &MF = *MBB->getParent();
10485 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10486 MachineRegisterInfo &MRI = MF.getRegInfo();
10487
10488 // Extract the operands. Base can be a register or a frame index.
10489 Register Dest = MI.getOperand(0).getReg();
10490 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10491 int64_t Disp = MI.getOperand(2).getImm();
10492 Register CmpVal = MI.getOperand(3).getReg();
10493 Register OrigSwapVal = MI.getOperand(4).getReg();
10494 Register BitShift = MI.getOperand(5).getReg();
10495 Register NegBitShift = MI.getOperand(6).getReg();
10496 int64_t BitSize = MI.getOperand(7).getImm();
10497 DebugLoc DL = MI.getDebugLoc();
10498
10499 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10500
10501 // Get the right opcodes for the displacement and zero-extension.
10502 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10503 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10504 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10505 assert(LOpcode && CSOpcode && "Displacement out of range");
10506
10507 // Create virtual registers for temporary results.
10508 Register OrigOldVal = MRI.createVirtualRegister(RC);
10509 Register OldVal = MRI.createVirtualRegister(RC);
10510 Register SwapVal = MRI.createVirtualRegister(RC);
10511 Register StoreVal = MRI.createVirtualRegister(RC);
10512 Register OldValRot = MRI.createVirtualRegister(RC);
10513 Register RetryOldVal = MRI.createVirtualRegister(RC);
10514 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10515
10516 // Insert 2 basic blocks for the loop.
10517 MachineBasicBlock *StartMBB = MBB;
10518 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10519 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10520 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10521
10522 // StartMBB:
10523 // ...
10524 // %OrigOldVal = L Disp(%Base)
10525 // # fall through to LoopMBB
10526 MBB = StartMBB;
10527 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10528 .add(Base)
10529 .addImm(Disp)
10530 .addReg(0);
10531 MBB->addSuccessor(LoopMBB);
10532
10533 // LoopMBB:
10534 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10535 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10536 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10537 // ^^ The low BitSize bits contain the field
10538 // of interest.
10539 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10540 // ^^ Replace the upper 32-BitSize bits of the
10541 // swap value with those that we loaded and rotated.
10542 // %Dest = LL[CH] %OldValRot
10543 // CR %Dest, %CmpVal
10544 // JNE DoneMBB
10545 // # Fall through to SetMBB
10546 MBB = LoopMBB;
10547 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10548 .addReg(OrigOldVal).addMBB(StartMBB)
10549 .addReg(RetryOldVal).addMBB(SetMBB);
10550 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10551 .addReg(OrigSwapVal).addMBB(StartMBB)
10552 .addReg(RetrySwapVal).addMBB(SetMBB);
10553 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10554 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10555 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10556 .addReg(SwapVal)
10557 .addReg(OldValRot)
10558 .addImm(32)
10559 .addImm(63 - BitSize)
10560 .addImm(0)
10561 .setOperandDead(6);
10562 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10563 .addReg(OldValRot);
10564 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10565 .addReg(Dest).addReg(CmpVal);
10566 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10569 MBB->addSuccessor(DoneMBB);
10570 MBB->addSuccessor(SetMBB);
10571
10572 // SetMBB:
10573 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10574 // ^^ Rotate the new field to its proper position.
10575 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10576 // JNE LoopMBB
10577 // # fall through to ExitMBB
10578 MBB = SetMBB;
10579 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10580 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10581 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10582 .addReg(OldVal)
10583 .addReg(StoreVal)
10584 .add(Base)
10585 .addImm(Disp);
10586 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10588 MBB->addSuccessor(LoopMBB);
10589 MBB->addSuccessor(DoneMBB);
10590
10591 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10592 // to the block after the loop. At this point, CC may have been defined
10593 // either by the CR in LoopMBB or by the CS in SetMBB.
10594 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10595 DoneMBB->addLiveIn(SystemZ::CC);
10596
10597 MI.eraseFromParent();
10598 return DoneMBB;
10599}
10600
10602SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10604 unsigned Opcode, bool IsMemset) const {
10605 MachineFunction &MF = *MBB->getParent();
10606 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10607 MachineRegisterInfo &MRI = MF.getRegInfo();
10608 DebugLoc DL = MI.getDebugLoc();
10609
10610 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10611 uint64_t DestDisp = MI.getOperand(1).getImm();
10612 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10613 uint64_t SrcDisp;
10614
10615 // Fold the displacement Disp if it is out of range.
10616 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10617 if (!isUInt<12>(Disp)) {
10618 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10619 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10620 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10621 .add(Base).addImm(Disp).addReg(0);
10623 Disp = 0;
10624 }
10625 };
10626
10627 if (!IsMemset) {
10628 SrcBase = earlyUseOperand(MI.getOperand(2));
10629 SrcDisp = MI.getOperand(3).getImm();
10630 } else {
10631 SrcBase = DestBase;
10632 SrcDisp = DestDisp++;
10633 foldDisplIfNeeded(DestBase, DestDisp);
10634 }
10635
10636 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10637 bool IsImmForm = LengthMO.isImm();
10638 bool IsRegForm = !IsImmForm;
10639
10640 // Build and insert one Opcode of Length, with special treatment for memset.
10641 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10643 MachineOperand DBase, uint64_t DDisp,
10644 MachineOperand SBase, uint64_t SDisp,
10645 unsigned Length) -> void {
10646 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10647 if (IsMemset) {
10648 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10649 if (ByteMO.isImm())
10650 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10651 .add(SBase).addImm(SDisp).add(ByteMO);
10652 else
10653 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10654 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10655 if (--Length == 0)
10656 return;
10657 }
10658 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10659 .add(DBase).addImm(DDisp).addImm(Length)
10660 .add(SBase).addImm(SDisp)
10661 .setMemRefs(MI.memoperands());
10662 };
10663
10664 bool NeedsLoop = false;
10665 uint64_t ImmLength = 0;
10666 Register LenAdjReg = SystemZ::NoRegister;
10667 if (IsImmForm) {
10668 ImmLength = LengthMO.getImm();
10669 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10670 if (ImmLength == 0) {
10671 MI.eraseFromParent();
10672 return MBB;
10673 }
10674 if (Opcode == SystemZ::CLC) {
10675 if (ImmLength > 3 * 256)
10676 // A two-CLC sequence is a clear win over a loop, not least because
10677 // it needs only one branch. A three-CLC sequence needs the same
10678 // number of branches as a loop (i.e. 2), but is shorter. That
10679 // brings us to lengths greater than 768 bytes. It seems relatively
10680 // likely that a difference will be found within the first 768 bytes,
10681 // so we just optimize for the smallest number of branch
10682 // instructions, in order to avoid polluting the prediction buffer
10683 // too much.
10684 NeedsLoop = true;
10685 } else if (ImmLength > 6 * 256)
10686 // The heuristic we use is to prefer loops for anything that would
10687 // require 7 or more MVCs. With these kinds of sizes there isn't much
10688 // to choose between straight-line code and looping code, since the
10689 // time will be dominated by the MVCs themselves.
10690 NeedsLoop = true;
10691 } else {
10692 NeedsLoop = true;
10693 LenAdjReg = LengthMO.getReg();
10694 }
10695
10696 // When generating more than one CLC, all but the last will need to
10697 // branch to the end when a difference is found.
10698 MachineBasicBlock *EndMBB =
10699 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10701 : nullptr);
10702
10703 if (NeedsLoop) {
10704 Register StartCountReg =
10705 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10706 if (IsImmForm) {
10707 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10708 ImmLength &= 255;
10709 } else {
10710 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10711 .addReg(LenAdjReg)
10712 .addReg(0)
10713 .addImm(8);
10714 }
10715
10716 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10717 auto loadZeroAddress = [&]() -> MachineOperand {
10718 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10719 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10720 return MachineOperand::CreateReg(Reg, false);
10721 };
10722 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10723 DestBase = loadZeroAddress();
10724 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10725 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10726
10727 MachineBasicBlock *StartMBB = nullptr;
10728 MachineBasicBlock *LoopMBB = nullptr;
10729 MachineBasicBlock *NextMBB = nullptr;
10730 MachineBasicBlock *DoneMBB = nullptr;
10731 MachineBasicBlock *AllDoneMBB = nullptr;
10732
10733 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10734 Register StartDestReg =
10735 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10736
10737 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10738 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10739 Register ThisDestReg =
10740 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10741 Register NextSrcReg = MRI.createVirtualRegister(RC);
10742 Register NextDestReg =
10743 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10744 RC = &SystemZ::GR64BitRegClass;
10745 Register ThisCountReg = MRI.createVirtualRegister(RC);
10746 Register NextCountReg = MRI.createVirtualRegister(RC);
10747
10748 if (IsRegForm) {
10749 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10750 StartMBB = SystemZ::emitBlockAfter(MBB);
10751 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10752 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10753 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10754
10755 // MBB:
10756 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10757 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10758 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10759 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10761 .addMBB(AllDoneMBB);
10762 MBB->addSuccessor(AllDoneMBB);
10763 if (!IsMemset)
10764 MBB->addSuccessor(StartMBB);
10765 else {
10766 // MemsetOneCheckMBB:
10767 // # Jump to MemsetOneMBB for a memset of length 1, or
10768 // # fall thru to StartMBB.
10769 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10770 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10771 MBB->addSuccessor(MemsetOneCheckMBB);
10772 MBB = MemsetOneCheckMBB;
10773 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10774 .addReg(LenAdjReg).addImm(-1);
10775 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10777 .addMBB(MemsetOneMBB);
10778 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10779 MBB->addSuccessor(StartMBB, {90, 100});
10780
10781 // MemsetOneMBB:
10782 // # Jump back to AllDoneMBB after a single MVI or STC.
10783 MBB = MemsetOneMBB;
10784 insertMemMemOp(MBB, MBB->end(),
10785 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10786 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10787 1);
10788 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10789 MBB->addSuccessor(AllDoneMBB);
10790 }
10791
10792 // StartMBB:
10793 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10794 MBB = StartMBB;
10795 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10796 .addReg(StartCountReg).addImm(0);
10797 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10799 .addMBB(DoneMBB);
10800 MBB->addSuccessor(DoneMBB);
10801 MBB->addSuccessor(LoopMBB);
10802 }
10803 else {
10804 StartMBB = MBB;
10805 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10806 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10807 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10808
10809 // StartMBB:
10810 // # fall through to LoopMBB
10811 MBB->addSuccessor(LoopMBB);
10812
10813 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10814 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10815 if (EndMBB && !ImmLength)
10816 // If the loop handled the whole CLC range, DoneMBB will be empty with
10817 // CC live-through into EndMBB, so add it as live-in.
10818 DoneMBB->addLiveIn(SystemZ::CC);
10819 }
10820
10821 // LoopMBB:
10822 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10823 // [ %NextDestReg, NextMBB ]
10824 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10825 // [ %NextSrcReg, NextMBB ]
10826 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10827 // [ %NextCountReg, NextMBB ]
10828 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10829 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10830 // ( JLH EndMBB )
10831 //
10832 // The prefetch is used only for MVC. The JLH is used only for CLC.
10833 MBB = LoopMBB;
10834 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10835 .addReg(StartDestReg).addMBB(StartMBB)
10836 .addReg(NextDestReg).addMBB(NextMBB);
10837 if (!HaveSingleBase)
10838 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10839 .addReg(StartSrcReg).addMBB(StartMBB)
10840 .addReg(NextSrcReg).addMBB(NextMBB);
10841 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10842 .addReg(StartCountReg).addMBB(StartMBB)
10843 .addReg(NextCountReg).addMBB(NextMBB);
10844 if (Opcode == SystemZ::MVC)
10845 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10847 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10848 insertMemMemOp(MBB, MBB->end(),
10849 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10850 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10851 if (EndMBB) {
10852 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10854 .addMBB(EndMBB);
10855 MBB->addSuccessor(EndMBB);
10856 MBB->addSuccessor(NextMBB);
10857 }
10858
10859 // NextMBB:
10860 // %NextDestReg = LA 256(%ThisDestReg)
10861 // %NextSrcReg = LA 256(%ThisSrcReg)
10862 // %NextCountReg = AGHI %ThisCountReg, -1
10863 // CGHI %NextCountReg, 0
10864 // JLH LoopMBB
10865 // # fall through to DoneMBB
10866 //
10867 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
10868 MBB = NextMBB;
10869 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
10870 .addReg(ThisDestReg).addImm(256).addReg(0);
10871 if (!HaveSingleBase)
10872 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
10873 .addReg(ThisSrcReg).addImm(256).addReg(0);
10874 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
10875 .addReg(ThisCountReg)
10876 .addImm(-1)
10877 .setOperandDead(3);
10878 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10879 .addReg(NextCountReg).addImm(0);
10880 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10882 .addMBB(LoopMBB);
10883 MBB->addSuccessor(LoopMBB);
10884 MBB->addSuccessor(DoneMBB);
10885
10886 MBB = DoneMBB;
10887 if (IsRegForm) {
10888 // DoneMBB:
10889 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
10890 // # Use EXecute Relative Long for the remainder of the bytes. The target
10891 // instruction of the EXRL will have a length field of 1 since 0 is an
10892 // illegal value. The number of bytes processed becomes (%LenAdjReg &
10893 // 0xff) + 1.
10894 // # Fall through to AllDoneMBB.
10895 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10896 Register RemDestReg = HaveSingleBase ? RemSrcReg
10897 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10898 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
10899 .addReg(StartDestReg).addMBB(StartMBB)
10900 .addReg(NextDestReg).addMBB(NextMBB);
10901 if (!HaveSingleBase)
10902 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
10903 .addReg(StartSrcReg).addMBB(StartMBB)
10904 .addReg(NextSrcReg).addMBB(NextMBB);
10905 if (IsMemset)
10906 insertMemMemOp(MBB, MBB->end(),
10907 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
10908 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
10909 MachineInstrBuilder EXRL_MIB =
10910 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
10911 .addImm(Opcode)
10912 .addReg(LenAdjReg)
10913 .addReg(RemDestReg).addImm(DestDisp)
10914 .addReg(RemSrcReg).addImm(SrcDisp);
10915 MBB->addSuccessor(AllDoneMBB);
10916 MBB = AllDoneMBB;
10917 if (Opcode != SystemZ::MVC) {
10918 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
10919 if (EndMBB)
10920 MBB->addLiveIn(SystemZ::CC);
10921 }
10922 }
10923 MF.getProperties().resetNoPHIs();
10924 }
10925
10926 // Handle any remaining bytes with straight-line code.
10927 while (ImmLength > 0) {
10928 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
10929 // The previous iteration might have created out-of-range displacements.
10930 // Apply them using LA/LAY if so.
10931 foldDisplIfNeeded(DestBase, DestDisp);
10932 foldDisplIfNeeded(SrcBase, SrcDisp);
10933 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
10934 DestDisp += ThisLength;
10935 SrcDisp += ThisLength;
10936 ImmLength -= ThisLength;
10937 // If there's another CLC to go, branch to the end if a difference
10938 // was found.
10939 if (EndMBB && ImmLength > 0) {
10940 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
10941 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10943 .addMBB(EndMBB);
10944 MBB->addSuccessor(EndMBB);
10945 MBB->addSuccessor(NextMBB);
10946 MBB = NextMBB;
10947 }
10948 }
10949 if (EndMBB) {
10950 MBB->addSuccessor(EndMBB);
10951 MBB = EndMBB;
10952 MBB->addLiveIn(SystemZ::CC);
10953 }
10954
10955 MI.eraseFromParent();
10956 return MBB;
10957}
10958
10960SystemZTargetLowering::emitMemmoveImm(MachineInstr &MI,
10961 MachineBasicBlock *MBB) const {
10962 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10963
10964 DebugLoc DL = MI.getDebugLoc();
10965 MachineOperand DstAddr = earlyUseOperand(MI.getOperand(0));
10966 MachineOperand SrcAddr = earlyUseOperand(MI.getOperand(1));
10967 uint64_t Len = MI.getOperand(2).getImm();
10968 assert(Len > 0 && Len <= 256 && "Memmove of of unsupported constant length.");
10969
10970 // Use MVC or MVCRL after comparing the addresses.
10971 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
10972 MachineBasicBlock *MvcMBB = SystemZ::emitBlockAfter(MBB);
10973 MachineBasicBlock *MvcrlMBB = SystemZ::emitBlockAfter(MvcMBB);
10974 MBB->addSuccessor(MvcMBB);
10975 MBB->addSuccessor(MvcrlMBB);
10976 MvcMBB->addSuccessor(DoneMBB);
10977 MvcrlMBB->addSuccessor(DoneMBB);
10978
10979 BuildMI(MBB, DL, TII->get(SystemZ::CLGR)).add(SrcAddr).add(DstAddr);
10980 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10982 .addMBB(MvcrlMBB);
10983
10984 BuildMI(MvcMBB, DL, TII->get(SystemZ::MVC))
10985 .add(DstAddr).addImm(0)
10986 .addImm(Len)
10987 .add(SrcAddr).addImm(0)
10988 .setMemRefs(MI.memoperands());
10989 BuildMI(MvcMBB, DL, TII->get(SystemZ::J)).addMBB(DoneMBB);
10990
10991 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::LHI), SystemZ::R0L).addImm(Len - 1);
10992 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::MVCRL))
10993 .add(DstAddr).addImm(0)
10994 .add(SrcAddr).addImm(0)
10995 .setMemRefs(MI.memoperands());
10996
10997 MI.eraseFromParent();
10998 return DoneMBB;
10999}
11000
11001// Decompose string pseudo-instruction MI into a loop that continually performs
11002// Opcode until CC != 3.
11003MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
11004 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11005 MachineFunction &MF = *MBB->getParent();
11006 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11007 MachineRegisterInfo &MRI = MF.getRegInfo();
11008 DebugLoc DL = MI.getDebugLoc();
11009
11010 uint64_t End1Reg = MI.getOperand(0).getReg();
11011 uint64_t Start1Reg = MI.getOperand(1).getReg();
11012 uint64_t Start2Reg = MI.getOperand(2).getReg();
11013 uint64_t CharReg = MI.getOperand(3).getReg();
11014
11015 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
11016 uint64_t This1Reg = MRI.createVirtualRegister(RC);
11017 uint64_t This2Reg = MRI.createVirtualRegister(RC);
11018 uint64_t End2Reg = MRI.createVirtualRegister(RC);
11019
11020 MachineBasicBlock *StartMBB = MBB;
11021 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
11022 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
11023
11024 // StartMBB:
11025 // # fall through to LoopMBB
11026 MBB->addSuccessor(LoopMBB);
11027
11028 // LoopMBB:
11029 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
11030 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
11031 // R0L = %CharReg
11032 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
11033 // JO LoopMBB
11034 // # fall through to DoneMBB
11035 //
11036 // The load of R0L can be hoisted by post-RA LICM.
11037 MBB = LoopMBB;
11038
11039 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
11040 .addReg(Start1Reg).addMBB(StartMBB)
11041 .addReg(End1Reg).addMBB(LoopMBB);
11042 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
11043 .addReg(Start2Reg).addMBB(StartMBB)
11044 .addReg(End2Reg).addMBB(LoopMBB);
11045 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
11046 BuildMI(MBB, DL, TII->get(Opcode))
11047 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
11048 .addReg(This1Reg).addReg(This2Reg);
11049 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11051 MBB->addSuccessor(LoopMBB);
11052 MBB->addSuccessor(DoneMBB);
11053
11054 DoneMBB->addLiveIn(SystemZ::CC);
11055
11056 MI.eraseFromParent();
11057 return DoneMBB;
11058}
11059
11060// Update TBEGIN instruction with final opcode and register clobbers.
11061MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
11062 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
11063 bool NoFloat) const {
11064 MachineFunction &MF = *MBB->getParent();
11065 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11066 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11067
11068 // Update opcode.
11069 MI.setDesc(TII->get(Opcode));
11070
11071 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
11072 // Make sure to add the corresponding GRSM bits if they are missing.
11073 uint64_t Control = MI.getOperand(2).getImm();
11074 static const unsigned GPRControlBit[16] = {
11075 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
11076 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
11077 };
11078 Control |= GPRControlBit[15];
11079 if (TFI->hasFP(MF))
11080 Control |= GPRControlBit[11];
11081 MI.getOperand(2).setImm(Control);
11082
11083 // Add GPR clobbers.
11084 for (int I = 0; I < 16; I++) {
11085 if ((Control & GPRControlBit[I]) == 0) {
11086 unsigned Reg = SystemZMC::GR64Regs[I];
11087 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11088 }
11089 }
11090
11091 // Add FPR/VR clobbers.
11092 if (!NoFloat && (Control & 4) != 0) {
11093 if (Subtarget.hasVector()) {
11094 for (unsigned Reg : SystemZMC::VR128Regs) {
11095 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11096 }
11097 } else {
11098 for (unsigned Reg : SystemZMC::FP64Regs) {
11099 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11100 }
11101 }
11102 }
11103
11104 return MBB;
11105}
11106
11107MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
11108 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11109 MachineFunction &MF = *MBB->getParent();
11110 MachineRegisterInfo *MRI = &MF.getRegInfo();
11111 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11112 DebugLoc DL = MI.getDebugLoc();
11113
11114 Register SrcReg = MI.getOperand(0).getReg();
11115
11116 // Create new virtual register of the same class as source.
11117 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
11118 Register DstReg = MRI->createVirtualRegister(RC);
11119
11120 // Replace pseudo with a normal load-and-test that models the def as
11121 // well.
11122 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
11123 .addReg(SrcReg)
11124 .setMIFlags(MI.getFlags());
11125 MI.eraseFromParent();
11126
11127 return MBB;
11128}
11129
11130MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11132 MachineFunction &MF = *MBB->getParent();
11133 MachineRegisterInfo *MRI = &MF.getRegInfo();
11134 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11135 DebugLoc DL = MI.getDebugLoc();
11136 const unsigned ProbeSize = getStackProbeSize(MF);
11137 Register DstReg = MI.getOperand(0).getReg();
11138 Register SizeReg = MI.getOperand(2).getReg();
11139
11140 MachineBasicBlock *StartMBB = MBB;
11141 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11142 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11143 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11144 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11145 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11146
11147 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11149
11150 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11151 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11152
11153 // LoopTestMBB
11154 // BRC TailTestMBB
11155 // # fallthrough to LoopBodyMBB
11156 StartMBB->addSuccessor(LoopTestMBB);
11157 MBB = LoopTestMBB;
11158 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11159 .addReg(SizeReg)
11160 .addMBB(StartMBB)
11161 .addReg(IncReg)
11162 .addMBB(LoopBodyMBB);
11163 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11164 .addReg(PHIReg)
11165 .addImm(ProbeSize);
11166 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11168 .addMBB(TailTestMBB);
11169 MBB->addSuccessor(LoopBodyMBB);
11170 MBB->addSuccessor(TailTestMBB);
11171
11172 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11173 // J LoopTestMBB
11174 MBB = LoopBodyMBB;
11175 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11176 .addReg(PHIReg)
11177 .addImm(ProbeSize)
11178 .setOperandDead(3);
11179 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11180 .addReg(SystemZ::R15D)
11181 .addImm(ProbeSize)
11182 .setOperandDead(3);
11183 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11184 .addReg(SystemZ::R15D)
11185 .addReg(SystemZ::R15D)
11186 .addImm(ProbeSize - 8)
11187 .addReg(0)
11188 .setOperandDead(4)
11189 .setMemRefs(VolLdMMO);
11190 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11191 MBB->addSuccessor(LoopTestMBB);
11192
11193 // TailTestMBB
11194 // BRC DoneMBB
11195 // # fallthrough to TailMBB
11196 MBB = TailTestMBB;
11197 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11198 .addReg(PHIReg)
11199 .addImm(0);
11200 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11202 .addMBB(DoneMBB);
11203 MBB->addSuccessor(TailMBB);
11204 MBB->addSuccessor(DoneMBB);
11205
11206 // TailMBB
11207 // # fallthrough to DoneMBB
11208 MBB = TailMBB;
11209 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11210 .addReg(SystemZ::R15D)
11211 .addReg(PHIReg)
11212 .setOperandDead(3);
11213 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11214 .addReg(SystemZ::R15D)
11215 .addReg(SystemZ::R15D)
11216 .addImm(-8)
11217 .addReg(PHIReg)
11218 .setOperandDead(4)
11219 .setMemRefs(VolLdMMO);
11220 MBB->addSuccessor(DoneMBB);
11221
11222 // DoneMBB
11223 MBB = DoneMBB;
11224 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11225 .addReg(SystemZ::R15D);
11226
11227 MI.eraseFromParent();
11228 return DoneMBB;
11229}
11230
11231SDValue SystemZTargetLowering::
11232getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11234 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11235 SDLoc DL(SP);
11236 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11237 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11238}
11239
11240// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11241// a dead early-clobber def reg that will be used as a scratch register
11242// when the pseudo is expanded.
11243MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11244 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11245 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11246 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11247 DebugLoc DL = MI.getDebugLoc();
11248 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11249 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11250 .addFrameIndex(MI.getOperand(0).getIndex())
11251 .addImm(MI.getOperand(1).getImm());
11252 MI.eraseFromParent();
11253 return MBB;
11254}
11255
11258 switch (MI.getOpcode()) {
11259 case SystemZ::ADJCALLSTACKDOWN:
11260 case SystemZ::ADJCALLSTACKUP:
11261 return emitAdjCallStack(MI, MBB);
11262
11263 case SystemZ::Select32:
11264 case SystemZ::Select64:
11265 case SystemZ::Select128:
11266 case SystemZ::SelectF32:
11267 case SystemZ::SelectF64:
11268 case SystemZ::SelectF128:
11269 case SystemZ::SelectVR32:
11270 case SystemZ::SelectVR64:
11271 case SystemZ::SelectVR128:
11272 return emitSelect(MI, MBB);
11273
11274 case SystemZ::CondStore8Mux:
11275 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11276 case SystemZ::CondStore8MuxInv:
11277 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11278 case SystemZ::CondStore16Mux:
11279 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11280 case SystemZ::CondStore16MuxInv:
11281 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11282 case SystemZ::CondStore32Mux:
11283 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11284 case SystemZ::CondStore32MuxInv:
11285 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11286 case SystemZ::CondStore8:
11287 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11288 case SystemZ::CondStore8Inv:
11289 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11290 case SystemZ::CondStore16:
11291 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11292 case SystemZ::CondStore16Inv:
11293 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11294 case SystemZ::CondStore32:
11295 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11296 case SystemZ::CondStore32Inv:
11297 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11298 case SystemZ::CondStore64:
11299 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11300 case SystemZ::CondStore64Inv:
11301 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11302 case SystemZ::CondStoreF32:
11303 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11304 case SystemZ::CondStoreF32Inv:
11305 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11306 case SystemZ::CondStoreF64:
11307 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11308 case SystemZ::CondStoreF64Inv:
11309 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11310
11311 case SystemZ::SCmp128Hi:
11312 return emitICmp128Hi(MI, MBB, false);
11313 case SystemZ::UCmp128Hi:
11314 return emitICmp128Hi(MI, MBB, true);
11315
11316
11317 case SystemZ::ATOMIC_SWAPW:
11318 return emitAtomicLoadBinary(MI, MBB, 0);
11319
11320 case SystemZ::ATOMIC_LOADW_AR:
11321 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11322 case SystemZ::ATOMIC_LOADW_AFI:
11323 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11324
11325 case SystemZ::ATOMIC_LOADW_SR:
11326 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11327
11328 case SystemZ::ATOMIC_LOADW_NR:
11329 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11330 case SystemZ::ATOMIC_LOADW_NILH:
11331 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11332
11333 case SystemZ::ATOMIC_LOADW_OR:
11334 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11335 case SystemZ::ATOMIC_LOADW_OILH:
11336 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11337
11338 case SystemZ::ATOMIC_LOADW_XR:
11339 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11340 case SystemZ::ATOMIC_LOADW_XILF:
11341 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11342
11343 case SystemZ::ATOMIC_LOADW_NRi:
11344 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11345 case SystemZ::ATOMIC_LOADW_NILHi:
11346 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11347
11348 case SystemZ::ATOMIC_LOADW_MIN:
11349 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11350 case SystemZ::ATOMIC_LOADW_MAX:
11351 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11352 case SystemZ::ATOMIC_LOADW_UMIN:
11353 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11354 case SystemZ::ATOMIC_LOADW_UMAX:
11355 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11356
11357 case SystemZ::ATOMIC_CMP_SWAPW:
11358 return emitAtomicCmpSwapW(MI, MBB);
11359 case SystemZ::MVCImm:
11360 case SystemZ::MVCReg:
11361 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11362 case SystemZ::NCImm:
11363 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11364 case SystemZ::OCImm:
11365 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11366 case SystemZ::XCImm:
11367 case SystemZ::XCReg:
11368 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11369 case SystemZ::CLCImm:
11370 case SystemZ::CLCReg:
11371 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11372 case SystemZ::MemsetImmImm:
11373 case SystemZ::MemsetImmReg:
11374 case SystemZ::MemsetRegImm:
11375 case SystemZ::MemsetRegReg:
11376 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11377 case SystemZ::MemmoveImm:
11378 return emitMemmoveImm(MI, MBB);
11379 case SystemZ::CLSTLoop:
11380 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11381 case SystemZ::MVSTLoop:
11382 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11383 case SystemZ::SRSTLoop:
11384 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11385 case SystemZ::TBEGIN:
11386 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11387 case SystemZ::TBEGIN_nofloat:
11388 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11389 case SystemZ::TBEGINC:
11390 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11391 case SystemZ::LTEBRCompare_Pseudo:
11392 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11393 case SystemZ::LTDBRCompare_Pseudo:
11394 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11395 case SystemZ::LTXBRCompare_Pseudo:
11396 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11397
11398 case SystemZ::PROBED_ALLOCA:
11399 return emitProbedAlloca(MI, MBB);
11400 case SystemZ::EH_SjLj_SetJmp:
11401 return emitEHSjLjSetJmp(MI, MBB);
11402 case SystemZ::EH_SjLj_LongJmp:
11403 return emitEHSjLjLongJmp(MI, MBB);
11404
11405 case TargetOpcode::STACKMAP:
11406 case TargetOpcode::PATCHPOINT:
11407 return emitPatchPoint(MI, MBB);
11408
11409 case SystemZ::MOV_STACKGUARD_DAG:
11410 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11411
11412 case SystemZ::CMP_STACKGUARD_DAG:
11413 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11414
11415 default:
11416 llvm_unreachable("Unexpected instr type to insert");
11417 }
11418}
11419
11420SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11421 SelectionDAG &DAG) const {
11422 SDLoc dl(Op);
11423 /*
11424 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11425 settings:
11426 00 Round to nearest
11427 01 Round to 0
11428 10 Round to +inf
11429 11 Round to -inf
11430
11431 FLT_ROUNDS, on the other hand, expects the following:
11432 -1 Undefined
11433 0 Round to 0
11434 1 Round to nearest
11435 2 Round to +inf
11436 3 Round to -inf
11437 */
11438
11439 // Save FPC to register.
11440 SDValue Chain = Op.getOperand(0);
11441 SDValue EFPC(
11442 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11443 Chain = EFPC.getValue(1);
11444
11445 // Transform as necessary
11446 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11447 DAG.getConstant(3, dl, MVT::i32));
11448 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11449 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11450 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11451 DAG.getConstant(1, dl, MVT::i32)));
11452
11453 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11454 DAG.getConstant(1, dl, MVT::i32));
11455 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11456
11457 return DAG.getMergeValues({RetVal, Chain}, dl);
11458}
11459
11460SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11461 SelectionDAG &DAG) const {
11462 EVT VT = Op.getValueType();
11463 Op = Op.getOperand(0);
11464 EVT OpVT = Op.getValueType();
11465
11466 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11467
11468 SDLoc DL(Op);
11469
11470 // load a 0 vector for the third operand of VSUM.
11471 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11472
11473 // execute VSUM.
11474 switch (OpVT.getScalarSizeInBits()) {
11475 case 8:
11476 case 16:
11477 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11478 [[fallthrough]];
11479 case 32:
11480 case 64:
11481 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11482 DAG.getBitcast(Op.getValueType(), Zero));
11483 break;
11484 case 128:
11485 break; // VSUM over v1i128 should not happen and would be a noop
11486 default:
11487 llvm_unreachable("Unexpected scalar size.");
11488 }
11489 // Cast to original vector type, retrieve last element.
11490 return DAG.getNode(
11491 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11492 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11493}
11494
11495static void printFunctionArgExts(const Function *F, raw_ostream &OS) {
11496 FunctionType *FT = F->getFunctionType();
11497 const AttributeList &Attrs = F->getAttributes();
11498 if (Attrs.hasRetAttrs())
11499 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11500 OS << *F->getReturnType() << " @" << F->getName() << "(";
11501 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11502 if (I)
11503 OS << ", ";
11504 OS << *FT->getParamType(I);
11505 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11506 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11507 if (ArgAttrs.hasAttribute(A))
11508 OS << " " << Attribute::getNameFromAttrKind(A);
11509 }
11510 if (F->isVarArg())
11511 OS << ", ...";
11512 OS << ")\n";
11513}
11514
11515bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11516 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11517 if (Itr == IsInternalCache.end())
11518 Itr = IsInternalCache
11519 .insert(std::pair<const Function *, bool>(
11520 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11521 .first;
11522 return Itr->second;
11523}
11524
11525bool SystemZTargetLowering::enableNarrowIntArgsVerification() const {
11526 if (!Subtarget.isTargetELF())
11527 return false;
11528
11530 return EnableIntArgExtCheck;
11531
11532#ifdef NDEBUG
11533 return false;
11534#endif
11535
11537}
11538
11539void SystemZTargetLowering::verifyNarrowIntegerArgs_Call(
11540 CallLoweringInfo &CLI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11541 const Function *F, SDValue Callee) const {
11542 if (!enableNarrowIntArgsVerification())
11543 return;
11544 bool IsInternal = false;
11545 const Function *CalleeFn = nullptr;
11546 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11547 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11548 IsInternal = isInternal(CalleeFn);
11549 bool C_ABI = CLI.CallConv == CallingConv::C && !IsInternal;
11550 if (!verifyNarrowIntegerArgs(C_ABI, Outs, CalleeFn, /*IsRet=*/false)) {
11551 errs() << "Callee: ";
11552 if (CalleeFn != nullptr)
11553 printFunctionArgExts(CalleeFn, errs());
11554 else
11555 errs() << "-\n";
11556 errs() << "Caller: ";
11558 if (CLI.CB)
11559 errs() << " " << *CLI.CB;
11560 llvm_unreachable("");
11561 }
11562 LLVM_DEBUG(dbgs() << "Outgoing call arguments verified as ABI compliant: ";
11563 if (CalleeFn != nullptr) printFunctionArgExts(CalleeFn, dbgs());
11564 else dbgs() << "-\n";);
11565}
11566
11567void SystemZTargetLowering::verifyNarrowIntegerArgs_Ret(
11569 const Function *F) const {
11570 if (!enableNarrowIntArgsVerification())
11571 return;
11572 bool C_ABI = CallConv == CallingConv::C && !isInternal(F);
11573 if (!verifyNarrowIntegerArgs(C_ABI, Outs, F, /*IsRet=*/true)) {
11574 errs() << "Returning from function: ";
11576 llvm_unreachable("");
11577 }
11578 LLVM_DEBUG(dbgs() << "Return argument verified as ABI compliant : ";
11580}
11581
11582// Verify that narrow integer arguments are extended according to the
11583// function header (calllee for a call, containing function for a ret).
11584// If C_ABI is true, an extension attribute must be present.
11585bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11586 bool C_ABI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11587 const Function *FunHeader, bool IsRet) const {
11588 if (IsRet && Outs.size() != 1)
11589 return true;
11590
11591 for (unsigned i = 0; i < Outs.size(); ++i) {
11592 EVT OrigArgVT = Outs[i].ArgVT;
11593 if (!OrigArgVT.isScalarInteger() || OrigArgVT.getSizeInBits() >= 64)
11594 continue;
11595 assert(Outs[i].VT == MVT::i32 && "Unexpected integer argument VT.");
11596 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11597 unsigned OrigIdx = Outs[i].OrigArgIndex;
11598
11599 // Per the C ABI there must be an extension.
11600 if (C_ABI && !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt()) {
11601 errs() << "ERROR: (C ABI violation) missing extension attribute on "
11602 << (IsRet ? "return value" : Twine("arg ") + Twine(OrigIdx))
11603 << ".\n";
11604 return false;
11605 }
11606
11607 // Flags should reflect the attributes of the function header.
11608 if (FunHeader) {
11609 const AttributeList &FunAttrs = FunHeader->getAttributes();
11610 const AttributeSet Attrs =
11611 IsRet ? FunAttrs.getRetAttrs() : FunAttrs.getParamAttrs(OrigIdx);
11612 if (Attrs.hasAttribute(Attribute::SExt) && !Flags.isSExt()) {
11613 errs() << "ERROR: Missing SExt on arg " << OrigIdx << ".\n";
11614 return false;
11615 }
11616 if (Attrs.hasAttribute(Attribute::ZExt) && !Flags.isZExt()) {
11617 errs() << "ERROR: Missing ZExt on arg " << OrigIdx << ".\n";
11618 return false;
11619 }
11620 }
11621 }
11622
11623 return true;
11624}
11625
11627 Module &M, const LibcallLoweringInfo &Libcalls) const {
11628 StringRef GuardMode = M.getStackProtectorGuard();
11629
11630 // In the TLS case, no symbol needs to be inserted.
11631 if (GuardMode == "tls" || GuardMode.empty())
11632 return;
11633
11634 // Otherwise (in the global case), insert the appropriate global variable.
11636}
unsigned NumParts
return SDValue()
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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,...)
const HexagonInstrInfo * TII
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)
#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
SmallVector< MachineOperand, 4 > Cond
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 cl::opt< bool > EnableIntArgExtCheck("argext-abi-check", cl::init(false), cl::desc("Verify that narrow int args are properly extended per the " "SystemZ ABI."))
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 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:406
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
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:62
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:64
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
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:730
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
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)
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:490
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:720
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 integer and floating point boolean values from i1 to a w...
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
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
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
int getNumOccurrences() const
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
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ 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
@ 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.
@ 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
@ 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 bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
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(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
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
initializer< Ty > init(const Ty &Val)
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
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
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
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.