[SystemZ] Add CodeGen support for scalar f64 ops in vector registers
[oota-llvm.git] / lib / Target / SystemZ / SystemZISelLowering.cpp
1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SystemZTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SystemZISelLowering.h"
15 #include "SystemZCallingConv.h"
16 #include "SystemZConstantPoolValue.h"
17 #include "SystemZMachineFunctionInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include <cctype>
25
26 using namespace llvm;
27
28 #define DEBUG_TYPE "systemz-lower"
29
30 namespace {
31 // Represents a sequence for extracting a 0/1 value from an IPM result:
32 // (((X ^ XORValue) + AddValue) >> Bit)
33 struct IPMConversion {
34   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
35     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
36
37   int64_t XORValue;
38   int64_t AddValue;
39   unsigned Bit;
40 };
41
42 // Represents information about a comparison.
43 struct Comparison {
44   Comparison(SDValue Op0In, SDValue Op1In)
45     : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
46
47   // The operands to the comparison.
48   SDValue Op0, Op1;
49
50   // The opcode that should be used to compare Op0 and Op1.
51   unsigned Opcode;
52
53   // A SystemZICMP value.  Only used for integer comparisons.
54   unsigned ICmpType;
55
56   // The mask of CC values that Opcode can produce.
57   unsigned CCValid;
58
59   // The mask of CC values for which the original condition is true.
60   unsigned CCMask;
61 };
62 } // end anonymous namespace
63
64 // Classify VT as either 32 or 64 bit.
65 static bool is32Bit(EVT VT) {
66   switch (VT.getSimpleVT().SimpleTy) {
67   case MVT::i32:
68     return true;
69   case MVT::i64:
70     return false;
71   default:
72     llvm_unreachable("Unsupported type");
73   }
74 }
75
76 // Return a version of MachineOperand that can be safely used before the
77 // final use.
78 static MachineOperand earlyUseOperand(MachineOperand Op) {
79   if (Op.isReg())
80     Op.setIsKill(false);
81   return Op;
82 }
83
84 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &tm,
85                                              const SystemZSubtarget &STI)
86     : TargetLowering(tm), Subtarget(STI) {
87   MVT PtrVT = getPointerTy();
88
89   // Set up the register classes.
90   if (Subtarget.hasHighWord())
91     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
92   else
93     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
94   addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
95   if (Subtarget.hasVector()) {
96     addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
97     addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
98   } else {
99     addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
100     addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
101   }
102   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
103
104   if (Subtarget.hasVector()) {
105     addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
106     addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
107     addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
108     addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
109     addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
110     addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
111   }
112
113   // Compute derived properties from the register classes
114   computeRegisterProperties(Subtarget.getRegisterInfo());
115
116   // Set up special registers.
117   setExceptionPointerRegister(SystemZ::R6D);
118   setExceptionSelectorRegister(SystemZ::R7D);
119   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
120
121   // TODO: It may be better to default to latency-oriented scheduling, however
122   // LLVM's current latency-oriented scheduler can't handle physreg definitions
123   // such as SystemZ has with CC, so set this to the register-pressure
124   // scheduler, because it can.
125   setSchedulingPreference(Sched::RegPressure);
126
127   setBooleanContents(ZeroOrOneBooleanContent);
128   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
129
130   // Instructions are strings of 2-byte aligned 2-byte values.
131   setMinFunctionAlignment(2);
132
133   // Handle operations that are handled in a similar way for all types.
134   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
135        I <= MVT::LAST_FP_VALUETYPE;
136        ++I) {
137     MVT VT = MVT::SimpleValueType(I);
138     if (isTypeLegal(VT)) {
139       // Lower SET_CC into an IPM-based sequence.
140       setOperationAction(ISD::SETCC, VT, Custom);
141
142       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
143       setOperationAction(ISD::SELECT, VT, Expand);
144
145       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
146       setOperationAction(ISD::SELECT_CC, VT, Custom);
147       setOperationAction(ISD::BR_CC,     VT, Custom);
148     }
149   }
150
151   // Expand jump table branches as address arithmetic followed by an
152   // indirect jump.
153   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
154
155   // Expand BRCOND into a BR_CC (see above).
156   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
157
158   // Handle integer types.
159   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
160        I <= MVT::LAST_INTEGER_VALUETYPE;
161        ++I) {
162     MVT VT = MVT::SimpleValueType(I);
163     if (isTypeLegal(VT)) {
164       // Expand individual DIV and REMs into DIVREMs.
165       setOperationAction(ISD::SDIV, VT, Expand);
166       setOperationAction(ISD::UDIV, VT, Expand);
167       setOperationAction(ISD::SREM, VT, Expand);
168       setOperationAction(ISD::UREM, VT, Expand);
169       setOperationAction(ISD::SDIVREM, VT, Custom);
170       setOperationAction(ISD::UDIVREM, VT, Custom);
171
172       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
173       // stores, putting a serialization instruction after the stores.
174       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
175       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
176
177       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
178       // available, or if the operand is constant.
179       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
180
181       // Use POPCNT on z196 and above.
182       if (Subtarget.hasPopulationCount())
183         setOperationAction(ISD::CTPOP, VT, Custom);
184       else
185         setOperationAction(ISD::CTPOP, VT, Expand);
186
187       // No special instructions for these.
188       setOperationAction(ISD::CTTZ,            VT, Expand);
189       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
190       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
191       setOperationAction(ISD::ROTR,            VT, Expand);
192
193       // Use *MUL_LOHI where possible instead of MULH*.
194       setOperationAction(ISD::MULHS, VT, Expand);
195       setOperationAction(ISD::MULHU, VT, Expand);
196       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
197       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
198
199       // Only z196 and above have native support for conversions to unsigned.
200       if (!Subtarget.hasFPExtension())
201         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
202     }
203   }
204
205   // Type legalization will convert 8- and 16-bit atomic operations into
206   // forms that operate on i32s (but still keeping the original memory VT).
207   // Lower them into full i32 operations.
208   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
209   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
210   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
211   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
212   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
213   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
214   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
215   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
216   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
217   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
218   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
219   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
220
221   // z10 has instructions for signed but not unsigned FP conversion.
222   // Handle unsigned 32-bit types as signed 64-bit types.
223   if (!Subtarget.hasFPExtension()) {
224     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
225     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
226   }
227
228   // We have native support for a 64-bit CTLZ, via FLOGR.
229   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
230   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
231
232   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
233   setOperationAction(ISD::OR, MVT::i64, Custom);
234
235   // FIXME: Can we support these natively?
236   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
237   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
238   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
239
240   // We have native instructions for i8, i16 and i32 extensions, but not i1.
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
242   for (MVT VT : MVT::integer_valuetypes()) {
243     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
244     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
245     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
246   }
247
248   // Handle the various types of symbolic address.
249   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
250   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
251   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
252   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
253   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
254
255   // We need to handle dynamic allocations specially because of the
256   // 160-byte area at the bottom of the stack.
257   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
258
259   // Use custom expanders so that we can force the function to use
260   // a frame pointer.
261   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
262   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
263
264   // Handle prefetches with PFD or PFDRL.
265   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
266
267   for (MVT VT : MVT::vector_valuetypes()) {
268     // Assume by default that all vector operations need to be expanded.
269     for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
270       if (getOperationAction(Opcode, VT) == Legal)
271         setOperationAction(Opcode, VT, Expand);
272
273     // Likewise all truncating stores and extending loads.
274     for (MVT InnerVT : MVT::vector_valuetypes()) {
275       setTruncStoreAction(VT, InnerVT, Expand);
276       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
277       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
278       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
279     }
280
281     if (isTypeLegal(VT)) {
282       // These operations are legal for anything that can be stored in a
283       // vector register, even if there is no native support for the format
284       // as such.  In particular, we can do these for v4f32 even though there
285       // are no specific instructions for that format.
286       setOperationAction(ISD::LOAD, VT, Legal);
287       setOperationAction(ISD::STORE, VT, Legal);
288       setOperationAction(ISD::VSELECT, VT, Legal);
289       setOperationAction(ISD::BITCAST, VT, Legal);
290       setOperationAction(ISD::UNDEF, VT, Legal);
291
292       // Likewise, except that we need to replace the nodes with something
293       // more specific.
294       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
295       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
296     }
297   }
298
299   // Handle integer vector types.
300   for (MVT VT : MVT::integer_vector_valuetypes()) {
301     if (isTypeLegal(VT)) {
302       // These operations have direct equivalents.
303       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
304       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
305       setOperationAction(ISD::ADD, VT, Legal);
306       setOperationAction(ISD::SUB, VT, Legal);
307       if (VT != MVT::v2i64)
308         setOperationAction(ISD::MUL, VT, Legal);
309       setOperationAction(ISD::AND, VT, Legal);
310       setOperationAction(ISD::OR, VT, Legal);
311       setOperationAction(ISD::XOR, VT, Legal);
312       setOperationAction(ISD::CTPOP, VT, Custom);
313       setOperationAction(ISD::CTTZ, VT, Legal);
314       setOperationAction(ISD::CTLZ, VT, Legal);
315       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
316       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
317
318       // Convert a GPR scalar to a vector by inserting it into element 0.
319       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
320
321       // Detect shifts by a scalar amount and convert them into
322       // V*_BY_SCALAR.
323       setOperationAction(ISD::SHL, VT, Custom);
324       setOperationAction(ISD::SRA, VT, Custom);
325       setOperationAction(ISD::SRL, VT, Custom);
326
327       // At present ROTL isn't matched by DAGCombiner.  ROTR should be
328       // converted into ROTL.
329       setOperationAction(ISD::ROTL, VT, Expand);
330       setOperationAction(ISD::ROTR, VT, Expand);
331
332       // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
333       // and inverting the result as necessary.
334       setOperationAction(ISD::SETCC, VT, Custom);
335     }
336   }
337
338   if (Subtarget.hasVector()) {
339     // There should be no need to check for float types other than v2f64
340     // since <2 x f32> isn't a legal type.
341     setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
342     setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
343     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
344     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
345   }
346
347   // Handle floating-point types.
348   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
349        I <= MVT::LAST_FP_VALUETYPE;
350        ++I) {
351     MVT VT = MVT::SimpleValueType(I);
352     if (isTypeLegal(VT)) {
353       // We can use FI for FRINT.
354       setOperationAction(ISD::FRINT, VT, Legal);
355
356       // We can use the extended form of FI for other rounding operations.
357       if (Subtarget.hasFPExtension()) {
358         setOperationAction(ISD::FNEARBYINT, VT, Legal);
359         setOperationAction(ISD::FFLOOR, VT, Legal);
360         setOperationAction(ISD::FCEIL, VT, Legal);
361         setOperationAction(ISD::FTRUNC, VT, Legal);
362         setOperationAction(ISD::FROUND, VT, Legal);
363       }
364
365       // No special instructions for these.
366       setOperationAction(ISD::FSIN, VT, Expand);
367       setOperationAction(ISD::FCOS, VT, Expand);
368       setOperationAction(ISD::FREM, VT, Expand);
369     }
370   }
371
372   // Handle floating-point vector types.
373   if (Subtarget.hasVector()) {
374     // Scalar-to-vector conversion is just a subreg.
375     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
376     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
377
378     // Some insertions and extractions can be done directly but others
379     // need to go via integers.
380     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
381     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
382     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
383     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
384
385     // These operations have direct equivalents.
386     setOperationAction(ISD::FADD, MVT::v2f64, Legal);
387     setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
388     setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
389     setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
390     setOperationAction(ISD::FMA, MVT::v2f64, Legal);
391     setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
392     setOperationAction(ISD::FABS, MVT::v2f64, Legal);
393     setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
394     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
395     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
396     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
397     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
398     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
399     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
400   }
401
402   // We have fused multiply-addition for f32 and f64 but not f128.
403   setOperationAction(ISD::FMA, MVT::f32,  Legal);
404   setOperationAction(ISD::FMA, MVT::f64,  Legal);
405   setOperationAction(ISD::FMA, MVT::f128, Expand);
406
407   // Needed so that we don't try to implement f128 constant loads using
408   // a load-and-extend of a f80 constant (in cases where the constant
409   // would fit in an f80).
410   for (MVT VT : MVT::fp_valuetypes())
411     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
412
413   // Floating-point truncation and stores need to be done separately.
414   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
415   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
416   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
417
418   // We have 64-bit FPR<->GPR moves, but need special handling for
419   // 32-bit forms.
420   if (!Subtarget.hasVector()) {
421     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
422     setOperationAction(ISD::BITCAST, MVT::f32, Custom);
423   }
424
425   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
426   // structure, but VAEND is a no-op.
427   setOperationAction(ISD::VASTART, MVT::Other, Custom);
428   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
429   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
430
431   // Codes for which we want to perform some z-specific combinations.
432   setTargetDAGCombine(ISD::SIGN_EXTEND);
433   setTargetDAGCombine(ISD::STORE);
434   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
435   setTargetDAGCombine(ISD::FP_ROUND);
436
437   // Handle intrinsics.
438   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
439
440   // We want to use MVC in preference to even a single load/store pair.
441   MaxStoresPerMemcpy = 0;
442   MaxStoresPerMemcpyOptSize = 0;
443
444   // The main memset sequence is a byte store followed by an MVC.
445   // Two STC or MV..I stores win over that, but the kind of fused stores
446   // generated by target-independent code don't when the byte value is
447   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
448   // than "STC;MVC".  Handle the choice in target-specific code instead.
449   MaxStoresPerMemset = 0;
450   MaxStoresPerMemsetOptSize = 0;
451 }
452
453 EVT SystemZTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
454   if (!VT.isVector())
455     return MVT::i32;
456   return VT.changeVectorElementTypeToInteger();
457 }
458
459 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
460   VT = VT.getScalarType();
461
462   if (!VT.isSimple())
463     return false;
464
465   switch (VT.getSimpleVT().SimpleTy) {
466   case MVT::f32:
467   case MVT::f64:
468     return true;
469   case MVT::f128:
470     return false;
471   default:
472     break;
473   }
474
475   return false;
476 }
477
478 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
479   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
480   return Imm.isZero() || Imm.isNegZero();
481 }
482
483 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
484   // We can use CGFI or CLGFI.
485   return isInt<32>(Imm) || isUInt<32>(Imm);
486 }
487
488 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
489   // We can use ALGFI or SLGFI.
490   return isUInt<32>(Imm) || isUInt<32>(-Imm);
491 }
492
493 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
494                                                            unsigned,
495                                                            unsigned,
496                                                            bool *Fast) const {
497   // Unaligned accesses should never be slower than the expanded version.
498   // We check specifically for aligned accesses in the few cases where
499   // they are required.
500   if (Fast)
501     *Fast = true;
502   return true;
503 }
504   
505 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
506                                                   Type *Ty) const {
507   // Punt on globals for now, although they can be used in limited
508   // RELATIVE LONG cases.
509   if (AM.BaseGV)
510     return false;
511
512   // Require a 20-bit signed offset.
513   if (!isInt<20>(AM.BaseOffs))
514     return false;
515
516   // Indexing is OK but no scale factor can be applied.
517   return AM.Scale == 0 || AM.Scale == 1;
518 }
519
520 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
521   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
522     return false;
523   unsigned FromBits = FromType->getPrimitiveSizeInBits();
524   unsigned ToBits = ToType->getPrimitiveSizeInBits();
525   return FromBits > ToBits;
526 }
527
528 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
529   if (!FromVT.isInteger() || !ToVT.isInteger())
530     return false;
531   unsigned FromBits = FromVT.getSizeInBits();
532   unsigned ToBits = ToVT.getSizeInBits();
533   return FromBits > ToBits;
534 }
535
536 //===----------------------------------------------------------------------===//
537 // Inline asm support
538 //===----------------------------------------------------------------------===//
539
540 TargetLowering::ConstraintType
541 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
542   if (Constraint.size() == 1) {
543     switch (Constraint[0]) {
544     case 'a': // Address register
545     case 'd': // Data register (equivalent to 'r')
546     case 'f': // Floating-point register
547     case 'h': // High-part register
548     case 'r': // General-purpose register
549       return C_RegisterClass;
550
551     case 'Q': // Memory with base and unsigned 12-bit displacement
552     case 'R': // Likewise, plus an index
553     case 'S': // Memory with base and signed 20-bit displacement
554     case 'T': // Likewise, plus an index
555     case 'm': // Equivalent to 'T'.
556       return C_Memory;
557
558     case 'I': // Unsigned 8-bit constant
559     case 'J': // Unsigned 12-bit constant
560     case 'K': // Signed 16-bit constant
561     case 'L': // Signed 20-bit displacement (on all targets we support)
562     case 'M': // 0x7fffffff
563       return C_Other;
564
565     default:
566       break;
567     }
568   }
569   return TargetLowering::getConstraintType(Constraint);
570 }
571
572 TargetLowering::ConstraintWeight SystemZTargetLowering::
573 getSingleConstraintMatchWeight(AsmOperandInfo &info,
574                                const char *constraint) const {
575   ConstraintWeight weight = CW_Invalid;
576   Value *CallOperandVal = info.CallOperandVal;
577   // If we don't have a value, we can't do a match,
578   // but allow it at the lowest weight.
579   if (!CallOperandVal)
580     return CW_Default;
581   Type *type = CallOperandVal->getType();
582   // Look at the constraint type.
583   switch (*constraint) {
584   default:
585     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
586     break;
587
588   case 'a': // Address register
589   case 'd': // Data register (equivalent to 'r')
590   case 'h': // High-part register
591   case 'r': // General-purpose register
592     if (CallOperandVal->getType()->isIntegerTy())
593       weight = CW_Register;
594     break;
595
596   case 'f': // Floating-point register
597     if (type->isFloatingPointTy())
598       weight = CW_Register;
599     break;
600
601   case 'I': // Unsigned 8-bit constant
602     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
603       if (isUInt<8>(C->getZExtValue()))
604         weight = CW_Constant;
605     break;
606
607   case 'J': // Unsigned 12-bit constant
608     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
609       if (isUInt<12>(C->getZExtValue()))
610         weight = CW_Constant;
611     break;
612
613   case 'K': // Signed 16-bit constant
614     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
615       if (isInt<16>(C->getSExtValue()))
616         weight = CW_Constant;
617     break;
618
619   case 'L': // Signed 20-bit displacement (on all targets we support)
620     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
621       if (isInt<20>(C->getSExtValue()))
622         weight = CW_Constant;
623     break;
624
625   case 'M': // 0x7fffffff
626     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
627       if (C->getZExtValue() == 0x7fffffff)
628         weight = CW_Constant;
629     break;
630   }
631   return weight;
632 }
633
634 // Parse a "{tNNN}" register constraint for which the register type "t"
635 // has already been verified.  MC is the class associated with "t" and
636 // Map maps 0-based register numbers to LLVM register numbers.
637 static std::pair<unsigned, const TargetRegisterClass *>
638 parseRegisterNumber(const std::string &Constraint,
639                     const TargetRegisterClass *RC, const unsigned *Map) {
640   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
641   if (isdigit(Constraint[2])) {
642     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
643     unsigned Index = atoi(Suffix.c_str());
644     if (Index < 16 && Map[Index])
645       return std::make_pair(Map[Index], RC);
646   }
647   return std::make_pair(0U, nullptr);
648 }
649
650 std::pair<unsigned, const TargetRegisterClass *>
651 SystemZTargetLowering::getRegForInlineAsmConstraint(
652     const TargetRegisterInfo *TRI, const std::string &Constraint,
653     MVT VT) const {
654   if (Constraint.size() == 1) {
655     // GCC Constraint Letters
656     switch (Constraint[0]) {
657     default: break;
658     case 'd': // Data register (equivalent to 'r')
659     case 'r': // General-purpose register
660       if (VT == MVT::i64)
661         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
662       else if (VT == MVT::i128)
663         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
664       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
665
666     case 'a': // Address register
667       if (VT == MVT::i64)
668         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
669       else if (VT == MVT::i128)
670         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
671       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
672
673     case 'h': // High-part register (an LLVM extension)
674       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
675
676     case 'f': // Floating-point register
677       if (VT == MVT::f64)
678         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
679       else if (VT == MVT::f128)
680         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
681       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
682     }
683   }
684   if (Constraint[0] == '{') {
685     // We need to override the default register parsing for GPRs and FPRs
686     // because the interpretation depends on VT.  The internal names of
687     // the registers are also different from the external names
688     // (F0D and F0S instead of F0, etc.).
689     if (Constraint[1] == 'r') {
690       if (VT == MVT::i32)
691         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
692                                    SystemZMC::GR32Regs);
693       if (VT == MVT::i128)
694         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
695                                    SystemZMC::GR128Regs);
696       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
697                                  SystemZMC::GR64Regs);
698     }
699     if (Constraint[1] == 'f') {
700       if (VT == MVT::f32)
701         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
702                                    SystemZMC::FP32Regs);
703       if (VT == MVT::f128)
704         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
705                                    SystemZMC::FP128Regs);
706       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
707                                  SystemZMC::FP64Regs);
708     }
709   }
710   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
711 }
712
713 void SystemZTargetLowering::
714 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
715                              std::vector<SDValue> &Ops,
716                              SelectionDAG &DAG) const {
717   // Only support length 1 constraints for now.
718   if (Constraint.length() == 1) {
719     switch (Constraint[0]) {
720     case 'I': // Unsigned 8-bit constant
721       if (auto *C = dyn_cast<ConstantSDNode>(Op))
722         if (isUInt<8>(C->getZExtValue()))
723           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
724                                               Op.getValueType()));
725       return;
726
727     case 'J': // Unsigned 12-bit constant
728       if (auto *C = dyn_cast<ConstantSDNode>(Op))
729         if (isUInt<12>(C->getZExtValue()))
730           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
731                                               Op.getValueType()));
732       return;
733
734     case 'K': // Signed 16-bit constant
735       if (auto *C = dyn_cast<ConstantSDNode>(Op))
736         if (isInt<16>(C->getSExtValue()))
737           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
738                                               Op.getValueType()));
739       return;
740
741     case 'L': // Signed 20-bit displacement (on all targets we support)
742       if (auto *C = dyn_cast<ConstantSDNode>(Op))
743         if (isInt<20>(C->getSExtValue()))
744           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
745                                               Op.getValueType()));
746       return;
747
748     case 'M': // 0x7fffffff
749       if (auto *C = dyn_cast<ConstantSDNode>(Op))
750         if (C->getZExtValue() == 0x7fffffff)
751           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
752                                               Op.getValueType()));
753       return;
754     }
755   }
756   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
757 }
758
759 //===----------------------------------------------------------------------===//
760 // Calling conventions
761 //===----------------------------------------------------------------------===//
762
763 #include "SystemZGenCallingConv.inc"
764
765 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
766                                                      Type *ToType) const {
767   return isTruncateFree(FromType, ToType);
768 }
769
770 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
771   if (!CI->isTailCall())
772     return false;
773   return true;
774 }
775
776 // Value is a value that has been passed to us in the location described by VA
777 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
778 // any loads onto Chain.
779 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
780                                    CCValAssign &VA, SDValue Chain,
781                                    SDValue Value) {
782   // If the argument has been promoted from a smaller type, insert an
783   // assertion to capture this.
784   if (VA.getLocInfo() == CCValAssign::SExt)
785     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
786                         DAG.getValueType(VA.getValVT()));
787   else if (VA.getLocInfo() == CCValAssign::ZExt)
788     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
789                         DAG.getValueType(VA.getValVT()));
790
791   if (VA.isExtInLoc())
792     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
793   else if (VA.getLocInfo() == CCValAssign::Indirect)
794     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
795                         MachinePointerInfo(), false, false, false, 0);
796   else
797     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
798   return Value;
799 }
800
801 // Value is a value of type VA.getValVT() that we need to copy into
802 // the location described by VA.  Return a copy of Value converted to
803 // VA.getValVT().  The caller is responsible for handling indirect values.
804 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
805                                    CCValAssign &VA, SDValue Value) {
806   switch (VA.getLocInfo()) {
807   case CCValAssign::SExt:
808     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
809   case CCValAssign::ZExt:
810     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
811   case CCValAssign::AExt:
812     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
813   case CCValAssign::Full:
814     return Value;
815   default:
816     llvm_unreachable("Unhandled getLocInfo()");
817   }
818 }
819
820 SDValue SystemZTargetLowering::
821 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
822                      const SmallVectorImpl<ISD::InputArg> &Ins,
823                      SDLoc DL, SelectionDAG &DAG,
824                      SmallVectorImpl<SDValue> &InVals) const {
825   MachineFunction &MF = DAG.getMachineFunction();
826   MachineFrameInfo *MFI = MF.getFrameInfo();
827   MachineRegisterInfo &MRI = MF.getRegInfo();
828   SystemZMachineFunctionInfo *FuncInfo =
829       MF.getInfo<SystemZMachineFunctionInfo>();
830   auto *TFL =
831       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
832
833   // Assign locations to all of the incoming arguments.
834   SmallVector<CCValAssign, 16> ArgLocs;
835   SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
836   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
837
838   unsigned NumFixedGPRs = 0;
839   unsigned NumFixedFPRs = 0;
840   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
841     SDValue ArgValue;
842     CCValAssign &VA = ArgLocs[I];
843     EVT LocVT = VA.getLocVT();
844     if (VA.isRegLoc()) {
845       // Arguments passed in registers
846       const TargetRegisterClass *RC;
847       switch (LocVT.getSimpleVT().SimpleTy) {
848       default:
849         // Integers smaller than i64 should be promoted to i64.
850         llvm_unreachable("Unexpected argument type");
851       case MVT::i32:
852         NumFixedGPRs += 1;
853         RC = &SystemZ::GR32BitRegClass;
854         break;
855       case MVT::i64:
856         NumFixedGPRs += 1;
857         RC = &SystemZ::GR64BitRegClass;
858         break;
859       case MVT::f32:
860         NumFixedFPRs += 1;
861         RC = &SystemZ::FP32BitRegClass;
862         break;
863       case MVT::f64:
864         NumFixedFPRs += 1;
865         RC = &SystemZ::FP64BitRegClass;
866         break;
867       case MVT::v16i8:
868       case MVT::v8i16:
869       case MVT::v4i32:
870       case MVT::v2i64:
871       case MVT::v4f32:
872       case MVT::v2f64:
873         RC = &SystemZ::VR128BitRegClass;
874         break;
875       }
876
877       unsigned VReg = MRI.createVirtualRegister(RC);
878       MRI.addLiveIn(VA.getLocReg(), VReg);
879       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
880     } else {
881       assert(VA.isMemLoc() && "Argument not register or memory");
882
883       // Create the frame index object for this incoming parameter.
884       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
885                                       VA.getLocMemOffset(), true);
886
887       // Create the SelectionDAG nodes corresponding to a load
888       // from this parameter.  Unpromoted ints and floats are
889       // passed as right-justified 8-byte values.
890       EVT PtrVT = getPointerTy();
891       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
892       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
893         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
894                           DAG.getIntPtrConstant(4, DL));
895       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
896                              MachinePointerInfo::getFixedStack(FI),
897                              false, false, false, 0);
898     }
899
900     // Convert the value of the argument register into the value that's
901     // being passed.
902     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
903   }
904
905   if (IsVarArg) {
906     // Save the number of non-varargs registers for later use by va_start, etc.
907     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
908     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
909
910     // Likewise the address (in the form of a frame index) of where the
911     // first stack vararg would be.  The 1-byte size here is arbitrary.
912     int64_t StackSize = CCInfo.getNextStackOffset();
913     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
914
915     // ...and a similar frame index for the caller-allocated save area
916     // that will be used to store the incoming registers.
917     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
918     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
919     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
920
921     // Store the FPR varargs in the reserved frame slots.  (We store the
922     // GPRs as part of the prologue.)
923     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
924       SDValue MemOps[SystemZ::NumArgFPRs];
925       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
926         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
927         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
928         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
929         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
930                                      &SystemZ::FP64BitRegClass);
931         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
932         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
933                                  MachinePointerInfo::getFixedStack(FI),
934                                  false, false, 0);
935
936       }
937       // Join the stores, which are independent of one another.
938       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
939                           makeArrayRef(&MemOps[NumFixedFPRs],
940                                        SystemZ::NumArgFPRs-NumFixedFPRs));
941     }
942   }
943
944   return Chain;
945 }
946
947 static bool canUseSiblingCall(const CCState &ArgCCInfo,
948                               SmallVectorImpl<CCValAssign> &ArgLocs) {
949   // Punt if there are any indirect or stack arguments, or if the call
950   // needs the call-saved argument register R6.
951   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
952     CCValAssign &VA = ArgLocs[I];
953     if (VA.getLocInfo() == CCValAssign::Indirect)
954       return false;
955     if (!VA.isRegLoc())
956       return false;
957     unsigned Reg = VA.getLocReg();
958     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
959       return false;
960   }
961   return true;
962 }
963
964 SDValue
965 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
966                                  SmallVectorImpl<SDValue> &InVals) const {
967   SelectionDAG &DAG = CLI.DAG;
968   SDLoc &DL = CLI.DL;
969   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
970   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
971   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
972   SDValue Chain = CLI.Chain;
973   SDValue Callee = CLI.Callee;
974   bool &IsTailCall = CLI.IsTailCall;
975   CallingConv::ID CallConv = CLI.CallConv;
976   bool IsVarArg = CLI.IsVarArg;
977   MachineFunction &MF = DAG.getMachineFunction();
978   EVT PtrVT = getPointerTy();
979
980   // Analyze the operands of the call, assigning locations to each operand.
981   SmallVector<CCValAssign, 16> ArgLocs;
982   SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
983   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
984
985   // We don't support GuaranteedTailCallOpt, only automatically-detected
986   // sibling calls.
987   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
988     IsTailCall = false;
989
990   // Get a count of how many bytes are to be pushed on the stack.
991   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
992
993   // Mark the start of the call.
994   if (!IsTailCall)
995     Chain = DAG.getCALLSEQ_START(Chain,
996                                  DAG.getConstant(NumBytes, DL, PtrVT, true),
997                                  DL);
998
999   // Copy argument values to their designated locations.
1000   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1001   SmallVector<SDValue, 8> MemOpChains;
1002   SDValue StackPtr;
1003   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1004     CCValAssign &VA = ArgLocs[I];
1005     SDValue ArgValue = OutVals[I];
1006
1007     if (VA.getLocInfo() == CCValAssign::Indirect) {
1008       // Store the argument in a stack slot and pass its address.
1009       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1010       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1011       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1012                                          MachinePointerInfo::getFixedStack(FI),
1013                                          false, false, 0));
1014       ArgValue = SpillSlot;
1015     } else
1016       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1017
1018     if (VA.isRegLoc())
1019       // Queue up the argument copies and emit them at the end.
1020       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1021     else {
1022       assert(VA.isMemLoc() && "Argument not register or memory");
1023
1024       // Work out the address of the stack slot.  Unpromoted ints and
1025       // floats are passed as right-justified 8-byte values.
1026       if (!StackPtr.getNode())
1027         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1028       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1029       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1030         Offset += 4;
1031       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1032                                     DAG.getIntPtrConstant(Offset, DL));
1033
1034       // Emit the store.
1035       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
1036                                          MachinePointerInfo(),
1037                                          false, false, 0));
1038     }
1039   }
1040
1041   // Join the stores, which are independent of one another.
1042   if (!MemOpChains.empty())
1043     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1044
1045   // Accept direct calls by converting symbolic call addresses to the
1046   // associated Target* opcodes.  Force %r1 to be used for indirect
1047   // tail calls.
1048   SDValue Glue;
1049   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1050     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1051     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1052   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1053     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1054     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1055   } else if (IsTailCall) {
1056     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1057     Glue = Chain.getValue(1);
1058     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1059   }
1060
1061   // Build a sequence of copy-to-reg nodes, chained and glued together.
1062   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1063     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1064                              RegsToPass[I].second, Glue);
1065     Glue = Chain.getValue(1);
1066   }
1067
1068   // The first call operand is the chain and the second is the target address.
1069   SmallVector<SDValue, 8> Ops;
1070   Ops.push_back(Chain);
1071   Ops.push_back(Callee);
1072
1073   // Add argument registers to the end of the list so that they are
1074   // known live into the call.
1075   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1076     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1077                                   RegsToPass[I].second.getValueType()));
1078
1079   // Add a register mask operand representing the call-preserved registers.
1080   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1081   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1082   assert(Mask && "Missing call preserved mask for calling convention");
1083   Ops.push_back(DAG.getRegisterMask(Mask));
1084
1085   // Glue the call to the argument copies, if any.
1086   if (Glue.getNode())
1087     Ops.push_back(Glue);
1088
1089   // Emit the call.
1090   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1091   if (IsTailCall)
1092     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1093   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1094   Glue = Chain.getValue(1);
1095
1096   // Mark the end of the call, which is glued to the call itself.
1097   Chain = DAG.getCALLSEQ_END(Chain,
1098                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1099                              DAG.getConstant(0, DL, PtrVT, true),
1100                              Glue, DL);
1101   Glue = Chain.getValue(1);
1102
1103   // Assign locations to each value returned by this call.
1104   SmallVector<CCValAssign, 16> RetLocs;
1105   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1106   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1107
1108   // Copy all of the result registers out of their specified physreg.
1109   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1110     CCValAssign &VA = RetLocs[I];
1111
1112     // Copy the value out, gluing the copy to the end of the call sequence.
1113     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1114                                           VA.getLocVT(), Glue);
1115     Chain = RetValue.getValue(1);
1116     Glue = RetValue.getValue(2);
1117
1118     // Convert the value of the return register into the value that's
1119     // being returned.
1120     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1121   }
1122
1123   return Chain;
1124 }
1125
1126 SDValue
1127 SystemZTargetLowering::LowerReturn(SDValue Chain,
1128                                    CallingConv::ID CallConv, bool IsVarArg,
1129                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1130                                    const SmallVectorImpl<SDValue> &OutVals,
1131                                    SDLoc DL, SelectionDAG &DAG) const {
1132   MachineFunction &MF = DAG.getMachineFunction();
1133
1134   // Assign locations to each returned value.
1135   SmallVector<CCValAssign, 16> RetLocs;
1136   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1137   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1138
1139   // Quick exit for void returns
1140   if (RetLocs.empty())
1141     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1142
1143   // Copy the result values into the output registers.
1144   SDValue Glue;
1145   SmallVector<SDValue, 4> RetOps;
1146   RetOps.push_back(Chain);
1147   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1148     CCValAssign &VA = RetLocs[I];
1149     SDValue RetValue = OutVals[I];
1150
1151     // Make the return register live on exit.
1152     assert(VA.isRegLoc() && "Can only return in registers!");
1153
1154     // Promote the value as required.
1155     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1156
1157     // Chain and glue the copies together.
1158     unsigned Reg = VA.getLocReg();
1159     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1160     Glue = Chain.getValue(1);
1161     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1162   }
1163
1164   // Update chain and glue.
1165   RetOps[0] = Chain;
1166   if (Glue.getNode())
1167     RetOps.push_back(Glue);
1168
1169   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1170 }
1171
1172 SDValue SystemZTargetLowering::
1173 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
1174   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1175 }
1176
1177 // Return true if Op is an intrinsic node with chain that returns the CC value
1178 // as its only (other) argument.  Provide the associated SystemZISD opcode and
1179 // the mask of valid CC values if so.
1180 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1181                                       unsigned &CCValid) {
1182   unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1183   switch (Id) {
1184   case Intrinsic::s390_tbegin:
1185     Opcode = SystemZISD::TBEGIN;
1186     CCValid = SystemZ::CCMASK_TBEGIN;
1187     return true;
1188
1189   case Intrinsic::s390_tbegin_nofloat:
1190     Opcode = SystemZISD::TBEGIN_NOFLOAT;
1191     CCValid = SystemZ::CCMASK_TBEGIN;
1192     return true;
1193
1194   case Intrinsic::s390_tend:
1195     Opcode = SystemZISD::TEND;
1196     CCValid = SystemZ::CCMASK_TEND;
1197     return true;
1198
1199   default:
1200     return false;
1201   }
1202 }
1203
1204 // Emit an intrinsic with chain with a glued value instead of its CC result.
1205 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1206                                              unsigned Opcode) {
1207   // Copy all operands except the intrinsic ID.
1208   unsigned NumOps = Op.getNumOperands();
1209   SmallVector<SDValue, 6> Ops;
1210   Ops.reserve(NumOps - 1);
1211   Ops.push_back(Op.getOperand(0));
1212   for (unsigned I = 2; I < NumOps; ++I)
1213     Ops.push_back(Op.getOperand(I));
1214
1215   assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1216   SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1217   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1218   SDValue OldChain = SDValue(Op.getNode(), 1);
1219   SDValue NewChain = SDValue(Intr.getNode(), 0);
1220   DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1221   return Intr;
1222 }
1223
1224 // CC is a comparison that will be implemented using an integer or
1225 // floating-point comparison.  Return the condition code mask for
1226 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
1227 // unsigned comparisons and clear for signed ones.  In the floating-point
1228 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1229 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1230 #define CONV(X) \
1231   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1232   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1233   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1234
1235   switch (CC) {
1236   default:
1237     llvm_unreachable("Invalid integer condition!");
1238
1239   CONV(EQ);
1240   CONV(NE);
1241   CONV(GT);
1242   CONV(GE);
1243   CONV(LT);
1244   CONV(LE);
1245
1246   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
1247   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1248   }
1249 #undef CONV
1250 }
1251
1252 // Return a sequence for getting a 1 from an IPM result when CC has a
1253 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1254 // The handling of CC values outside CCValid doesn't matter.
1255 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1256   // Deal with cases where the result can be taken directly from a bit
1257   // of the IPM result.
1258   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1259     return IPMConversion(0, 0, SystemZ::IPM_CC);
1260   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1261     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1262
1263   // Deal with cases where we can add a value to force the sign bit
1264   // to contain the right value.  Putting the bit in 31 means we can
1265   // use SRL rather than RISBG(L), and also makes it easier to get a
1266   // 0/-1 value, so it has priority over the other tests below.
1267   //
1268   // These sequences rely on the fact that the upper two bits of the
1269   // IPM result are zero.
1270   uint64_t TopBit = uint64_t(1) << 31;
1271   if (CCMask == (CCValid & SystemZ::CCMASK_0))
1272     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1273   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1274     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1275   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1276                             | SystemZ::CCMASK_1
1277                             | SystemZ::CCMASK_2)))
1278     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1279   if (CCMask == (CCValid & SystemZ::CCMASK_3))
1280     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1281   if (CCMask == (CCValid & (SystemZ::CCMASK_1
1282                             | SystemZ::CCMASK_2
1283                             | SystemZ::CCMASK_3)))
1284     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1285
1286   // Next try inverting the value and testing a bit.  0/1 could be
1287   // handled this way too, but we dealt with that case above.
1288   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1289     return IPMConversion(-1, 0, SystemZ::IPM_CC);
1290
1291   // Handle cases where adding a value forces a non-sign bit to contain
1292   // the right value.
1293   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1294     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1295   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1296     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1297
1298   // The remaining cases are 1, 2, 0/1/3 and 0/2/3.  All these are
1299   // can be done by inverting the low CC bit and applying one of the
1300   // sign-based extractions above.
1301   if (CCMask == (CCValid & SystemZ::CCMASK_1))
1302     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1303   if (CCMask == (CCValid & SystemZ::CCMASK_2))
1304     return IPMConversion(1 << SystemZ::IPM_CC,
1305                          TopBit - (3 << SystemZ::IPM_CC), 31);
1306   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1307                             | SystemZ::CCMASK_1
1308                             | SystemZ::CCMASK_3)))
1309     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1310   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1311                             | SystemZ::CCMASK_2
1312                             | SystemZ::CCMASK_3)))
1313     return IPMConversion(1 << SystemZ::IPM_CC,
1314                          TopBit - (1 << SystemZ::IPM_CC), 31);
1315
1316   llvm_unreachable("Unexpected CC combination");
1317 }
1318
1319 // If C can be converted to a comparison against zero, adjust the operands
1320 // as necessary.
1321 static void adjustZeroCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1322   if (C.ICmpType == SystemZICMP::UnsignedOnly)
1323     return;
1324
1325   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1326   if (!ConstOp1)
1327     return;
1328
1329   int64_t Value = ConstOp1->getSExtValue();
1330   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1331       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1332       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1333       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1334     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1335     C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1336   }
1337 }
1338
1339 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1340 // adjust the operands as necessary.
1341 static void adjustSubwordCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1342   // For us to make any changes, it must a comparison between a single-use
1343   // load and a constant.
1344   if (!C.Op0.hasOneUse() ||
1345       C.Op0.getOpcode() != ISD::LOAD ||
1346       C.Op1.getOpcode() != ISD::Constant)
1347     return;
1348
1349   // We must have an 8- or 16-bit load.
1350   auto *Load = cast<LoadSDNode>(C.Op0);
1351   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1352   if (NumBits != 8 && NumBits != 16)
1353     return;
1354
1355   // The load must be an extending one and the constant must be within the
1356   // range of the unextended value.
1357   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1358   uint64_t Value = ConstOp1->getZExtValue();
1359   uint64_t Mask = (1 << NumBits) - 1;
1360   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1361     // Make sure that ConstOp1 is in range of C.Op0.
1362     int64_t SignedValue = ConstOp1->getSExtValue();
1363     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1364       return;
1365     if (C.ICmpType != SystemZICMP::SignedOnly) {
1366       // Unsigned comparison between two sign-extended values is equivalent
1367       // to unsigned comparison between two zero-extended values.
1368       Value &= Mask;
1369     } else if (NumBits == 8) {
1370       // Try to treat the comparison as unsigned, so that we can use CLI.
1371       // Adjust CCMask and Value as necessary.
1372       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1373         // Test whether the high bit of the byte is set.
1374         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1375       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1376         // Test whether the high bit of the byte is clear.
1377         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1378       else
1379         // No instruction exists for this combination.
1380         return;
1381       C.ICmpType = SystemZICMP::UnsignedOnly;
1382     }
1383   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1384     if (Value > Mask)
1385       return;
1386     assert(C.ICmpType == SystemZICMP::Any &&
1387            "Signedness shouldn't matter here.");
1388   } else
1389     return;
1390
1391   // Make sure that the first operand is an i32 of the right extension type.
1392   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1393                               ISD::SEXTLOAD :
1394                               ISD::ZEXTLOAD);
1395   if (C.Op0.getValueType() != MVT::i32 ||
1396       Load->getExtensionType() != ExtType)
1397     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1398                            Load->getChain(), Load->getBasePtr(),
1399                            Load->getPointerInfo(), Load->getMemoryVT(),
1400                            Load->isVolatile(), Load->isNonTemporal(),
1401                            Load->isInvariant(), Load->getAlignment());
1402
1403   // Make sure that the second operand is an i32 with the right value.
1404   if (C.Op1.getValueType() != MVT::i32 ||
1405       Value != ConstOp1->getZExtValue())
1406     C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1407 }
1408
1409 // Return true if Op is either an unextended load, or a load suitable
1410 // for integer register-memory comparisons of type ICmpType.
1411 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1412   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1413   if (Load) {
1414     // There are no instructions to compare a register with a memory byte.
1415     if (Load->getMemoryVT() == MVT::i8)
1416       return false;
1417     // Otherwise decide on extension type.
1418     switch (Load->getExtensionType()) {
1419     case ISD::NON_EXTLOAD:
1420       return true;
1421     case ISD::SEXTLOAD:
1422       return ICmpType != SystemZICMP::UnsignedOnly;
1423     case ISD::ZEXTLOAD:
1424       return ICmpType != SystemZICMP::SignedOnly;
1425     default:
1426       break;
1427     }
1428   }
1429   return false;
1430 }
1431
1432 // Return true if it is better to swap the operands of C.
1433 static bool shouldSwapCmpOperands(const Comparison &C) {
1434   // Leave f128 comparisons alone, since they have no memory forms.
1435   if (C.Op0.getValueType() == MVT::f128)
1436     return false;
1437
1438   // Always keep a floating-point constant second, since comparisons with
1439   // zero can use LOAD TEST and comparisons with other constants make a
1440   // natural memory operand.
1441   if (isa<ConstantFPSDNode>(C.Op1))
1442     return false;
1443
1444   // Never swap comparisons with zero since there are many ways to optimize
1445   // those later.
1446   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1447   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1448     return false;
1449
1450   // Also keep natural memory operands second if the loaded value is
1451   // only used here.  Several comparisons have memory forms.
1452   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1453     return false;
1454
1455   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1456   // In that case we generally prefer the memory to be second.
1457   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1458     // The only exceptions are when the second operand is a constant and
1459     // we can use things like CHHSI.
1460     if (!ConstOp1)
1461       return true;
1462     // The unsigned memory-immediate instructions can handle 16-bit
1463     // unsigned integers.
1464     if (C.ICmpType != SystemZICMP::SignedOnly &&
1465         isUInt<16>(ConstOp1->getZExtValue()))
1466       return false;
1467     // The signed memory-immediate instructions can handle 16-bit
1468     // signed integers.
1469     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1470         isInt<16>(ConstOp1->getSExtValue()))
1471       return false;
1472     return true;
1473   }
1474
1475   // Try to promote the use of CGFR and CLGFR.
1476   unsigned Opcode0 = C.Op0.getOpcode();
1477   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1478     return true;
1479   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1480     return true;
1481   if (C.ICmpType != SystemZICMP::SignedOnly &&
1482       Opcode0 == ISD::AND &&
1483       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1484       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1485     return true;
1486
1487   return false;
1488 }
1489
1490 // Return a version of comparison CC mask CCMask in which the LT and GT
1491 // actions are swapped.
1492 static unsigned reverseCCMask(unsigned CCMask) {
1493   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1494           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1495           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1496           (CCMask & SystemZ::CCMASK_CMP_UO));
1497 }
1498
1499 // Check whether C tests for equality between X and Y and whether X - Y
1500 // or Y - X is also computed.  In that case it's better to compare the
1501 // result of the subtraction against zero.
1502 static void adjustForSubtraction(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1503   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1504       C.CCMask == SystemZ::CCMASK_CMP_NE) {
1505     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1506       SDNode *N = *I;
1507       if (N->getOpcode() == ISD::SUB &&
1508           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1509            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1510         C.Op0 = SDValue(N, 0);
1511         C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1512         return;
1513       }
1514     }
1515   }
1516 }
1517
1518 // Check whether C compares a floating-point value with zero and if that
1519 // floating-point value is also negated.  In this case we can use the
1520 // negation to set CC, so avoiding separate LOAD AND TEST and
1521 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1522 static void adjustForFNeg(Comparison &C) {
1523   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1524   if (C1 && C1->isZero()) {
1525     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1526       SDNode *N = *I;
1527       if (N->getOpcode() == ISD::FNEG) {
1528         C.Op0 = SDValue(N, 0);
1529         C.CCMask = reverseCCMask(C.CCMask);
1530         return;
1531       }
1532     }
1533   }
1534 }
1535
1536 // Check whether C compares (shl X, 32) with 0 and whether X is
1537 // also sign-extended.  In that case it is better to test the result
1538 // of the sign extension using LTGFR.
1539 //
1540 // This case is important because InstCombine transforms a comparison
1541 // with (sext (trunc X)) into a comparison with (shl X, 32).
1542 static void adjustForLTGFR(Comparison &C) {
1543   // Check for a comparison between (shl X, 32) and 0.
1544   if (C.Op0.getOpcode() == ISD::SHL &&
1545       C.Op0.getValueType() == MVT::i64 &&
1546       C.Op1.getOpcode() == ISD::Constant &&
1547       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1548     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1549     if (C1 && C1->getZExtValue() == 32) {
1550       SDValue ShlOp0 = C.Op0.getOperand(0);
1551       // See whether X has any SIGN_EXTEND_INREG uses.
1552       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1553         SDNode *N = *I;
1554         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1555             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1556           C.Op0 = SDValue(N, 0);
1557           return;
1558         }
1559       }
1560     }
1561   }
1562 }
1563
1564 // If C compares the truncation of an extending load, try to compare
1565 // the untruncated value instead.  This exposes more opportunities to
1566 // reuse CC.
1567 static void adjustICmpTruncate(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1568   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1569       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1570       C.Op1.getOpcode() == ISD::Constant &&
1571       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1572     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1573     if (L->getMemoryVT().getStoreSizeInBits()
1574         <= C.Op0.getValueType().getSizeInBits()) {
1575       unsigned Type = L->getExtensionType();
1576       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1577           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1578         C.Op0 = C.Op0.getOperand(0);
1579         C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1580       }
1581     }
1582   }
1583 }
1584
1585 // Return true if shift operation N has an in-range constant shift value.
1586 // Store it in ShiftVal if so.
1587 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1588   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1589   if (!Shift)
1590     return false;
1591
1592   uint64_t Amount = Shift->getZExtValue();
1593   if (Amount >= N.getValueType().getSizeInBits())
1594     return false;
1595
1596   ShiftVal = Amount;
1597   return true;
1598 }
1599
1600 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1601 // instruction and whether the CC value is descriptive enough to handle
1602 // a comparison of type Opcode between the AND result and CmpVal.
1603 // CCMask says which comparison result is being tested and BitSize is
1604 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1605 // return the corresponding CC mask, otherwise return 0.
1606 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1607                                      uint64_t Mask, uint64_t CmpVal,
1608                                      unsigned ICmpType) {
1609   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1610
1611   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1612   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1613       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1614     return 0;
1615
1616   // Work out the masks for the lowest and highest bits.
1617   unsigned HighShift = 63 - countLeadingZeros(Mask);
1618   uint64_t High = uint64_t(1) << HighShift;
1619   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1620
1621   // Signed ordered comparisons are effectively unsigned if the sign
1622   // bit is dropped.
1623   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1624
1625   // Check for equality comparisons with 0, or the equivalent.
1626   if (CmpVal == 0) {
1627     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1628       return SystemZ::CCMASK_TM_ALL_0;
1629     if (CCMask == SystemZ::CCMASK_CMP_NE)
1630       return SystemZ::CCMASK_TM_SOME_1;
1631   }
1632   if (EffectivelyUnsigned && CmpVal <= Low) {
1633     if (CCMask == SystemZ::CCMASK_CMP_LT)
1634       return SystemZ::CCMASK_TM_ALL_0;
1635     if (CCMask == SystemZ::CCMASK_CMP_GE)
1636       return SystemZ::CCMASK_TM_SOME_1;
1637   }
1638   if (EffectivelyUnsigned && CmpVal < Low) {
1639     if (CCMask == SystemZ::CCMASK_CMP_LE)
1640       return SystemZ::CCMASK_TM_ALL_0;
1641     if (CCMask == SystemZ::CCMASK_CMP_GT)
1642       return SystemZ::CCMASK_TM_SOME_1;
1643   }
1644
1645   // Check for equality comparisons with the mask, or the equivalent.
1646   if (CmpVal == Mask) {
1647     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1648       return SystemZ::CCMASK_TM_ALL_1;
1649     if (CCMask == SystemZ::CCMASK_CMP_NE)
1650       return SystemZ::CCMASK_TM_SOME_0;
1651   }
1652   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1653     if (CCMask == SystemZ::CCMASK_CMP_GT)
1654       return SystemZ::CCMASK_TM_ALL_1;
1655     if (CCMask == SystemZ::CCMASK_CMP_LE)
1656       return SystemZ::CCMASK_TM_SOME_0;
1657   }
1658   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1659     if (CCMask == SystemZ::CCMASK_CMP_GE)
1660       return SystemZ::CCMASK_TM_ALL_1;
1661     if (CCMask == SystemZ::CCMASK_CMP_LT)
1662       return SystemZ::CCMASK_TM_SOME_0;
1663   }
1664
1665   // Check for ordered comparisons with the top bit.
1666   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1667     if (CCMask == SystemZ::CCMASK_CMP_LE)
1668       return SystemZ::CCMASK_TM_MSB_0;
1669     if (CCMask == SystemZ::CCMASK_CMP_GT)
1670       return SystemZ::CCMASK_TM_MSB_1;
1671   }
1672   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1673     if (CCMask == SystemZ::CCMASK_CMP_LT)
1674       return SystemZ::CCMASK_TM_MSB_0;
1675     if (CCMask == SystemZ::CCMASK_CMP_GE)
1676       return SystemZ::CCMASK_TM_MSB_1;
1677   }
1678
1679   // If there are just two bits, we can do equality checks for Low and High
1680   // as well.
1681   if (Mask == Low + High) {
1682     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1683       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1684     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1685       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1686     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1687       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1688     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1689       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1690   }
1691
1692   // Looks like we've exhausted our options.
1693   return 0;
1694 }
1695
1696 // See whether C can be implemented as a TEST UNDER MASK instruction.
1697 // Update the arguments with the TM version if so.
1698 static void adjustForTestUnderMask(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1699   // Check that we have a comparison with a constant.
1700   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1701   if (!ConstOp1)
1702     return;
1703   uint64_t CmpVal = ConstOp1->getZExtValue();
1704
1705   // Check whether the nonconstant input is an AND with a constant mask.
1706   Comparison NewC(C);
1707   uint64_t MaskVal;
1708   ConstantSDNode *Mask = nullptr;
1709   if (C.Op0.getOpcode() == ISD::AND) {
1710     NewC.Op0 = C.Op0.getOperand(0);
1711     NewC.Op1 = C.Op0.getOperand(1);
1712     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1713     if (!Mask)
1714       return;
1715     MaskVal = Mask->getZExtValue();
1716   } else {
1717     // There is no instruction to compare with a 64-bit immediate
1718     // so use TMHH instead if possible.  We need an unsigned ordered
1719     // comparison with an i64 immediate.
1720     if (NewC.Op0.getValueType() != MVT::i64 ||
1721         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1722         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1723         NewC.ICmpType == SystemZICMP::SignedOnly)
1724       return;
1725     // Convert LE and GT comparisons into LT and GE.
1726     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1727         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1728       if (CmpVal == uint64_t(-1))
1729         return;
1730       CmpVal += 1;
1731       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1732     }
1733     // If the low N bits of Op1 are zero than the low N bits of Op0 can
1734     // be masked off without changing the result.
1735     MaskVal = -(CmpVal & -CmpVal);
1736     NewC.ICmpType = SystemZICMP::UnsignedOnly;
1737   }
1738   if (!MaskVal)
1739     return;
1740
1741   // Check whether the combination of mask, comparison value and comparison
1742   // type are suitable.
1743   unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
1744   unsigned NewCCMask, ShiftVal;
1745   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1746       NewC.Op0.getOpcode() == ISD::SHL &&
1747       isSimpleShift(NewC.Op0, ShiftVal) &&
1748       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1749                                         MaskVal >> ShiftVal,
1750                                         CmpVal >> ShiftVal,
1751                                         SystemZICMP::Any))) {
1752     NewC.Op0 = NewC.Op0.getOperand(0);
1753     MaskVal >>= ShiftVal;
1754   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1755              NewC.Op0.getOpcode() == ISD::SRL &&
1756              isSimpleShift(NewC.Op0, ShiftVal) &&
1757              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1758                                                MaskVal << ShiftVal,
1759                                                CmpVal << ShiftVal,
1760                                                SystemZICMP::UnsignedOnly))) {
1761     NewC.Op0 = NewC.Op0.getOperand(0);
1762     MaskVal <<= ShiftVal;
1763   } else {
1764     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
1765                                      NewC.ICmpType);
1766     if (!NewCCMask)
1767       return;
1768   }
1769
1770   // Go ahead and make the change.
1771   C.Opcode = SystemZISD::TM;
1772   C.Op0 = NewC.Op0;
1773   if (Mask && Mask->getZExtValue() == MaskVal)
1774     C.Op1 = SDValue(Mask, 0);
1775   else
1776     C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
1777   C.CCValid = SystemZ::CCMASK_TM;
1778   C.CCMask = NewCCMask;
1779 }
1780
1781 // Return a Comparison that tests the condition-code result of intrinsic
1782 // node Call against constant integer CC using comparison code Cond.
1783 // Opcode is the opcode of the SystemZISD operation for the intrinsic
1784 // and CCValid is the set of possible condition-code results.
1785 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
1786                                   SDValue Call, unsigned CCValid, uint64_t CC,
1787                                   ISD::CondCode Cond) {
1788   Comparison C(Call, SDValue());
1789   C.Opcode = Opcode;
1790   C.CCValid = CCValid;
1791   if (Cond == ISD::SETEQ)
1792     // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
1793     C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
1794   else if (Cond == ISD::SETNE)
1795     // ...and the inverse of that.
1796     C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
1797   else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
1798     // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
1799     // always true for CC>3.
1800     C.CCMask = CC < 4 ? -1 << (4 - CC) : -1;
1801   else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
1802     // ...and the inverse of that.
1803     C.CCMask = CC < 4 ? ~(-1 << (4 - CC)) : 0;
1804   else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
1805     // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
1806     // always true for CC>3.
1807     C.CCMask = CC < 4 ? -1 << (3 - CC) : -1;
1808   else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
1809     // ...and the inverse of that.
1810     C.CCMask = CC < 4 ? ~(-1 << (3 - CC)) : 0;
1811   else
1812     llvm_unreachable("Unexpected integer comparison type");
1813   C.CCMask &= CCValid;
1814   return C;
1815 }
1816
1817 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
1818 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
1819                          ISD::CondCode Cond, SDLoc DL) {
1820   if (CmpOp1.getOpcode() == ISD::Constant) {
1821     uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
1822     unsigned Opcode, CCValid;
1823     if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
1824         CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
1825         isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
1826       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
1827   }
1828   Comparison C(CmpOp0, CmpOp1);
1829   C.CCMask = CCMaskForCondCode(Cond);
1830   if (C.Op0.getValueType().isFloatingPoint()) {
1831     C.CCValid = SystemZ::CCMASK_FCMP;
1832     C.Opcode = SystemZISD::FCMP;
1833     adjustForFNeg(C);
1834   } else {
1835     C.CCValid = SystemZ::CCMASK_ICMP;
1836     C.Opcode = SystemZISD::ICMP;
1837     // Choose the type of comparison.  Equality and inequality tests can
1838     // use either signed or unsigned comparisons.  The choice also doesn't
1839     // matter if both sign bits are known to be clear.  In those cases we
1840     // want to give the main isel code the freedom to choose whichever
1841     // form fits best.
1842     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1843         C.CCMask == SystemZ::CCMASK_CMP_NE ||
1844         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
1845       C.ICmpType = SystemZICMP::Any;
1846     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
1847       C.ICmpType = SystemZICMP::UnsignedOnly;
1848     else
1849       C.ICmpType = SystemZICMP::SignedOnly;
1850     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
1851     adjustZeroCmp(DAG, DL, C);
1852     adjustSubwordCmp(DAG, DL, C);
1853     adjustForSubtraction(DAG, DL, C);
1854     adjustForLTGFR(C);
1855     adjustICmpTruncate(DAG, DL, C);
1856   }
1857
1858   if (shouldSwapCmpOperands(C)) {
1859     std::swap(C.Op0, C.Op1);
1860     C.CCMask = reverseCCMask(C.CCMask);
1861   }
1862
1863   adjustForTestUnderMask(DAG, DL, C);
1864   return C;
1865 }
1866
1867 // Emit the comparison instruction described by C.
1868 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1869   if (!C.Op1.getNode()) {
1870     SDValue Op;
1871     switch (C.Op0.getOpcode()) {
1872     case ISD::INTRINSIC_W_CHAIN:
1873       Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
1874       break;
1875     default:
1876       llvm_unreachable("Invalid comparison operands");
1877     }
1878     return SDValue(Op.getNode(), Op->getNumValues() - 1);
1879   }
1880   if (C.Opcode == SystemZISD::ICMP)
1881     return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
1882                        DAG.getConstant(C.ICmpType, DL, MVT::i32));
1883   if (C.Opcode == SystemZISD::TM) {
1884     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1885                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1886     return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
1887                        DAG.getConstant(RegisterOnly, DL, MVT::i32));
1888   }
1889   return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
1890 }
1891
1892 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1893 // 64 bits.  Extend is the extension type to use.  Store the high part
1894 // in Hi and the low part in Lo.
1895 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1896                             unsigned Extend, SDValue Op0, SDValue Op1,
1897                             SDValue &Hi, SDValue &Lo) {
1898   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1899   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1900   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1901   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1902                    DAG.getConstant(32, DL, MVT::i64));
1903   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1904   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1905 }
1906
1907 // Lower a binary operation that produces two VT results, one in each
1908 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
1909 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1910 // on the extended Op0 and (unextended) Op1.  Store the even register result
1911 // in Even and the odd register result in Odd.
1912 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1913                              unsigned Extend, unsigned Opcode,
1914                              SDValue Op0, SDValue Op1,
1915                              SDValue &Even, SDValue &Odd) {
1916   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1917   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1918                                SDValue(In128, 0), Op1);
1919   bool Is32Bit = is32Bit(VT);
1920   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
1921   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
1922 }
1923
1924 // Return an i32 value that is 1 if the CC value produced by Glue is
1925 // in the mask CCMask and 0 otherwise.  CC is known to have a value
1926 // in CCValid, so other values can be ignored.
1927 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
1928                          unsigned CCValid, unsigned CCMask) {
1929   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
1930   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
1931
1932   if (Conversion.XORValue)
1933     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
1934                          DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
1935
1936   if (Conversion.AddValue)
1937     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
1938                          DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
1939
1940   // The SHR/AND sequence should get optimized to an RISBG.
1941   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
1942                        DAG.getConstant(Conversion.Bit, DL, MVT::i32));
1943   if (Conversion.Bit != 31)
1944     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
1945                          DAG.getConstant(1, DL, MVT::i32));
1946   return Result;
1947 }
1948
1949 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
1950 // be done directly.  IsFP is true if CC is for a floating-point rather than
1951 // integer comparison.
1952 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
1953   switch (CC) {
1954   case ISD::SETOEQ:
1955   case ISD::SETEQ:
1956     return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
1957
1958   case ISD::SETOGE:
1959   case ISD::SETGE:
1960     return IsFP ? SystemZISD::VFCMPHE : 0;
1961
1962   case ISD::SETOGT:
1963   case ISD::SETGT:
1964     return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
1965
1966   case ISD::SETUGT:
1967     return IsFP ? 0 : SystemZISD::VICMPHL;
1968
1969   default:
1970     return 0;
1971   }
1972 }
1973
1974 // Return the SystemZISD vector comparison operation for CC or its inverse,
1975 // or 0 if neither can be done directly.  Indicate in Invert whether the
1976 // result is for the inverse of CC.  IsFP is true if CC is for a
1977 // floating-point rather than integer comparison.
1978 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
1979                                             bool &Invert) {
1980   if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
1981     Invert = false;
1982     return Opcode;
1983   }
1984
1985   CC = ISD::getSetCCInverse(CC, !IsFP);
1986   if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
1987     Invert = true;
1988     return Opcode;
1989   }
1990
1991   return 0;
1992 }
1993
1994 // Return a v2f64 that contains the extended form of elements Start and Start+1
1995 // of v4f32 value Op.
1996 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, SDLoc DL,
1997                                   SDValue Op) {
1998   int Mask[] = { Start, -1, Start + 1, -1 };
1999   Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2000   return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2001 }
2002
2003 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2004 // producing a result of type VT.
2005 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, SDLoc DL,
2006                             EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2007   // There is no hardware support for v4f32, so extend the vector into
2008   // two v2f64s and compare those.
2009   if (CmpOp0.getValueType() == MVT::v4f32) {
2010     SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2011     SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2012     SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2013     SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2014     SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2015     SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2016     return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2017   }
2018   return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2019 }
2020
2021 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2022 // an integer mask of type VT.
2023 static SDValue lowerVectorSETCC(SelectionDAG &DAG, SDLoc DL, EVT VT,
2024                                 ISD::CondCode CC, SDValue CmpOp0,
2025                                 SDValue CmpOp1) {
2026   bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2027   bool Invert = false;
2028   SDValue Cmp;
2029   switch (CC) {
2030     // Handle tests for order using (or (ogt y x) (oge x y)).
2031   case ISD::SETUO:
2032     Invert = true;
2033   case ISD::SETO: {
2034     assert(IsFP && "Unexpected integer comparison");
2035     SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2036     SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2037     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2038     break;
2039   }
2040
2041     // Handle <> tests using (or (ogt y x) (ogt x y)).
2042   case ISD::SETUEQ:
2043     Invert = true;
2044   case ISD::SETONE: {
2045     assert(IsFP && "Unexpected integer comparison");
2046     SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2047     SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2048     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2049     break;
2050   }
2051
2052     // Otherwise a single comparison is enough.  It doesn't really
2053     // matter whether we try the inversion or the swap first, since
2054     // there are no cases where both work.
2055   default:
2056     if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2057       Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2058     else {
2059       CC = ISD::getSetCCSwappedOperands(CC);
2060       if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2061         Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2062       else
2063         llvm_unreachable("Unhandled comparison");
2064     }
2065     break;
2066   }
2067   if (Invert) {
2068     SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2069                                DAG.getConstant(65535, DL, MVT::i32));
2070     Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2071     Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2072   }
2073   return Cmp;
2074 }
2075
2076 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2077                                           SelectionDAG &DAG) const {
2078   SDValue CmpOp0   = Op.getOperand(0);
2079   SDValue CmpOp1   = Op.getOperand(1);
2080   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2081   SDLoc DL(Op);
2082   EVT VT = Op.getValueType();
2083   if (VT.isVector())
2084     return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2085
2086   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2087   SDValue Glue = emitCmp(DAG, DL, C);
2088   return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2089 }
2090
2091 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2092   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2093   SDValue CmpOp0   = Op.getOperand(2);
2094   SDValue CmpOp1   = Op.getOperand(3);
2095   SDValue Dest     = Op.getOperand(4);
2096   SDLoc DL(Op);
2097
2098   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2099   SDValue Glue = emitCmp(DAG, DL, C);
2100   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2101                      Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2102                      DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2103 }
2104
2105 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2106 // allowing Pos and Neg to be wider than CmpOp.
2107 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2108   return (Neg.getOpcode() == ISD::SUB &&
2109           Neg.getOperand(0).getOpcode() == ISD::Constant &&
2110           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2111           Neg.getOperand(1) == Pos &&
2112           (Pos == CmpOp ||
2113            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2114             Pos.getOperand(0) == CmpOp)));
2115 }
2116
2117 // Return the absolute or negative absolute of Op; IsNegative decides which.
2118 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
2119                            bool IsNegative) {
2120   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2121   if (IsNegative)
2122     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2123                      DAG.getConstant(0, DL, Op.getValueType()), Op);
2124   return Op;
2125 }
2126
2127 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2128                                               SelectionDAG &DAG) const {
2129   SDValue CmpOp0   = Op.getOperand(0);
2130   SDValue CmpOp1   = Op.getOperand(1);
2131   SDValue TrueOp   = Op.getOperand(2);
2132   SDValue FalseOp  = Op.getOperand(3);
2133   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2134   SDLoc DL(Op);
2135
2136   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2137
2138   // Check for absolute and negative-absolute selections, including those
2139   // where the comparison value is sign-extended (for LPGFR and LNGFR).
2140   // This check supplements the one in DAGCombiner.
2141   if (C.Opcode == SystemZISD::ICMP &&
2142       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2143       C.CCMask != SystemZ::CCMASK_CMP_NE &&
2144       C.Op1.getOpcode() == ISD::Constant &&
2145       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2146     if (isAbsolute(C.Op0, TrueOp, FalseOp))
2147       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2148     if (isAbsolute(C.Op0, FalseOp, TrueOp))
2149       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2150   }
2151
2152   SDValue Glue = emitCmp(DAG, DL, C);
2153
2154   // Special case for handling -1/0 results.  The shifts we use here
2155   // should get optimized with the IPM conversion sequence.
2156   auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2157   auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2158   if (TrueC && FalseC) {
2159     int64_t TrueVal = TrueC->getSExtValue();
2160     int64_t FalseVal = FalseC->getSExtValue();
2161     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2162       // Invert the condition if we want -1 on false.
2163       if (TrueVal == 0)
2164         C.CCMask ^= C.CCValid;
2165       SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2166       EVT VT = Op.getValueType();
2167       // Extend the result to VT.  Upper bits are ignored.
2168       if (!is32Bit(VT))
2169         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2170       // Sign-extend from the low bit.
2171       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2172       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2173       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2174     }
2175   }
2176
2177   SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2178                    DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2179
2180   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2181   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2182 }
2183
2184 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2185                                                   SelectionDAG &DAG) const {
2186   SDLoc DL(Node);
2187   const GlobalValue *GV = Node->getGlobal();
2188   int64_t Offset = Node->getOffset();
2189   EVT PtrVT = getPointerTy();
2190   Reloc::Model RM = DAG.getTarget().getRelocationModel();
2191   CodeModel::Model CM = DAG.getTarget().getCodeModel();
2192
2193   SDValue Result;
2194   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
2195     // Assign anchors at 1<<12 byte boundaries.
2196     uint64_t Anchor = Offset & ~uint64_t(0xfff);
2197     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2198     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2199
2200     // The offset can be folded into the address if it is aligned to a halfword.
2201     Offset -= Anchor;
2202     if (Offset != 0 && (Offset & 1) == 0) {
2203       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2204       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2205       Offset = 0;
2206     }
2207   } else {
2208     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2209     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2210     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2211                          MachinePointerInfo::getGOT(), false, false, false, 0);
2212   }
2213
2214   // If there was a non-zero offset that we didn't fold, create an explicit
2215   // addition for it.
2216   if (Offset != 0)
2217     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2218                          DAG.getConstant(Offset, DL, PtrVT));
2219
2220   return Result;
2221 }
2222
2223 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2224                                                  SelectionDAG &DAG,
2225                                                  unsigned Opcode,
2226                                                  SDValue GOTOffset) const {
2227   SDLoc DL(Node);
2228   EVT PtrVT = getPointerTy();
2229   SDValue Chain = DAG.getEntryNode();
2230   SDValue Glue;
2231
2232   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2233   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2234   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2235   Glue = Chain.getValue(1);
2236   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2237   Glue = Chain.getValue(1);
2238
2239   // The first call operand is the chain and the second is the TLS symbol.
2240   SmallVector<SDValue, 8> Ops;
2241   Ops.push_back(Chain);
2242   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2243                                            Node->getValueType(0),
2244                                            0, 0));
2245
2246   // Add argument registers to the end of the list so that they are
2247   // known live into the call.
2248   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2249   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2250
2251   // Add a register mask operand representing the call-preserved registers.
2252   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2253   const uint32_t *Mask =
2254       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2255   assert(Mask && "Missing call preserved mask for calling convention");
2256   Ops.push_back(DAG.getRegisterMask(Mask));
2257
2258   // Glue the call to the argument copies.
2259   Ops.push_back(Glue);
2260
2261   // Emit the call.
2262   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2263   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2264   Glue = Chain.getValue(1);
2265
2266   // Copy the return value from %r2.
2267   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2268 }
2269
2270 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2271                                                      SelectionDAG &DAG) const {
2272   SDLoc DL(Node);
2273   const GlobalValue *GV = Node->getGlobal();
2274   EVT PtrVT = getPointerTy();
2275   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2276
2277   // The high part of the thread pointer is in access register 0.
2278   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2279                              DAG.getConstant(0, DL, MVT::i32));
2280   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2281
2282   // The low part of the thread pointer is in access register 1.
2283   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2284                              DAG.getConstant(1, DL, MVT::i32));
2285   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2286
2287   // Merge them into a single 64-bit address.
2288   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2289                                     DAG.getConstant(32, DL, PtrVT));
2290   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2291
2292   // Get the offset of GA from the thread pointer, based on the TLS model.
2293   SDValue Offset;
2294   switch (model) {
2295     case TLSModel::GeneralDynamic: {
2296       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2297       SystemZConstantPoolValue *CPV =
2298         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2299
2300       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2301       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2302                            Offset, MachinePointerInfo::getConstantPool(),
2303                            false, false, false, 0);
2304
2305       // Call __tls_get_offset to retrieve the offset.
2306       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2307       break;
2308     }
2309
2310     case TLSModel::LocalDynamic: {
2311       // Load the GOT offset of the module ID.
2312       SystemZConstantPoolValue *CPV =
2313         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2314
2315       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2316       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2317                            Offset, MachinePointerInfo::getConstantPool(),
2318                            false, false, false, 0);
2319
2320       // Call __tls_get_offset to retrieve the module base offset.
2321       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2322
2323       // Note: The SystemZLDCleanupPass will remove redundant computations
2324       // of the module base offset.  Count total number of local-dynamic
2325       // accesses to trigger execution of that pass.
2326       SystemZMachineFunctionInfo* MFI =
2327         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2328       MFI->incNumLocalDynamicTLSAccesses();
2329
2330       // Add the per-symbol offset.
2331       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2332
2333       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2334       DTPOffset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2335                               DTPOffset, MachinePointerInfo::getConstantPool(),
2336                               false, false, false, 0);
2337
2338       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2339       break;
2340     }
2341
2342     case TLSModel::InitialExec: {
2343       // Load the offset from the GOT.
2344       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2345                                           SystemZII::MO_INDNTPOFF);
2346       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2347       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2348                            Offset, MachinePointerInfo::getGOT(),
2349                            false, false, false, 0);
2350       break;
2351     }
2352
2353     case TLSModel::LocalExec: {
2354       // Force the offset into the constant pool and load it from there.
2355       SystemZConstantPoolValue *CPV =
2356         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2357
2358       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2359       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2360                            Offset, MachinePointerInfo::getConstantPool(),
2361                            false, false, false, 0);
2362       break;
2363     }
2364   }
2365
2366   // Add the base and offset together.
2367   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2368 }
2369
2370 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2371                                                  SelectionDAG &DAG) const {
2372   SDLoc DL(Node);
2373   const BlockAddress *BA = Node->getBlockAddress();
2374   int64_t Offset = Node->getOffset();
2375   EVT PtrVT = getPointerTy();
2376
2377   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2378   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2379   return Result;
2380 }
2381
2382 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2383                                               SelectionDAG &DAG) const {
2384   SDLoc DL(JT);
2385   EVT PtrVT = getPointerTy();
2386   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2387
2388   // Use LARL to load the address of the table.
2389   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2390 }
2391
2392 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2393                                                  SelectionDAG &DAG) const {
2394   SDLoc DL(CP);
2395   EVT PtrVT = getPointerTy();
2396
2397   SDValue Result;
2398   if (CP->isMachineConstantPoolEntry())
2399     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2400                                        CP->getAlignment());
2401   else
2402     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2403                                        CP->getAlignment(), CP->getOffset());
2404
2405   // Use LARL to load the address of the constant pool entry.
2406   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2407 }
2408
2409 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2410                                             SelectionDAG &DAG) const {
2411   SDLoc DL(Op);
2412   SDValue In = Op.getOperand(0);
2413   EVT InVT = In.getValueType();
2414   EVT ResVT = Op.getValueType();
2415
2416   // Convert loads directly.  This is normally done by DAGCombiner,
2417   // but we need this case for bitcasts that are created during lowering
2418   // and which are then lowered themselves.
2419   if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2420     return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2421                        LoadN->getMemOperand());
2422
2423   if (InVT == MVT::i32 && ResVT == MVT::f32) {
2424     SDValue In64;
2425     if (Subtarget.hasHighWord()) {
2426       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2427                                        MVT::i64);
2428       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2429                                        MVT::i64, SDValue(U64, 0), In);
2430     } else {
2431       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2432       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2433                          DAG.getConstant(32, DL, MVT::i64));
2434     }
2435     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2436     return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2437                                       DL, MVT::f32, Out64);
2438   }
2439   if (InVT == MVT::f32 && ResVT == MVT::i32) {
2440     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2441     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2442                                              MVT::f64, SDValue(U64, 0), In);
2443     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2444     if (Subtarget.hasHighWord())
2445       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2446                                         MVT::i32, Out64);
2447     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2448                                 DAG.getConstant(32, DL, MVT::i64));
2449     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2450   }
2451   llvm_unreachable("Unexpected bitcast combination");
2452 }
2453
2454 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2455                                             SelectionDAG &DAG) const {
2456   MachineFunction &MF = DAG.getMachineFunction();
2457   SystemZMachineFunctionInfo *FuncInfo =
2458     MF.getInfo<SystemZMachineFunctionInfo>();
2459   EVT PtrVT = getPointerTy();
2460
2461   SDValue Chain   = Op.getOperand(0);
2462   SDValue Addr    = Op.getOperand(1);
2463   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2464   SDLoc DL(Op);
2465
2466   // The initial values of each field.
2467   const unsigned NumFields = 4;
2468   SDValue Fields[NumFields] = {
2469     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2470     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2471     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2472     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2473   };
2474
2475   // Store each field into its respective slot.
2476   SDValue MemOps[NumFields];
2477   unsigned Offset = 0;
2478   for (unsigned I = 0; I < NumFields; ++I) {
2479     SDValue FieldAddr = Addr;
2480     if (Offset != 0)
2481       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2482                               DAG.getIntPtrConstant(Offset, DL));
2483     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2484                              MachinePointerInfo(SV, Offset),
2485                              false, false, 0);
2486     Offset += 8;
2487   }
2488   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2489 }
2490
2491 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2492                                            SelectionDAG &DAG) const {
2493   SDValue Chain      = Op.getOperand(0);
2494   SDValue DstPtr     = Op.getOperand(1);
2495   SDValue SrcPtr     = Op.getOperand(2);
2496   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2497   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2498   SDLoc DL(Op);
2499
2500   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2501                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2502                        /*isTailCall*/false,
2503                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2504 }
2505
2506 SDValue SystemZTargetLowering::
2507 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2508   SDValue Chain = Op.getOperand(0);
2509   SDValue Size  = Op.getOperand(1);
2510   SDLoc DL(Op);
2511
2512   unsigned SPReg = getStackPointerRegisterToSaveRestore();
2513
2514   // Get a reference to the stack pointer.
2515   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2516
2517   // Get the new stack pointer value.
2518   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
2519
2520   // Copy the new stack pointer back.
2521   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2522
2523   // The allocated data lives above the 160 bytes allocated for the standard
2524   // frame, plus any outgoing stack arguments.  We don't know how much that
2525   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2526   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2527   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2528
2529   SDValue Ops[2] = { Result, Chain };
2530   return DAG.getMergeValues(Ops, DL);
2531 }
2532
2533 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2534                                               SelectionDAG &DAG) const {
2535   EVT VT = Op.getValueType();
2536   SDLoc DL(Op);
2537   SDValue Ops[2];
2538   if (is32Bit(VT))
2539     // Just do a normal 64-bit multiplication and extract the results.
2540     // We define this so that it can be used for constant division.
2541     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2542                     Op.getOperand(1), Ops[1], Ops[0]);
2543   else {
2544     // Do a full 128-bit multiplication based on UMUL_LOHI64:
2545     //
2546     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2547     //
2548     // but using the fact that the upper halves are either all zeros
2549     // or all ones:
2550     //
2551     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2552     //
2553     // and grouping the right terms together since they are quicker than the
2554     // multiplication:
2555     //
2556     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2557     SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2558     SDValue LL = Op.getOperand(0);
2559     SDValue RL = Op.getOperand(1);
2560     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2561     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2562     // UMUL_LOHI64 returns the low result in the odd register and the high
2563     // result in the even register.  SMUL_LOHI is defined to return the
2564     // low half first, so the results are in reverse order.
2565     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2566                      LL, RL, Ops[1], Ops[0]);
2567     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2568     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2569     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2570     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2571   }
2572   return DAG.getMergeValues(Ops, DL);
2573 }
2574
2575 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2576                                               SelectionDAG &DAG) const {
2577   EVT VT = Op.getValueType();
2578   SDLoc DL(Op);
2579   SDValue Ops[2];
2580   if (is32Bit(VT))
2581     // Just do a normal 64-bit multiplication and extract the results.
2582     // We define this so that it can be used for constant division.
2583     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2584                     Op.getOperand(1), Ops[1], Ops[0]);
2585   else
2586     // UMUL_LOHI64 returns the low result in the odd register and the high
2587     // result in the even register.  UMUL_LOHI is defined to return the
2588     // low half first, so the results are in reverse order.
2589     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2590                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2591   return DAG.getMergeValues(Ops, DL);
2592 }
2593
2594 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2595                                             SelectionDAG &DAG) const {
2596   SDValue Op0 = Op.getOperand(0);
2597   SDValue Op1 = Op.getOperand(1);
2598   EVT VT = Op.getValueType();
2599   SDLoc DL(Op);
2600   unsigned Opcode;
2601
2602   // We use DSGF for 32-bit division.
2603   if (is32Bit(VT)) {
2604     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2605     Opcode = SystemZISD::SDIVREM32;
2606   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2607     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2608     Opcode = SystemZISD::SDIVREM32;
2609   } else    
2610     Opcode = SystemZISD::SDIVREM64;
2611
2612   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2613   // input is "don't care".  The instruction returns the remainder in
2614   // the even register and the quotient in the odd register.
2615   SDValue Ops[2];
2616   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2617                    Op0, Op1, Ops[1], Ops[0]);
2618   return DAG.getMergeValues(Ops, DL);
2619 }
2620
2621 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
2622                                             SelectionDAG &DAG) const {
2623   EVT VT = Op.getValueType();
2624   SDLoc DL(Op);
2625
2626   // DL(G) uses a double-width dividend, so we need to clear the even
2627   // register in the GR128 input.  The instruction returns the remainder
2628   // in the even register and the quotient in the odd register.
2629   SDValue Ops[2];
2630   if (is32Bit(VT))
2631     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
2632                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2633   else
2634     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2635                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2636   return DAG.getMergeValues(Ops, DL);
2637 }
2638
2639 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2640   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
2641
2642   // Get the known-zero masks for each operand.
2643   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
2644   APInt KnownZero[2], KnownOne[2];
2645   DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
2646   DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
2647
2648   // See if the upper 32 bits of one operand and the lower 32 bits of the
2649   // other are known zero.  They are the low and high operands respectively.
2650   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
2651                        KnownZero[1].getZExtValue() };
2652   unsigned High, Low;
2653   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
2654     High = 1, Low = 0;
2655   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
2656     High = 0, Low = 1;
2657   else
2658     return Op;
2659
2660   SDValue LowOp = Ops[Low];
2661   SDValue HighOp = Ops[High];
2662
2663   // If the high part is a constant, we're better off using IILH.
2664   if (HighOp.getOpcode() == ISD::Constant)
2665     return Op;
2666
2667   // If the low part is a constant that is outside the range of LHI,
2668   // then we're better off using IILF.
2669   if (LowOp.getOpcode() == ISD::Constant) {
2670     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
2671     if (!isInt<16>(Value))
2672       return Op;
2673   }
2674
2675   // Check whether the high part is an AND that doesn't change the
2676   // high 32 bits and just masks out low bits.  We can skip it if so.
2677   if (HighOp.getOpcode() == ISD::AND &&
2678       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
2679     SDValue HighOp0 = HighOp.getOperand(0);
2680     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
2681     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
2682       HighOp = HighOp0;
2683   }
2684
2685   // Take advantage of the fact that all GR32 operations only change the
2686   // low 32 bits by truncating Low to an i32 and inserting it directly
2687   // using a subreg.  The interesting cases are those where the truncation
2688   // can be folded.
2689   SDLoc DL(Op);
2690   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
2691   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
2692                                    MVT::i64, HighOp, Low32);
2693 }
2694
2695 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
2696                                           SelectionDAG &DAG) const {
2697   EVT VT = Op.getValueType();
2698   SDLoc DL(Op);
2699   Op = Op.getOperand(0);
2700
2701   // Handle vector types via VPOPCT.
2702   if (VT.isVector()) {
2703     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
2704     Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
2705     switch (VT.getVectorElementType().getSizeInBits()) {
2706     case 8:
2707       break;
2708     case 16: {
2709       Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
2710       SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
2711       SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
2712       Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2713       Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
2714       break;
2715     }
2716     case 32: {
2717       SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2718                                 DAG.getConstant(0, DL, MVT::i32));
2719       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2720       break;
2721     }
2722     case 64: {
2723       SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2724                                 DAG.getConstant(0, DL, MVT::i32));
2725       Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
2726       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2727       break;
2728     }
2729     default:
2730       llvm_unreachable("Unexpected type");
2731     }
2732     return Op;
2733   }
2734
2735   // Get the known-zero mask for the operand.
2736   APInt KnownZero, KnownOne;
2737   DAG.computeKnownBits(Op, KnownZero, KnownOne);
2738   unsigned NumSignificantBits = (~KnownZero).getActiveBits();
2739   if (NumSignificantBits == 0)
2740     return DAG.getConstant(0, DL, VT);
2741
2742   // Skip known-zero high parts of the operand.
2743   int64_t OrigBitSize = VT.getSizeInBits();
2744   int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
2745   BitSize = std::min(BitSize, OrigBitSize);
2746
2747   // The POPCNT instruction counts the number of bits in each byte.
2748   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
2749   Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
2750   Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
2751
2752   // Add up per-byte counts in a binary tree.  All bits of Op at
2753   // position larger than BitSize remain zero throughout.
2754   for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
2755     SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
2756     if (BitSize != OrigBitSize)
2757       Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
2758                         DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
2759     Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2760   }
2761
2762   // Extract overall result from high byte.
2763   if (BitSize > 8)
2764     Op = DAG.getNode(ISD::SRL, DL, VT, Op,
2765                      DAG.getConstant(BitSize - 8, DL, VT));
2766
2767   return Op;
2768 }
2769
2770 // Op is an atomic load.  Lower it into a normal volatile load.
2771 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
2772                                                 SelectionDAG &DAG) const {
2773   auto *Node = cast<AtomicSDNode>(Op.getNode());
2774   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
2775                         Node->getChain(), Node->getBasePtr(),
2776                         Node->getMemoryVT(), Node->getMemOperand());
2777 }
2778
2779 // Op is an atomic store.  Lower it into a normal volatile store followed
2780 // by a serialization.
2781 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
2782                                                  SelectionDAG &DAG) const {
2783   auto *Node = cast<AtomicSDNode>(Op.getNode());
2784   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
2785                                     Node->getBasePtr(), Node->getMemoryVT(),
2786                                     Node->getMemOperand());
2787   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
2788                                     Chain), 0);
2789 }
2790
2791 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
2792 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
2793 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
2794                                                    SelectionDAG &DAG,
2795                                                    unsigned Opcode) const {
2796   auto *Node = cast<AtomicSDNode>(Op.getNode());
2797
2798   // 32-bit operations need no code outside the main loop.
2799   EVT NarrowVT = Node->getMemoryVT();
2800   EVT WideVT = MVT::i32;
2801   if (NarrowVT == WideVT)
2802     return Op;
2803
2804   int64_t BitSize = NarrowVT.getSizeInBits();
2805   SDValue ChainIn = Node->getChain();
2806   SDValue Addr = Node->getBasePtr();
2807   SDValue Src2 = Node->getVal();
2808   MachineMemOperand *MMO = Node->getMemOperand();
2809   SDLoc DL(Node);
2810   EVT PtrVT = Addr.getValueType();
2811
2812   // Convert atomic subtracts of constants into additions.
2813   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
2814     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
2815       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
2816       Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
2817     }
2818
2819   // Get the address of the containing word.
2820   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2821                                     DAG.getConstant(-4, DL, PtrVT));
2822
2823   // Get the number of bits that the word must be rotated left in order
2824   // to bring the field to the top bits of a GR32.
2825   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2826                                  DAG.getConstant(3, DL, PtrVT));
2827   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2828
2829   // Get the complementing shift amount, for rotating a field in the top
2830   // bits back to its proper position.
2831   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2832                                     DAG.getConstant(0, DL, WideVT), BitShift);
2833
2834   // Extend the source operand to 32 bits and prepare it for the inner loop.
2835   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
2836   // operations require the source to be shifted in advance.  (This shift
2837   // can be folded if the source is constant.)  For AND and NAND, the lower
2838   // bits must be set, while for other opcodes they should be left clear.
2839   if (Opcode != SystemZISD::ATOMIC_SWAPW)
2840     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
2841                        DAG.getConstant(32 - BitSize, DL, WideVT));
2842   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
2843       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
2844     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
2845                        DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
2846
2847   // Construct the ATOMIC_LOADW_* node.
2848   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2849   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
2850                     DAG.getConstant(BitSize, DL, WideVT) };
2851   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
2852                                              NarrowVT, MMO);
2853
2854   // Rotate the result of the final CS so that the field is in the lower
2855   // bits of a GR32, then truncate it.
2856   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
2857                                     DAG.getConstant(BitSize, DL, WideVT));
2858   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
2859
2860   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
2861   return DAG.getMergeValues(RetOps, DL);
2862 }
2863
2864 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
2865 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
2866 // operations into additions.
2867 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
2868                                                     SelectionDAG &DAG) const {
2869   auto *Node = cast<AtomicSDNode>(Op.getNode());
2870   EVT MemVT = Node->getMemoryVT();
2871   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
2872     // A full-width operation.
2873     assert(Op.getValueType() == MemVT && "Mismatched VTs");
2874     SDValue Src2 = Node->getVal();
2875     SDValue NegSrc2;
2876     SDLoc DL(Src2);
2877
2878     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
2879       // Use an addition if the operand is constant and either LAA(G) is
2880       // available or the negative value is in the range of A(G)FHI.
2881       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
2882       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
2883         NegSrc2 = DAG.getConstant(Value, DL, MemVT);
2884     } else if (Subtarget.hasInterlockedAccess1())
2885       // Use LAA(G) if available.
2886       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
2887                             Src2);
2888
2889     if (NegSrc2.getNode())
2890       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
2891                            Node->getChain(), Node->getBasePtr(), NegSrc2,
2892                            Node->getMemOperand(), Node->getOrdering(),
2893                            Node->getSynchScope());
2894
2895     // Use the node as-is.
2896     return Op;
2897   }
2898
2899   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2900 }
2901
2902 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
2903 // into a fullword ATOMIC_CMP_SWAPW operation.
2904 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
2905                                                     SelectionDAG &DAG) const {
2906   auto *Node = cast<AtomicSDNode>(Op.getNode());
2907
2908   // We have native support for 32-bit compare and swap.
2909   EVT NarrowVT = Node->getMemoryVT();
2910   EVT WideVT = MVT::i32;
2911   if (NarrowVT == WideVT)
2912     return Op;
2913
2914   int64_t BitSize = NarrowVT.getSizeInBits();
2915   SDValue ChainIn = Node->getOperand(0);
2916   SDValue Addr = Node->getOperand(1);
2917   SDValue CmpVal = Node->getOperand(2);
2918   SDValue SwapVal = Node->getOperand(3);
2919   MachineMemOperand *MMO = Node->getMemOperand();
2920   SDLoc DL(Node);
2921   EVT PtrVT = Addr.getValueType();
2922
2923   // Get the address of the containing word.
2924   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2925                                     DAG.getConstant(-4, DL, PtrVT));
2926
2927   // Get the number of bits that the word must be rotated left in order
2928   // to bring the field to the top bits of a GR32.
2929   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2930                                  DAG.getConstant(3, DL, PtrVT));
2931   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2932
2933   // Get the complementing shift amount, for rotating a field in the top
2934   // bits back to its proper position.
2935   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2936                                     DAG.getConstant(0, DL, WideVT), BitShift);
2937
2938   // Construct the ATOMIC_CMP_SWAPW node.
2939   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2940   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
2941                     NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
2942   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
2943                                              VTList, Ops, NarrowVT, MMO);
2944   return AtomicOp;
2945 }
2946
2947 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
2948                                               SelectionDAG &DAG) const {
2949   MachineFunction &MF = DAG.getMachineFunction();
2950   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2951   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
2952                             SystemZ::R15D, Op.getValueType());
2953 }
2954
2955 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
2956                                                  SelectionDAG &DAG) const {
2957   MachineFunction &MF = DAG.getMachineFunction();
2958   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2959   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
2960                           SystemZ::R15D, Op.getOperand(1));
2961 }
2962
2963 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
2964                                              SelectionDAG &DAG) const {
2965   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2966   if (!IsData)
2967     // Just preserve the chain.
2968     return Op.getOperand(0);
2969
2970   SDLoc DL(Op);
2971   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2972   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
2973   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
2974   SDValue Ops[] = {
2975     Op.getOperand(0),
2976     DAG.getConstant(Code, DL, MVT::i32),
2977     Op.getOperand(1)
2978   };
2979   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
2980                                  Node->getVTList(), Ops,
2981                                  Node->getMemoryVT(), Node->getMemOperand());
2982 }
2983
2984 // Return an i32 that contains the value of CC immediately after After,
2985 // whose final operand must be MVT::Glue.
2986 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
2987   SDLoc DL(After);
2988   SDValue Glue = SDValue(After, After->getNumValues() - 1);
2989   SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2990   return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
2991                      DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
2992 }
2993
2994 SDValue
2995 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
2996                                               SelectionDAG &DAG) const {
2997   unsigned Opcode, CCValid;
2998   if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
2999     assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3000     SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3001     SDValue CC = getCCResult(DAG, Glued.getNode());
3002     DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3003     return SDValue();
3004   }
3005
3006   return SDValue();
3007 }
3008
3009 namespace {
3010 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3011 // of a VPERM with permute vector Bytes.  If Opcode takes three operands,
3012 // Operand is the constant third operand, otherwise it is the number of
3013 // bytes in each element of the result.
3014 struct Permute {
3015   unsigned Opcode;
3016   unsigned Operand;
3017   unsigned char Bytes[SystemZ::VectorBytes];
3018 };
3019 }
3020
3021 static const Permute PermuteForms[] = {
3022   // VMRHG
3023   { SystemZISD::MERGE_HIGH, 8,
3024     { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3025   // VMRHF
3026   { SystemZISD::MERGE_HIGH, 4,
3027     { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3028   // VMRHH
3029   { SystemZISD::MERGE_HIGH, 2,
3030     { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3031   // VMRHB
3032   { SystemZISD::MERGE_HIGH, 1,
3033     { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3034   // VMRLG
3035   { SystemZISD::MERGE_LOW, 8,
3036     { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3037   // VMRLF
3038   { SystemZISD::MERGE_LOW, 4,
3039     { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3040   // VMRLH
3041   { SystemZISD::MERGE_LOW, 2,
3042     { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3043   // VMRLB
3044   { SystemZISD::MERGE_LOW, 1,
3045     { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3046   // VPKG
3047   { SystemZISD::PACK, 4,
3048     { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3049   // VPKF
3050   { SystemZISD::PACK, 2,
3051     { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3052   // VPKH
3053   { SystemZISD::PACK, 1,
3054     { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3055   // VPDI V1, V2, 4  (low half of V1, high half of V2)
3056   { SystemZISD::PERMUTE_DWORDS, 4,
3057     { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3058   // VPDI V1, V2, 1  (high half of V1, low half of V2)
3059   { SystemZISD::PERMUTE_DWORDS, 1,
3060     { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3061 };
3062
3063 // Called after matching a vector shuffle against a particular pattern.
3064 // Both the original shuffle and the pattern have two vector operands.
3065 // OpNos[0] is the operand of the original shuffle that should be used for
3066 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3067 // OpNos[1] is the same for operand 1 of the pattern.  Resolve these -1s and
3068 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3069 // for operands 0 and 1 of the pattern.
3070 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3071   if (OpNos[0] < 0) {
3072     if (OpNos[1] < 0)
3073       return false;
3074     OpNo0 = OpNo1 = OpNos[1];
3075   } else if (OpNos[1] < 0) {
3076     OpNo0 = OpNo1 = OpNos[0];
3077   } else {
3078     OpNo0 = OpNos[0];
3079     OpNo1 = OpNos[1];
3080   }
3081   return true;
3082 }
3083
3084 // Bytes is a VPERM-like permute vector, except that -1 is used for
3085 // undefined bytes.  Return true if the VPERM can be implemented using P.
3086 // When returning true set OpNo0 to the VPERM operand that should be
3087 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3088 //
3089 // For example, if swapping the VPERM operands allows P to match, OpNo0
3090 // will be 1 and OpNo1 will be 0.  If instead Bytes only refers to one
3091 // operand, but rewriting it to use two duplicated operands allows it to
3092 // match P, then OpNo0 and OpNo1 will be the same.
3093 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3094                          unsigned &OpNo0, unsigned &OpNo1) {
3095   int OpNos[] = { -1, -1 };
3096   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3097     int Elt = Bytes[I];
3098     if (Elt >= 0) {
3099       // Make sure that the two permute vectors use the same suboperand
3100       // byte number.  Only the operand numbers (the high bits) are
3101       // allowed to differ.
3102       if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3103         return false;
3104       int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3105       int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3106       // Make sure that the operand mappings are consistent with previous
3107       // elements.
3108       if (OpNos[ModelOpNo] == 1 - RealOpNo)
3109         return false;
3110       OpNos[ModelOpNo] = RealOpNo;
3111     }
3112   }
3113   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3114 }
3115
3116 // As above, but search for a matching permute.
3117 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3118                                    unsigned &OpNo0, unsigned &OpNo1) {
3119   for (auto &P : PermuteForms)
3120     if (matchPermute(Bytes, P, OpNo0, OpNo1))
3121       return &P;
3122   return nullptr;
3123 }
3124
3125 // Bytes is a VPERM-like permute vector, except that -1 is used for
3126 // undefined bytes.  This permute is an operand of an outer permute.
3127 // See whether redistributing the -1 bytes gives a shuffle that can be
3128 // implemented using P.  If so, set Transform to a VPERM-like permute vector
3129 // that, when applied to the result of P, gives the original permute in Bytes.
3130 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3131                                const Permute &P,
3132                                SmallVectorImpl<int> &Transform) {
3133   unsigned To = 0;
3134   for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3135     int Elt = Bytes[From];
3136     if (Elt < 0)
3137       // Byte number From of the result is undefined.
3138       Transform[From] = -1;
3139     else {
3140       while (P.Bytes[To] != Elt) {
3141         To += 1;
3142         if (To == SystemZ::VectorBytes)
3143           return false;
3144       }
3145       Transform[From] = To;
3146     }
3147   }
3148   return true;
3149 }
3150
3151 // As above, but search for a matching permute.
3152 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3153                                          SmallVectorImpl<int> &Transform) {
3154   for (auto &P : PermuteForms)
3155     if (matchDoublePermute(Bytes, P, Transform))
3156       return &P;
3157   return nullptr;
3158 }
3159
3160 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3161 // as if it had type vNi8.
3162 static void getVPermMask(ShuffleVectorSDNode *VSN,
3163                          SmallVectorImpl<int> &Bytes) {
3164   EVT VT = VSN->getValueType(0);
3165   unsigned NumElements = VT.getVectorNumElements();
3166   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3167   Bytes.resize(NumElements * BytesPerElement, -1);
3168   for (unsigned I = 0; I < NumElements; ++I) {
3169     int Index = VSN->getMaskElt(I);
3170     if (Index >= 0)
3171       for (unsigned J = 0; J < BytesPerElement; ++J)
3172         Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3173   }
3174 }
3175
3176 // Bytes is a VPERM-like permute vector, except that -1 is used for
3177 // undefined bytes.  See whether bytes [Start, Start + BytesPerElement) of
3178 // the result come from a contiguous sequence of bytes from one input.
3179 // Set Base to the selector for the first byte if so.
3180 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3181                             unsigned BytesPerElement, int &Base) {
3182   Base = -1;
3183   for (unsigned I = 0; I < BytesPerElement; ++I) {
3184     if (Bytes[Start + I] >= 0) {
3185       unsigned Elem = Bytes[Start + I];
3186       if (Base < 0) {
3187         Base = Elem - I;
3188         // Make sure the bytes would come from one input operand.
3189         if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3190           return false;
3191       } else if (unsigned(Base) != Elem - I)
3192         return false;
3193     }
3194   }
3195   return true;
3196 }
3197
3198 // Bytes is a VPERM-like permute vector, except that -1 is used for
3199 // undefined bytes.  Return true if it can be performed using VSLDI.
3200 // When returning true, set StartIndex to the shift amount and OpNo0
3201 // and OpNo1 to the VPERM operands that should be used as the first
3202 // and second shift operand respectively.
3203 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3204                                unsigned &StartIndex, unsigned &OpNo0,
3205                                unsigned &OpNo1) {
3206   int OpNos[] = { -1, -1 };
3207   int Shift = -1;
3208   for (unsigned I = 0; I < 16; ++I) {
3209     int Index = Bytes[I];
3210     if (Index >= 0) {
3211       int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3212       int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3213       int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3214       if (Shift < 0)
3215         Shift = ExpectedShift;
3216       else if (Shift != ExpectedShift)
3217         return false;
3218       // Make sure that the operand mappings are consistent with previous
3219       // elements.
3220       if (OpNos[ModelOpNo] == 1 - RealOpNo)
3221         return false;
3222       OpNos[ModelOpNo] = RealOpNo;
3223     }
3224   }
3225   StartIndex = Shift;
3226   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3227 }
3228
3229 // Create a node that performs P on operands Op0 and Op1, casting the
3230 // operands to the appropriate type.  The type of the result is determined by P.
3231 static SDValue getPermuteNode(SelectionDAG &DAG, SDLoc DL,
3232                               const Permute &P, SDValue Op0, SDValue Op1) {
3233   // VPDI (PERMUTE_DWORDS) always operates on v2i64s.  The input
3234   // elements of a PACK are twice as wide as the outputs.
3235   unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3236                       P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3237                       P.Operand);
3238   // Cast both operands to the appropriate type.
3239   MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3240                               SystemZ::VectorBytes / InBytes);
3241   Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3242   Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3243   SDValue Op;
3244   if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3245     SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3246     Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3247   } else if (P.Opcode == SystemZISD::PACK) {
3248     MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3249                                  SystemZ::VectorBytes / P.Operand);
3250     Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3251   } else {
3252     Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3253   }
3254   return Op;
3255 }
3256
3257 // Bytes is a VPERM-like permute vector, except that -1 is used for
3258 // undefined bytes.  Implement it on operands Ops[0] and Ops[1] using
3259 // VSLDI or VPERM.
3260 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, SDLoc DL, SDValue *Ops,
3261                                      const SmallVectorImpl<int> &Bytes) {
3262   for (unsigned I = 0; I < 2; ++I)
3263     Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3264
3265   // First see whether VSLDI can be used.
3266   unsigned StartIndex, OpNo0, OpNo1;
3267   if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3268     return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3269                        Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3270
3271   // Fall back on VPERM.  Construct an SDNode for the permute vector.
3272   SDValue IndexNodes[SystemZ::VectorBytes];
3273   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3274     if (Bytes[I] >= 0)
3275       IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3276     else
3277       IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3278   SDValue Op2 = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, IndexNodes);
3279   return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3280 }
3281
3282 namespace {
3283 // Describes a general N-operand vector shuffle.
3284 struct GeneralShuffle {
3285   GeneralShuffle(EVT vt) : VT(vt) {}
3286   void addUndef();
3287   void add(SDValue, unsigned);
3288   SDValue getNode(SelectionDAG &, SDLoc);
3289
3290   // The operands of the shuffle.
3291   SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3292
3293   // Index I is -1 if byte I of the result is undefined.  Otherwise the
3294   // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3295   // Bytes[I] / SystemZ::VectorBytes.
3296   SmallVector<int, SystemZ::VectorBytes> Bytes;
3297
3298   // The type of the shuffle result.
3299   EVT VT;
3300 };
3301 }
3302
3303 // Add an extra undefined element to the shuffle.
3304 void GeneralShuffle::addUndef() {
3305   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3306   for (unsigned I = 0; I < BytesPerElement; ++I)
3307     Bytes.push_back(-1);
3308 }
3309
3310 // Add an extra element to the shuffle, taking it from element Elem of Op.
3311 // A null Op indicates a vector input whose value will be calculated later;
3312 // there is at most one such input per shuffle and it always has the same
3313 // type as the result.
3314 void GeneralShuffle::add(SDValue Op, unsigned Elem) {
3315   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3316
3317   // The source vector can have wider elements than the result,
3318   // either through an explicit TRUNCATE or because of type legalization.
3319   // We want the least significant part.
3320   EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3321   unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3322   assert(FromBytesPerElement >= BytesPerElement &&
3323          "Invalid EXTRACT_VECTOR_ELT");
3324   unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3325                    (FromBytesPerElement - BytesPerElement));
3326
3327   // Look through things like shuffles and bitcasts.
3328   while (Op.getNode()) {
3329     if (Op.getOpcode() == ISD::BITCAST)
3330       Op = Op.getOperand(0);
3331     else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3332       // See whether the bytes we need come from a contiguous part of one
3333       // operand.
3334       SmallVector<int, SystemZ::VectorBytes> OpBytes;
3335       getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3336       int NewByte;
3337       if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3338         break;
3339       if (NewByte < 0) {
3340         addUndef();
3341         return;
3342       }
3343       Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3344       Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3345     } else if (Op.getOpcode() == ISD::UNDEF) {
3346       addUndef();
3347       return;
3348     } else
3349       break;
3350   }
3351
3352   // Make sure that the source of the extraction is in Ops.
3353   unsigned OpNo = 0;
3354   for (; OpNo < Ops.size(); ++OpNo)
3355     if (Ops[OpNo] == Op)
3356       break;
3357   if (OpNo == Ops.size())
3358     Ops.push_back(Op);
3359
3360   // Add the element to Bytes.
3361   unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3362   for (unsigned I = 0; I < BytesPerElement; ++I)
3363     Bytes.push_back(Base + I);
3364 }
3365
3366 // Return SDNodes for the completed shuffle.
3367 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, SDLoc DL) {
3368   assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3369
3370   if (Ops.size() == 0)
3371     return DAG.getUNDEF(VT);
3372
3373   // Make sure that there are at least two shuffle operands.
3374   if (Ops.size() == 1)
3375     Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3376
3377   // Create a tree of shuffles, deferring root node until after the loop.
3378   // Try to redistribute the undefined elements of non-root nodes so that
3379   // the non-root shuffles match something like a pack or merge, then adjust
3380   // the parent node's permute vector to compensate for the new order.
3381   // Among other things, this copes with vectors like <2 x i16> that were
3382   // padded with undefined elements during type legalization.
3383   //
3384   // In the best case this redistribution will lead to the whole tree
3385   // using packs and merges.  It should rarely be a loss in other cases.
3386   unsigned Stride = 1;
3387   for (; Stride * 2 < Ops.size(); Stride *= 2) {
3388     for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3389       SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3390
3391       // Create a mask for just these two operands.
3392       SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3393       for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3394         unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3395         unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3396         if (OpNo == I)
3397           NewBytes[J] = Byte;
3398         else if (OpNo == I + Stride)
3399           NewBytes[J] = SystemZ::VectorBytes + Byte;
3400         else
3401           NewBytes[J] = -1;
3402       }
3403       // See if it would be better to reorganize NewMask to avoid using VPERM.
3404       SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3405       if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3406         Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3407         // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3408         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3409           if (NewBytes[J] >= 0) {
3410             assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3411                    "Invalid double permute");
3412             Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3413           } else
3414             assert(NewBytesMap[J] < 0 && "Invalid double permute");
3415         }
3416       } else {
3417         // Just use NewBytes on the operands.
3418         Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3419         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3420           if (NewBytes[J] >= 0)
3421             Bytes[J] = I * SystemZ::VectorBytes + J;
3422       }
3423     }
3424   }
3425
3426   // Now we just have 2 inputs.  Put the second operand in Ops[1].
3427   if (Stride > 1) {
3428     Ops[1] = Ops[Stride];
3429     for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3430       if (Bytes[I] >= int(SystemZ::VectorBytes))
3431         Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3432   }
3433
3434   // Look for an instruction that can do the permute without resorting
3435   // to VPERM.
3436   unsigned OpNo0, OpNo1;
3437   SDValue Op;
3438   if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3439     Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3440   else
3441     Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3442   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3443 }
3444
3445 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3446 static bool isScalarToVector(SDValue Op) {
3447   for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3448     if (Op.getOperand(I).getOpcode() != ISD::UNDEF)
3449       return false;
3450   return true;
3451 }
3452
3453 // Return a vector of type VT that contains Value in the first element.
3454 // The other elements don't matter.
3455 static SDValue buildScalarToVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3456                                    SDValue Value) {
3457   // If we have a constant, replicate it to all elements and let the
3458   // BUILD_VECTOR lowering take care of it.
3459   if (Value.getOpcode() == ISD::Constant ||
3460       Value.getOpcode() == ISD::ConstantFP) {
3461     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3462     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
3463   }
3464   if (Value.getOpcode() == ISD::UNDEF)
3465     return DAG.getUNDEF(VT);
3466   return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3467 }
3468
3469 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3470 // element 1.  Used for cases in which replication is cheap.
3471 static SDValue buildMergeScalars(SelectionDAG &DAG, SDLoc DL, EVT VT,
3472                                  SDValue Op0, SDValue Op1) {
3473   if (Op0.getOpcode() == ISD::UNDEF) {
3474     if (Op1.getOpcode() == ISD::UNDEF)
3475       return DAG.getUNDEF(VT);
3476     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
3477   }
3478   if (Op1.getOpcode() == ISD::UNDEF)
3479     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
3480   return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
3481                      buildScalarToVector(DAG, DL, VT, Op0),
3482                      buildScalarToVector(DAG, DL, VT, Op1));
3483 }
3484
3485 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
3486 // vector for them.
3487 static SDValue joinDwords(SelectionDAG &DAG, SDLoc DL, SDValue Op0,
3488                           SDValue Op1) {
3489   if (Op0.getOpcode() == ISD::UNDEF && Op1.getOpcode() == ISD::UNDEF)
3490     return DAG.getUNDEF(MVT::v2i64);
3491   // If one of the two inputs is undefined then replicate the other one,
3492   // in order to avoid using another register unnecessarily.
3493   if (Op0.getOpcode() == ISD::UNDEF)
3494     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3495   else if (Op1.getOpcode() == ISD::UNDEF)
3496     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3497   else {
3498     Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3499     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3500   }
3501   return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
3502 }
3503
3504 // Try to represent constant BUILD_VECTOR node BVN using a
3505 // SystemZISD::BYTE_MASK-style mask.  Store the mask value in Mask
3506 // on success.
3507 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
3508   EVT ElemVT = BVN->getValueType(0).getVectorElementType();
3509   unsigned BytesPerElement = ElemVT.getStoreSize();
3510   for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
3511     SDValue Op = BVN->getOperand(I);
3512     if (Op.getOpcode() != ISD::UNDEF) {
3513       uint64_t Value;
3514       if (Op.getOpcode() == ISD::Constant)
3515         Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
3516       else if (Op.getOpcode() == ISD::ConstantFP)
3517         Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
3518                  .getZExtValue());
3519       else
3520         return false;
3521       for (unsigned J = 0; J < BytesPerElement; ++J) {
3522         uint64_t Byte = (Value >> (J * 8)) & 0xff;
3523         if (Byte == 0xff)
3524           Mask |= 1 << ((E - I - 1) * BytesPerElement + J);
3525         else if (Byte != 0)
3526           return false;
3527       }
3528     }
3529   }
3530   return true;
3531 }
3532
3533 // Try to load a vector constant in which BitsPerElement-bit value Value
3534 // is replicated to fill the vector.  VT is the type of the resulting
3535 // constant, which may have elements of a different size from BitsPerElement.
3536 // Return the SDValue of the constant on success, otherwise return
3537 // an empty value.
3538 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
3539                                        const SystemZInstrInfo *TII,
3540                                        SDLoc DL, EVT VT, uint64_t Value,
3541                                        unsigned BitsPerElement) {
3542   // Signed 16-bit values can be replicated using VREPI.
3543   int64_t SignedValue = SignExtend64(Value, BitsPerElement);
3544   if (isInt<16>(SignedValue)) {
3545     MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3546                                  SystemZ::VectorBits / BitsPerElement);
3547     SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
3548                              DAG.getConstant(SignedValue, DL, MVT::i32));
3549     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3550   }
3551   // See whether rotating the constant left some N places gives a value that
3552   // is one less than a power of 2 (i.e. all zeros followed by all ones).
3553   // If so we can use VGM.
3554   unsigned Start, End;
3555   if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
3556     // isRxSBGMask returns the bit numbers for a full 64-bit value,
3557     // with 0 denoting 1 << 63 and 63 denoting 1.  Convert them to
3558     // bit numbers for an BitsPerElement value, so that 0 denotes
3559     // 1 << (BitsPerElement-1).
3560     Start -= 64 - BitsPerElement;
3561     End -= 64 - BitsPerElement;
3562     MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3563                                  SystemZ::VectorBits / BitsPerElement);
3564     SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
3565                              DAG.getConstant(Start, DL, MVT::i32),
3566                              DAG.getConstant(End, DL, MVT::i32));
3567     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3568   }
3569   return SDValue();
3570 }
3571
3572 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
3573 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
3574 // the non-EXTRACT_VECTOR_ELT elements.  See if the given BUILD_VECTOR
3575 // would benefit from this representation and return it if so.
3576 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
3577                                      BuildVectorSDNode *BVN) {
3578   EVT VT = BVN->getValueType(0);
3579   unsigned NumElements = VT.getVectorNumElements();
3580
3581   // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
3582   // on byte vectors.  If there are non-EXTRACT_VECTOR_ELT elements that still
3583   // need a BUILD_VECTOR, add an additional placeholder operand for that
3584   // BUILD_VECTOR and store its operands in ResidueOps.
3585   GeneralShuffle GS(VT);
3586   SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
3587   bool FoundOne = false;
3588   for (unsigned I = 0; I < NumElements; ++I) {
3589     SDValue Op = BVN->getOperand(I);
3590     if (Op.getOpcode() == ISD::TRUNCATE)
3591       Op = Op.getOperand(0);
3592     if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3593         Op.getOperand(1).getOpcode() == ISD::Constant) {
3594       unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3595       GS.add(Op.getOperand(0), Elem);
3596       FoundOne = true;
3597     } else if (Op.getOpcode() == ISD::UNDEF) {
3598       GS.addUndef();
3599     } else {
3600       GS.add(SDValue(), ResidueOps.size());
3601       ResidueOps.push_back(Op);
3602     }
3603   }
3604
3605   // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
3606   if (!FoundOne)
3607     return SDValue();
3608
3609   // Create the BUILD_VECTOR for the remaining elements, if any.
3610   if (!ResidueOps.empty()) {
3611     while (ResidueOps.size() < NumElements)
3612       ResidueOps.push_back(DAG.getUNDEF(VT.getVectorElementType()));
3613     for (auto &Op : GS.Ops) {
3614       if (!Op.getNode()) {
3615         Op = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BVN), VT, ResidueOps);
3616         break;
3617       }
3618     }
3619   }
3620   return GS.getNode(DAG, SDLoc(BVN));
3621 }
3622
3623 // Combine GPR scalar values Elems into a vector of type VT.
3624 static SDValue buildVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3625                            SmallVectorImpl<SDValue> &Elems) {
3626   // See whether there is a single replicated value.
3627   SDValue Single;
3628   unsigned int NumElements = Elems.size();
3629   unsigned int Count = 0;
3630   for (auto Elem : Elems) {
3631     if (Elem.getOpcode() != ISD::UNDEF) {
3632       if (!Single.getNode())
3633         Single = Elem;
3634       else if (Elem != Single) {
3635         Single = SDValue();
3636         break;
3637       }
3638       Count += 1;
3639     }
3640   }
3641   // There are three cases here:
3642   //
3643   // - if the only defined element is a loaded one, the best sequence
3644   //   is a replicating load.
3645   //
3646   // - otherwise, if the only defined element is an i64 value, we will
3647   //   end up with the same VLVGP sequence regardless of whether we short-cut
3648   //   for replication or fall through to the later code.
3649   //
3650   // - otherwise, if the only defined element is an i32 or smaller value,
3651   //   we would need 2 instructions to replicate it: VLVGP followed by VREPx.
3652   //   This is only a win if the single defined element is used more than once.
3653   //   In other cases we're better off using a single VLVGx.
3654   if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
3655     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
3656
3657   // The best way of building a v2i64 from two i64s is to use VLVGP.
3658   if (VT == MVT::v2i64)
3659     return joinDwords(DAG, DL, Elems[0], Elems[1]);
3660
3661   // Use a 64-bit merge high to combine two doubles.
3662   if (VT == MVT::v2f64)
3663     return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3664
3665   // Build v4f32 values directly from the FPRs:
3666   //
3667   //   <Axxx> <Bxxx> <Cxxxx> <Dxxx>
3668   //         V              V         VMRHF
3669   //      <ABxx>         <CDxx>
3670   //                V                 VMRHG
3671   //              <ABCD>
3672   if (VT == MVT::v4f32) {
3673     SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3674     SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
3675     // Avoid unnecessary undefs by reusing the other operand.
3676     if (Op01.getOpcode() == ISD::UNDEF)
3677       Op01 = Op23;
3678     else if (Op23.getOpcode() == ISD::UNDEF)
3679       Op23 = Op01;
3680     // Merging identical replications is a no-op.
3681     if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
3682       return Op01;
3683     Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
3684     Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
3685     SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
3686                              DL, MVT::v2i64, Op01, Op23);
3687     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3688   }
3689
3690   // Collect the constant terms.
3691   SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
3692   SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
3693
3694   unsigned NumConstants = 0;
3695   for (unsigned I = 0; I < NumElements; ++I) {
3696     SDValue Elem = Elems[I];
3697     if (Elem.getOpcode() == ISD::Constant ||
3698         Elem.getOpcode() == ISD::ConstantFP) {
3699       NumConstants += 1;
3700       Constants[I] = Elem;
3701       Done[I] = true;
3702     }
3703   }
3704   // If there was at least one constant, fill in the other elements of
3705   // Constants with undefs to get a full vector constant and use that
3706   // as the starting point.
3707   SDValue Result;
3708   if (NumConstants > 0) {
3709     for (unsigned I = 0; I < NumElements; ++I)
3710       if (!Constants[I].getNode())
3711         Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
3712     Result = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Constants);
3713   } else {
3714     // Otherwise try to use VLVGP to start the sequence in order to
3715     // avoid a false dependency on any previous contents of the vector
3716     // register.  This only makes sense if one of the associated elements
3717     // is defined.
3718     unsigned I1 = NumElements / 2 - 1;
3719     unsigned I2 = NumElements - 1;
3720     bool Def1 = (Elems[I1].getOpcode() != ISD::UNDEF);
3721     bool Def2 = (Elems[I2].getOpcode() != ISD::UNDEF);
3722     if (Def1 || Def2) {
3723       SDValue Elem1 = Elems[Def1 ? I1 : I2];
3724       SDValue Elem2 = Elems[Def2 ? I2 : I1];
3725       Result = DAG.getNode(ISD::BITCAST, DL, VT,
3726                            joinDwords(DAG, DL, Elem1, Elem2));
3727       Done[I1] = true;
3728       Done[I2] = true;
3729     } else
3730       Result = DAG.getUNDEF(VT);
3731   }
3732
3733   // Use VLVGx to insert the other elements.
3734   for (unsigned I = 0; I < NumElements; ++I)
3735     if (!Done[I] && Elems[I].getOpcode() != ISD::UNDEF)
3736       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
3737                            DAG.getConstant(I, DL, MVT::i32));
3738   return Result;
3739 }
3740
3741 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
3742                                                  SelectionDAG &DAG) const {
3743   const SystemZInstrInfo *TII =
3744     static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3745   auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
3746   SDLoc DL(Op);
3747   EVT VT = Op.getValueType();
3748
3749   if (BVN->isConstant()) {
3750     // Try using VECTOR GENERATE BYTE MASK.  This is the architecturally-
3751     // preferred way of creating all-zero and all-one vectors so give it
3752     // priority over other methods below.
3753     uint64_t Mask = 0;
3754     if (tryBuildVectorByteMask(BVN, Mask)) {
3755       SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3756                                DAG.getConstant(Mask, DL, MVT::i32));
3757       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3758     }
3759
3760     // Try using some form of replication.
3761     APInt SplatBits, SplatUndef;
3762     unsigned SplatBitSize;
3763     bool HasAnyUndefs;
3764     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
3765                              8, true) &&
3766         SplatBitSize <= 64) {
3767       // First try assuming that any undefined bits above the highest set bit
3768       // and below the lowest set bit are 1s.  This increases the likelihood of
3769       // being able to use a sign-extended element value in VECTOR REPLICATE
3770       // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
3771       uint64_t SplatBitsZ = SplatBits.getZExtValue();
3772       uint64_t SplatUndefZ = SplatUndef.getZExtValue();
3773       uint64_t Lower = (SplatUndefZ
3774                         & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
3775       uint64_t Upper = (SplatUndefZ
3776                         & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
3777       uint64_t Value = SplatBitsZ | Upper | Lower;
3778       SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
3779                                            SplatBitSize);
3780       if (Op.getNode())
3781         return Op;
3782
3783       // Now try assuming that any undefined bits between the first and
3784       // last defined set bits are set.  This increases the chances of
3785       // using a non-wraparound mask.
3786       uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
3787       Value = SplatBitsZ | Middle;
3788       Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
3789       if (Op.getNode())
3790         return Op;
3791     }
3792
3793     // Fall back to loading it from memory.
3794     return SDValue();
3795   }
3796
3797   // See if we should use shuffles to construct the vector from other vectors.
3798   SDValue Res = tryBuildVectorShuffle(DAG, BVN);
3799   if (Res.getNode())
3800     return Res;
3801
3802   // Detect SCALAR_TO_VECTOR conversions.
3803   if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
3804     return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
3805
3806   // Otherwise use buildVector to build the vector up from GPRs.
3807   unsigned NumElements = Op.getNumOperands();
3808   SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
3809   for (unsigned I = 0; I < NumElements; ++I)
3810     Ops[I] = Op.getOperand(I);
3811   return buildVector(DAG, DL, VT, Ops);
3812 }
3813
3814 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
3815                                                    SelectionDAG &DAG) const {
3816   auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
3817   SDLoc DL(Op);
3818   EVT VT = Op.getValueType();
3819   unsigned NumElements = VT.getVectorNumElements();
3820
3821   if (VSN->isSplat()) {
3822     SDValue Op0 = Op.getOperand(0);
3823     unsigned Index = VSN->getSplatIndex();
3824     assert(Index < VT.getVectorNumElements() &&
3825            "Splat index should be defined and in first operand");
3826     // See whether the value we're splatting is directly available as a scalar.
3827     if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
3828         Op0.getOpcode() == ISD::BUILD_VECTOR)
3829       return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
3830     // Otherwise keep it as a vector-to-vector operation.
3831     return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
3832                        DAG.getConstant(Index, DL, MVT::i32));
3833   }
3834
3835   GeneralShuffle GS(VT);
3836   for (unsigned I = 0; I < NumElements; ++I) {
3837     int Elt = VSN->getMaskElt(I);
3838     if (Elt < 0)
3839       GS.addUndef();
3840     else
3841       GS.add(Op.getOperand(unsigned(Elt) / NumElements),
3842              unsigned(Elt) % NumElements);
3843   }
3844   return GS.getNode(DAG, SDLoc(VSN));
3845 }
3846
3847 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
3848                                                      SelectionDAG &DAG) const {
3849   SDLoc DL(Op);
3850   // Just insert the scalar into element 0 of an undefined vector.
3851   return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
3852                      Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
3853                      Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
3854 }
3855
3856 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3857                                                       SelectionDAG &DAG) const {
3858   // Handle insertions of floating-point values.
3859   SDLoc DL(Op);
3860   SDValue Op0 = Op.getOperand(0);
3861   SDValue Op1 = Op.getOperand(1);
3862   SDValue Op2 = Op.getOperand(2);
3863   EVT VT = Op.getValueType();
3864
3865   // Insertions into constant indices of a v2f64 can be done using VPDI.
3866   // However, if the inserted value is a bitcast or a constant then it's
3867   // better to use GPRs, as below.
3868   if (VT == MVT::v2f64 &&
3869       Op1.getOpcode() != ISD::BITCAST &&
3870       Op1.getOpcode() != ISD::ConstantFP &&
3871       Op2.getOpcode() == ISD::Constant) {
3872     uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
3873     unsigned Mask = VT.getVectorNumElements() - 1;
3874     if (Index <= Mask)
3875       return Op;
3876   }
3877
3878   // Otherwise bitcast to the equivalent integer form and insert via a GPR.
3879   MVT IntVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
3880   MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
3881   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
3882                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
3883                             DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
3884   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
3885 }
3886
3887 SDValue
3888 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3889                                                SelectionDAG &DAG) const {
3890   // Handle extractions of floating-point values.
3891   SDLoc DL(Op);
3892   SDValue Op0 = Op.getOperand(0);
3893   SDValue Op1 = Op.getOperand(1);
3894   EVT VT = Op.getValueType();
3895   EVT VecVT = Op0.getValueType();
3896
3897   // Extractions of constant indices can be done directly.
3898   if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
3899     uint64_t Index = CIndexN->getZExtValue();
3900     unsigned Mask = VecVT.getVectorNumElements() - 1;
3901     if (Index <= Mask)
3902       return Op;
3903   }
3904
3905   // Otherwise bitcast to the equivalent integer form and extract via a GPR.
3906   MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
3907   MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
3908   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
3909                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
3910   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
3911 }
3912
3913 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
3914                                           unsigned ByScalar) const {
3915   // Look for cases where a vector shift can use the *_BY_SCALAR form.
3916   SDValue Op0 = Op.getOperand(0);
3917   SDValue Op1 = Op.getOperand(1);
3918   SDLoc DL(Op);
3919   EVT VT = Op.getValueType();
3920   unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
3921
3922   // See whether the shift vector is a splat represented as BUILD_VECTOR.
3923   if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
3924     APInt SplatBits, SplatUndef;
3925     unsigned SplatBitSize;
3926     bool HasAnyUndefs;
3927     // Check for constant splats.  Use ElemBitSize as the minimum element
3928     // width and reject splats that need wider elements.
3929     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
3930                              ElemBitSize, true) &&
3931         SplatBitSize == ElemBitSize) {
3932       SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
3933                                       DL, MVT::i32);
3934       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
3935     }
3936     // Check for variable splats.
3937     BitVector UndefElements;
3938     SDValue Splat = BVN->getSplatValue(&UndefElements);
3939     if (Splat) {
3940       // Since i32 is the smallest legal type, we either need a no-op
3941       // or a truncation.
3942       SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
3943       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
3944     }
3945   }
3946
3947   // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
3948   // and the shift amount is directly available in a GPR.
3949   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
3950     if (VSN->isSplat()) {
3951       SDValue VSNOp0 = VSN->getOperand(0);
3952       unsigned Index = VSN->getSplatIndex();
3953       assert(Index < VT.getVectorNumElements() &&
3954              "Splat index should be defined and in first operand");
3955       if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
3956           VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
3957         // Since i32 is the smallest legal type, we either need a no-op
3958         // or a truncation.
3959         SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
3960                                     VSNOp0.getOperand(Index));
3961         return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
3962       }
3963     }
3964   }
3965
3966   // Otherwise just treat the current form as legal.
3967   return Op;
3968 }
3969
3970 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
3971                                               SelectionDAG &DAG) const {
3972   switch (Op.getOpcode()) {
3973   case ISD::BR_CC:
3974     return lowerBR_CC(Op, DAG);
3975   case ISD::SELECT_CC:
3976     return lowerSELECT_CC(Op, DAG);
3977   case ISD::SETCC:
3978     return lowerSETCC(Op, DAG);
3979   case ISD::GlobalAddress:
3980     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
3981   case ISD::GlobalTLSAddress:
3982     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
3983   case ISD::BlockAddress:
3984     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
3985   case ISD::JumpTable:
3986     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
3987   case ISD::ConstantPool:
3988     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
3989   case ISD::BITCAST:
3990     return lowerBITCAST(Op, DAG);
3991   case ISD::VASTART:
3992     return lowerVASTART(Op, DAG);
3993   case ISD::VACOPY:
3994     return lowerVACOPY(Op, DAG);
3995   case ISD::DYNAMIC_STACKALLOC:
3996     return lowerDYNAMIC_STACKALLOC(Op, DAG);
3997   case ISD::SMUL_LOHI:
3998     return lowerSMUL_LOHI(Op, DAG);
3999   case ISD::UMUL_LOHI:
4000     return lowerUMUL_LOHI(Op, DAG);
4001   case ISD::SDIVREM:
4002     return lowerSDIVREM(Op, DAG);
4003   case ISD::UDIVREM:
4004     return lowerUDIVREM(Op, DAG);
4005   case ISD::OR:
4006     return lowerOR(Op, DAG);
4007   case ISD::CTPOP:
4008     return lowerCTPOP(Op, DAG);
4009   case ISD::CTLZ_ZERO_UNDEF:
4010     return DAG.getNode(ISD::CTLZ, SDLoc(Op),
4011                        Op.getValueType(), Op.getOperand(0));
4012   case ISD::CTTZ_ZERO_UNDEF:
4013     return DAG.getNode(ISD::CTTZ, SDLoc(Op),
4014                        Op.getValueType(), Op.getOperand(0));
4015   case ISD::ATOMIC_SWAP:
4016     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4017   case ISD::ATOMIC_STORE:
4018     return lowerATOMIC_STORE(Op, DAG);
4019   case ISD::ATOMIC_LOAD:
4020     return lowerATOMIC_LOAD(Op, DAG);
4021   case ISD::ATOMIC_LOAD_ADD:
4022     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4023   case ISD::ATOMIC_LOAD_SUB:
4024     return lowerATOMIC_LOAD_SUB(Op, DAG);
4025   case ISD::ATOMIC_LOAD_AND:
4026     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4027   case ISD::ATOMIC_LOAD_OR:
4028     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4029   case ISD::ATOMIC_LOAD_XOR:
4030     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4031   case ISD::ATOMIC_LOAD_NAND:
4032     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4033   case ISD::ATOMIC_LOAD_MIN:
4034     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4035   case ISD::ATOMIC_LOAD_MAX:
4036     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4037   case ISD::ATOMIC_LOAD_UMIN:
4038     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4039   case ISD::ATOMIC_LOAD_UMAX:
4040     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4041   case ISD::ATOMIC_CMP_SWAP:
4042     return lowerATOMIC_CMP_SWAP(Op, DAG);
4043   case ISD::STACKSAVE:
4044     return lowerSTACKSAVE(Op, DAG);
4045   case ISD::STACKRESTORE:
4046     return lowerSTACKRESTORE(Op, DAG);
4047   case ISD::PREFETCH:
4048     return lowerPREFETCH(Op, DAG);
4049   case ISD::INTRINSIC_W_CHAIN:
4050     return lowerINTRINSIC_W_CHAIN(Op, DAG);
4051   case ISD::BUILD_VECTOR:
4052     return lowerBUILD_VECTOR(Op, DAG);
4053   case ISD::VECTOR_SHUFFLE:
4054     return lowerVECTOR_SHUFFLE(Op, DAG);
4055   case ISD::SCALAR_TO_VECTOR:
4056     return lowerSCALAR_TO_VECTOR(Op, DAG);
4057   case ISD::INSERT_VECTOR_ELT:
4058     return lowerINSERT_VECTOR_ELT(Op, DAG);
4059   case ISD::EXTRACT_VECTOR_ELT:
4060     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4061   case ISD::SHL:
4062     return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4063   case ISD::SRL:
4064     return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4065   case ISD::SRA:
4066     return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4067   default:
4068     llvm_unreachable("Unexpected node to lower");
4069   }
4070 }
4071
4072 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4073 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4074   switch (Opcode) {
4075     OPCODE(RET_FLAG);
4076     OPCODE(CALL);
4077     OPCODE(SIBCALL);
4078     OPCODE(TLS_GDCALL);
4079     OPCODE(TLS_LDCALL);
4080     OPCODE(PCREL_WRAPPER);
4081     OPCODE(PCREL_OFFSET);
4082     OPCODE(IABS);
4083     OPCODE(ICMP);
4084     OPCODE(FCMP);
4085     OPCODE(TM);
4086     OPCODE(BR_CCMASK);
4087     OPCODE(SELECT_CCMASK);
4088     OPCODE(ADJDYNALLOC);
4089     OPCODE(EXTRACT_ACCESS);
4090     OPCODE(POPCNT);
4091     OPCODE(UMUL_LOHI64);
4092     OPCODE(SDIVREM32);
4093     OPCODE(SDIVREM64);
4094     OPCODE(UDIVREM32);
4095     OPCODE(UDIVREM64);
4096     OPCODE(MVC);
4097     OPCODE(MVC_LOOP);
4098     OPCODE(NC);
4099     OPCODE(NC_LOOP);
4100     OPCODE(OC);
4101     OPCODE(OC_LOOP);
4102     OPCODE(XC);
4103     OPCODE(XC_LOOP);
4104     OPCODE(CLC);
4105     OPCODE(CLC_LOOP);
4106     OPCODE(STPCPY);
4107     OPCODE(STRCMP);
4108     OPCODE(SEARCH_STRING);
4109     OPCODE(IPM);
4110     OPCODE(SERIALIZE);
4111     OPCODE(TBEGIN);
4112     OPCODE(TBEGIN_NOFLOAT);
4113     OPCODE(TEND);
4114     OPCODE(BYTE_MASK);
4115     OPCODE(ROTATE_MASK);
4116     OPCODE(REPLICATE);
4117     OPCODE(JOIN_DWORDS);
4118     OPCODE(SPLAT);
4119     OPCODE(MERGE_HIGH);
4120     OPCODE(MERGE_LOW);
4121     OPCODE(SHL_DOUBLE);
4122     OPCODE(PERMUTE_DWORDS);
4123     OPCODE(PERMUTE);
4124     OPCODE(PACK);
4125     OPCODE(VSHL_BY_SCALAR);
4126     OPCODE(VSRL_BY_SCALAR);
4127     OPCODE(VSRA_BY_SCALAR);
4128     OPCODE(VSUM);
4129     OPCODE(VICMPE);
4130     OPCODE(VICMPH);
4131     OPCODE(VICMPHL);
4132     OPCODE(VFCMPE);
4133     OPCODE(VFCMPH);
4134     OPCODE(VFCMPHE);
4135     OPCODE(VEXTEND);
4136     OPCODE(VROUND);
4137     OPCODE(ATOMIC_SWAPW);
4138     OPCODE(ATOMIC_LOADW_ADD);
4139     OPCODE(ATOMIC_LOADW_SUB);
4140     OPCODE(ATOMIC_LOADW_AND);
4141     OPCODE(ATOMIC_LOADW_OR);
4142     OPCODE(ATOMIC_LOADW_XOR);
4143     OPCODE(ATOMIC_LOADW_NAND);
4144     OPCODE(ATOMIC_LOADW_MIN);
4145     OPCODE(ATOMIC_LOADW_MAX);
4146     OPCODE(ATOMIC_LOADW_UMIN);
4147     OPCODE(ATOMIC_LOADW_UMAX);
4148     OPCODE(ATOMIC_CMP_SWAPW);
4149     OPCODE(PREFETCH);
4150   }
4151   return nullptr;
4152 #undef OPCODE
4153 }
4154
4155 // Return true if VT is a vector whose elements are a whole number of bytes
4156 // in width.
4157 static bool canTreatAsByteVector(EVT VT) {
4158   return VT.isVector() && VT.getVectorElementType().getSizeInBits() % 8 == 0;
4159 }
4160
4161 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4162 // producing a result of type ResVT.  Op is a possibly bitcast version
4163 // of the input vector and Index is the index (based on type VecVT) that
4164 // should be extracted.  Return the new extraction if a simplification
4165 // was possible or if Force is true.
4166 SDValue SystemZTargetLowering::combineExtract(SDLoc DL, EVT ResVT, EVT VecVT,
4167                                               SDValue Op, unsigned Index,
4168                                               DAGCombinerInfo &DCI,
4169                                               bool Force) const {
4170   SelectionDAG &DAG = DCI.DAG;
4171
4172   // The number of bytes being extracted.
4173   unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4174
4175   for (;;) {
4176     unsigned Opcode = Op.getOpcode();
4177     if (Opcode == ISD::BITCAST)
4178       // Look through bitcasts.
4179       Op = Op.getOperand(0);
4180     else if (Opcode == ISD::VECTOR_SHUFFLE &&
4181              canTreatAsByteVector(Op.getValueType())) {
4182       // Get a VPERM-like permute mask and see whether the bytes covered
4183       // by the extracted element are a contiguous sequence from one
4184       // source operand.
4185       SmallVector<int, SystemZ::VectorBytes> Bytes;
4186       getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4187       int First;
4188       if (!getShuffleInput(Bytes, Index * BytesPerElement,
4189                            BytesPerElement, First))
4190         break;
4191       if (First < 0)
4192         return DAG.getUNDEF(ResVT);
4193       // Make sure the contiguous sequence starts at a multiple of the
4194       // original element size.
4195       unsigned Byte = unsigned(First) % Bytes.size();
4196       if (Byte % BytesPerElement != 0)
4197         break;
4198       // We can get the extracted value directly from an input.
4199       Index = Byte / BytesPerElement;
4200       Op = Op.getOperand(unsigned(First) / Bytes.size());
4201       Force = true;
4202     } else if (Opcode == ISD::BUILD_VECTOR &&
4203                canTreatAsByteVector(Op.getValueType())) {
4204       // We can only optimize this case if the BUILD_VECTOR elements are
4205       // at least as wide as the extracted value.
4206       EVT OpVT = Op.getValueType();
4207       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4208       if (OpBytesPerElement < BytesPerElement)
4209         break;
4210       // Make sure that the least-significant bit of the extracted value
4211       // is the least significant bit of an input.
4212       unsigned End = (Index + 1) * BytesPerElement;
4213       if (End % OpBytesPerElement != 0)
4214         break;
4215       // We're extracting the low part of one operand of the BUILD_VECTOR.
4216       Op = Op.getOperand(End / OpBytesPerElement - 1);
4217       if (!Op.getValueType().isInteger()) {
4218         EVT VT = MVT::getIntegerVT(Op.getValueType().getSizeInBits());
4219         Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4220         DCI.AddToWorklist(Op.getNode());
4221       }
4222       EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4223       Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4224       if (VT != ResVT) {
4225         DCI.AddToWorklist(Op.getNode());
4226         Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4227       }
4228       return Op;
4229     } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4230                 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4231                 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4232                canTreatAsByteVector(Op.getValueType()) &&
4233                canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4234       // Make sure that only the unextended bits are significant.
4235       EVT ExtVT = Op.getValueType();
4236       EVT OpVT = Op.getOperand(0).getValueType();
4237       unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4238       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4239       unsigned Byte = Index * BytesPerElement;
4240       unsigned SubByte = Byte % ExtBytesPerElement;
4241       unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4242       if (SubByte < MinSubByte ||
4243           SubByte + BytesPerElement > ExtBytesPerElement)
4244         break;
4245       // Get the byte offset of the unextended element
4246       Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4247       // ...then add the byte offset relative to that element.
4248       Byte += SubByte - MinSubByte;
4249       if (Byte % BytesPerElement != 0)
4250         break;
4251       Op = Op.getOperand(0);
4252       Index = Byte / BytesPerElement;
4253       Force = true;
4254     } else
4255       break;
4256   }
4257   if (Force) {
4258     if (Op.getValueType() != VecVT) {
4259       Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4260       DCI.AddToWorklist(Op.getNode());
4261     }
4262     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4263                        DAG.getConstant(Index, DL, MVT::i32));
4264   }
4265   return SDValue();
4266 }
4267
4268 // Optimize vector operations in scalar value Op on the basis that Op
4269 // is truncated to TruncVT.
4270 SDValue
4271 SystemZTargetLowering::combineTruncateExtract(SDLoc DL, EVT TruncVT, SDValue Op,
4272                                               DAGCombinerInfo &DCI) const {
4273   // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4274   // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4275   // of type TruncVT.
4276   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4277       TruncVT.getSizeInBits() % 8 == 0) {
4278     SDValue Vec = Op.getOperand(0);
4279     EVT VecVT = Vec.getValueType();
4280     if (canTreatAsByteVector(VecVT)) {
4281       if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4282         unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4283         unsigned TruncBytes = TruncVT.getStoreSize();
4284         if (BytesPerElement % TruncBytes == 0) {
4285           // Calculate the value of Y' in the above description.  We are
4286           // splitting the original elements into Scale equal-sized pieces
4287           // and for truncation purposes want the last (least-significant)
4288           // of these pieces for IndexN.  This is easiest to do by calculating
4289           // the start index of the following element and then subtracting 1.
4290           unsigned Scale = BytesPerElement / TruncBytes;
4291           unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4292
4293           // Defer the creation of the bitcast from X to combineExtract,
4294           // which might be able to optimize the extraction.
4295           VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4296                                    VecVT.getStoreSize() / TruncBytes);
4297           EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4298           return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4299         }
4300       }
4301     }
4302   }
4303   return SDValue();
4304 }
4305
4306 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
4307                                                  DAGCombinerInfo &DCI) const {
4308   SelectionDAG &DAG = DCI.DAG;
4309   unsigned Opcode = N->getOpcode();
4310   if (Opcode == ISD::SIGN_EXTEND) {
4311     // Convert (sext (ashr (shl X, C1), C2)) to
4312     // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4313     // cheap as narrower ones.
4314     SDValue N0 = N->getOperand(0);
4315     EVT VT = N->getValueType(0);
4316     if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4317       auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4318       SDValue Inner = N0.getOperand(0);
4319       if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4320         if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4321           unsigned Extra = (VT.getSizeInBits() -
4322                             N0.getValueType().getSizeInBits());
4323           unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4324           unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4325           EVT ShiftVT = N0.getOperand(1).getValueType();
4326           SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4327                                     Inner.getOperand(0));
4328           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4329                                     DAG.getConstant(NewShlAmt, SDLoc(Inner),
4330                                                     ShiftVT));
4331           return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4332                              DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4333         }
4334       }
4335     }
4336   }
4337   // (z_merge_high 0, 0) -> 0.  This is mostly useful for using VLLEZF
4338   // for v4f32.
4339   if (Opcode == SystemZISD::MERGE_HIGH) {
4340     SDValue Op0 = N->getOperand(0);
4341     SDValue Op1 = N->getOperand(1);
4342     if (Op0 == Op1) {
4343       if (Op0.getOpcode() == ISD::BITCAST)
4344         Op0 = Op0.getOperand(0);
4345       if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4346           cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0)
4347         return Op1;
4348     }
4349   }
4350   // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4351   // for the extraction to be done on a vMiN value, so that we can use VSTE.
4352   // If X has wider elements then convert it to:
4353   // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4354   if (Opcode == ISD::STORE) {
4355     auto *SN = cast<StoreSDNode>(N);
4356     EVT MemVT = SN->getMemoryVT();
4357     if (MemVT.isInteger()) {
4358       SDValue Value = combineTruncateExtract(SDLoc(N), MemVT,
4359                                              SN->getValue(), DCI);
4360       if (Value.getNode()) {
4361         DCI.AddToWorklist(Value.getNode());
4362
4363         // Rewrite the store with the new form of stored value.
4364         return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4365                                  SN->getBasePtr(), SN->getMemoryVT(),
4366                                  SN->getMemOperand());
4367       }
4368     }
4369   }
4370   // Try to simplify a vector extraction.
4371   if (Opcode == ISD::EXTRACT_VECTOR_ELT) {
4372     if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
4373       SDValue Op0 = N->getOperand(0);
4374       EVT VecVT = Op0.getValueType();
4375       return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
4376                             IndexN->getZExtValue(), DCI, false);
4377     }
4378   }
4379   // (join_dwords X, X) == (replicate X)
4380   if (Opcode == SystemZISD::JOIN_DWORDS &&
4381       N->getOperand(0) == N->getOperand(1))
4382     return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
4383                        N->getOperand(0));
4384   // (fround (extract_vector_elt X 0))
4385   // (fround (extract_vector_elt X 1)) ->
4386   // (extract_vector_elt (VROUND X) 0)
4387   // (extract_vector_elt (VROUND X) 1)
4388   //
4389   // This is a special case since the target doesn't really support v2f32s.
4390   if (Opcode == ISD::FP_ROUND) {
4391     SDValue Op0 = N->getOperand(0);
4392     if (N->getValueType(0) == MVT::f32 &&
4393         Op0.hasOneUse() &&
4394         Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4395         Op0.getOperand(0).getValueType() == MVT::v2f64 &&
4396         Op0.getOperand(1).getOpcode() == ISD::Constant &&
4397         cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
4398       SDValue Vec = Op0.getOperand(0);
4399       for (auto *U : Vec->uses()) {
4400         if (U != Op0.getNode() &&
4401             U->hasOneUse() &&
4402             U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4403             U->getOperand(0) == Vec &&
4404             U->getOperand(1).getOpcode() == ISD::Constant &&
4405             cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
4406           SDValue OtherRound = SDValue(*U->use_begin(), 0);
4407           if (OtherRound.getOpcode() == ISD::FP_ROUND &&
4408               OtherRound.getOperand(0) == SDValue(U, 0) &&
4409               OtherRound.getValueType() == MVT::f32) {
4410             SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
4411                                          MVT::v4f32, Vec);
4412             DCI.AddToWorklist(VRound.getNode());
4413             SDValue Extract1 =
4414               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
4415                           VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
4416             DCI.AddToWorklist(Extract1.getNode());
4417             DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
4418             SDValue Extract0 =
4419               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
4420                           VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
4421             return Extract0;
4422           }
4423         }
4424       }
4425     }
4426   }
4427   return SDValue();
4428 }
4429
4430 //===----------------------------------------------------------------------===//
4431 // Custom insertion
4432 //===----------------------------------------------------------------------===//
4433
4434 // Create a new basic block after MBB.
4435 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
4436   MachineFunction &MF = *MBB->getParent();
4437   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
4438   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
4439   return NewMBB;
4440 }
4441
4442 // Split MBB after MI and return the new block (the one that contains
4443 // instructions after MI).
4444 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
4445                                           MachineBasicBlock *MBB) {
4446   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4447   NewMBB->splice(NewMBB->begin(), MBB,
4448                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
4449   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4450   return NewMBB;
4451 }
4452
4453 // Split MBB before MI and return the new block (the one that contains MI).
4454 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
4455                                            MachineBasicBlock *MBB) {
4456   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4457   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
4458   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4459   return NewMBB;
4460 }
4461
4462 // Force base value Base into a register before MI.  Return the register.
4463 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
4464                          const SystemZInstrInfo *TII) {
4465   if (Base.isReg())
4466     return Base.getReg();
4467
4468   MachineBasicBlock *MBB = MI->getParent();
4469   MachineFunction &MF = *MBB->getParent();
4470   MachineRegisterInfo &MRI = MF.getRegInfo();
4471
4472   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
4473   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
4474     .addOperand(Base).addImm(0).addReg(0);
4475   return Reg;
4476 }
4477
4478 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
4479 MachineBasicBlock *
4480 SystemZTargetLowering::emitSelect(MachineInstr *MI,
4481                                   MachineBasicBlock *MBB) const {
4482   const SystemZInstrInfo *TII =
4483       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4484
4485   unsigned DestReg  = MI->getOperand(0).getReg();
4486   unsigned TrueReg  = MI->getOperand(1).getReg();
4487   unsigned FalseReg = MI->getOperand(2).getReg();
4488   unsigned CCValid  = MI->getOperand(3).getImm();
4489   unsigned CCMask   = MI->getOperand(4).getImm();
4490   DebugLoc DL       = MI->getDebugLoc();
4491
4492   MachineBasicBlock *StartMBB = MBB;
4493   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
4494   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4495
4496   //  StartMBB:
4497   //   BRC CCMask, JoinMBB
4498   //   # fallthrough to FalseMBB
4499   MBB = StartMBB;
4500   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4501     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4502   MBB->addSuccessor(JoinMBB);
4503   MBB->addSuccessor(FalseMBB);
4504
4505   //  FalseMBB:
4506   //   # fallthrough to JoinMBB
4507   MBB = FalseMBB;
4508   MBB->addSuccessor(JoinMBB);
4509
4510   //  JoinMBB:
4511   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
4512   //  ...
4513   MBB = JoinMBB;
4514   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
4515     .addReg(TrueReg).addMBB(StartMBB)
4516     .addReg(FalseReg).addMBB(FalseMBB);
4517
4518   MI->eraseFromParent();
4519   return JoinMBB;
4520 }
4521
4522 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
4523 // StoreOpcode is the store to use and Invert says whether the store should
4524 // happen when the condition is false rather than true.  If a STORE ON
4525 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
4526 MachineBasicBlock *
4527 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
4528                                      MachineBasicBlock *MBB,
4529                                      unsigned StoreOpcode, unsigned STOCOpcode,
4530                                      bool Invert) const {
4531   const SystemZInstrInfo *TII =
4532       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4533
4534   unsigned SrcReg     = MI->getOperand(0).getReg();
4535   MachineOperand Base = MI->getOperand(1);
4536   int64_t Disp        = MI->getOperand(2).getImm();
4537   unsigned IndexReg   = MI->getOperand(3).getReg();
4538   unsigned CCValid    = MI->getOperand(4).getImm();
4539   unsigned CCMask     = MI->getOperand(5).getImm();
4540   DebugLoc DL         = MI->getDebugLoc();
4541
4542   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
4543
4544   // Use STOCOpcode if possible.  We could use different store patterns in
4545   // order to avoid matching the index register, but the performance trade-offs
4546   // might be more complicated in that case.
4547   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
4548     if (Invert)
4549       CCMask ^= CCValid;
4550     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
4551       .addReg(SrcReg).addOperand(Base).addImm(Disp)
4552       .addImm(CCValid).addImm(CCMask);
4553     MI->eraseFromParent();
4554     return MBB;
4555   }
4556
4557   // Get the condition needed to branch around the store.
4558   if (!Invert)
4559     CCMask ^= CCValid;
4560
4561   MachineBasicBlock *StartMBB = MBB;
4562   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
4563   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4564
4565   //  StartMBB:
4566   //   BRC CCMask, JoinMBB
4567   //   # fallthrough to FalseMBB
4568   MBB = StartMBB;
4569   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4570     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4571   MBB->addSuccessor(JoinMBB);
4572   MBB->addSuccessor(FalseMBB);
4573
4574   //  FalseMBB:
4575   //   store %SrcReg, %Disp(%Index,%Base)
4576   //   # fallthrough to JoinMBB
4577   MBB = FalseMBB;
4578   BuildMI(MBB, DL, TII->get(StoreOpcode))
4579     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
4580   MBB->addSuccessor(JoinMBB);
4581
4582   MI->eraseFromParent();
4583   return JoinMBB;
4584 }
4585
4586 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
4587 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
4588 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
4589 // BitSize is the width of the field in bits, or 0 if this is a partword
4590 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
4591 // is one of the operands.  Invert says whether the field should be
4592 // inverted after performing BinOpcode (e.g. for NAND).
4593 MachineBasicBlock *
4594 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
4595                                             MachineBasicBlock *MBB,
4596                                             unsigned BinOpcode,
4597                                             unsigned BitSize,
4598                                             bool Invert) const {
4599   MachineFunction &MF = *MBB->getParent();
4600   const SystemZInstrInfo *TII =
4601       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4602   MachineRegisterInfo &MRI = MF.getRegInfo();
4603   bool IsSubWord = (BitSize < 32);
4604
4605   // Extract the operands.  Base can be a register or a frame index.
4606   // Src2 can be a register or immediate.
4607   unsigned Dest        = MI->getOperand(0).getReg();
4608   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
4609   int64_t Disp         = MI->getOperand(2).getImm();
4610   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
4611   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4612   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4613   DebugLoc DL          = MI->getDebugLoc();
4614   if (IsSubWord)
4615     BitSize = MI->getOperand(6).getImm();
4616
4617   // Subword operations use 32-bit registers.
4618   const TargetRegisterClass *RC = (BitSize <= 32 ?
4619                                    &SystemZ::GR32BitRegClass :
4620                                    &SystemZ::GR64BitRegClass);
4621   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
4622   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4623
4624   // Get the right opcodes for the displacement.
4625   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
4626   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4627   assert(LOpcode && CSOpcode && "Displacement out of range");
4628
4629   // Create virtual registers for temporary results.
4630   unsigned OrigVal       = MRI.createVirtualRegister(RC);
4631   unsigned OldVal        = MRI.createVirtualRegister(RC);
4632   unsigned NewVal        = (BinOpcode || IsSubWord ?
4633                             MRI.createVirtualRegister(RC) : Src2.getReg());
4634   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4635   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4636
4637   // Insert a basic block for the main loop.
4638   MachineBasicBlock *StartMBB = MBB;
4639   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
4640   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
4641
4642   //  StartMBB:
4643   //   ...
4644   //   %OrigVal = L Disp(%Base)
4645   //   # fall through to LoopMMB
4646   MBB = StartMBB;
4647   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
4648     .addOperand(Base).addImm(Disp).addReg(0);
4649   MBB->addSuccessor(LoopMBB);
4650
4651   //  LoopMBB:
4652   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
4653   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
4654   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
4655   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
4656   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
4657   //   JNE LoopMBB
4658   //   # fall through to DoneMMB
4659   MBB = LoopMBB;
4660   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4661     .addReg(OrigVal).addMBB(StartMBB)
4662     .addReg(Dest).addMBB(LoopMBB);
4663   if (IsSubWord)
4664     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
4665       .addReg(OldVal).addReg(BitShift).addImm(0);
4666   if (Invert) {
4667     // Perform the operation normally and then invert every bit of the field.
4668     unsigned Tmp = MRI.createVirtualRegister(RC);
4669     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
4670       .addReg(RotatedOldVal).addOperand(Src2);
4671     if (BitSize <= 32)
4672       // XILF with the upper BitSize bits set.
4673       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
4674         .addReg(Tmp).addImm(-1U << (32 - BitSize));
4675     else {
4676       // Use LCGR and add -1 to the result, which is more compact than
4677       // an XILF, XILH pair.
4678       unsigned Tmp2 = MRI.createVirtualRegister(RC);
4679       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
4680       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
4681         .addReg(Tmp2).addImm(-1);
4682     }
4683   } else if (BinOpcode)
4684     // A simply binary operation.
4685     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
4686       .addReg(RotatedOldVal).addOperand(Src2);
4687   else if (IsSubWord)
4688     // Use RISBG to rotate Src2 into position and use it to replace the
4689     // field in RotatedOldVal.
4690     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
4691       .addReg(RotatedOldVal).addReg(Src2.getReg())
4692       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
4693   if (IsSubWord)
4694     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
4695       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
4696   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
4697     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
4698   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4699     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4700   MBB->addSuccessor(LoopMBB);
4701   MBB->addSuccessor(DoneMBB);
4702
4703   MI->eraseFromParent();
4704   return DoneMBB;
4705 }
4706
4707 // Implement EmitInstrWithCustomInserter for pseudo
4708 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
4709 // instruction that should be used to compare the current field with the
4710 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
4711 // for when the current field should be kept.  BitSize is the width of
4712 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
4713 MachineBasicBlock *
4714 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
4715                                             MachineBasicBlock *MBB,
4716                                             unsigned CompareOpcode,
4717                                             unsigned KeepOldMask,
4718                                             unsigned BitSize) const {
4719   MachineFunction &MF = *MBB->getParent();
4720   const SystemZInstrInfo *TII =
4721       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4722   MachineRegisterInfo &MRI = MF.getRegInfo();
4723   bool IsSubWord = (BitSize < 32);
4724
4725   // Extract the operands.  Base can be a register or a frame index.
4726   unsigned Dest        = MI->getOperand(0).getReg();
4727   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
4728   int64_t  Disp        = MI->getOperand(2).getImm();
4729   unsigned Src2        = MI->getOperand(3).getReg();
4730   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4731   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4732   DebugLoc DL          = MI->getDebugLoc();
4733   if (IsSubWord)
4734     BitSize = MI->getOperand(6).getImm();
4735
4736   // Subword operations use 32-bit registers.
4737   const TargetRegisterClass *RC = (BitSize <= 32 ?
4738                                    &SystemZ::GR32BitRegClass :
4739                                    &SystemZ::GR64BitRegClass);
4740   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
4741   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4742
4743   // Get the right opcodes for the displacement.
4744   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
4745   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4746   assert(LOpcode && CSOpcode && "Displacement out of range");
4747
4748   // Create virtual registers for temporary results.
4749   unsigned OrigVal       = MRI.createVirtualRegister(RC);
4750   unsigned OldVal        = MRI.createVirtualRegister(RC);
4751   unsigned NewVal        = MRI.createVirtualRegister(RC);
4752   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4753   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
4754   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4755
4756   // Insert 3 basic blocks for the loop.
4757   MachineBasicBlock *StartMBB  = MBB;
4758   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
4759   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
4760   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
4761   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
4762
4763   //  StartMBB:
4764   //   ...
4765   //   %OrigVal     = L Disp(%Base)
4766   //   # fall through to LoopMMB
4767   MBB = StartMBB;
4768   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
4769     .addOperand(Base).addImm(Disp).addReg(0);
4770   MBB->addSuccessor(LoopMBB);
4771
4772   //  LoopMBB:
4773   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
4774   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
4775   //   CompareOpcode %RotatedOldVal, %Src2
4776   //   BRC KeepOldMask, UpdateMBB
4777   MBB = LoopMBB;
4778   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4779     .addReg(OrigVal).addMBB(StartMBB)
4780     .addReg(Dest).addMBB(UpdateMBB);
4781   if (IsSubWord)
4782     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
4783       .addReg(OldVal).addReg(BitShift).addImm(0);
4784   BuildMI(MBB, DL, TII->get(CompareOpcode))
4785     .addReg(RotatedOldVal).addReg(Src2);
4786   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4787     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
4788   MBB->addSuccessor(UpdateMBB);
4789   MBB->addSuccessor(UseAltMBB);
4790
4791   //  UseAltMBB:
4792   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
4793   //   # fall through to UpdateMMB
4794   MBB = UseAltMBB;
4795   if (IsSubWord)
4796     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
4797       .addReg(RotatedOldVal).addReg(Src2)
4798       .addImm(32).addImm(31 + BitSize).addImm(0);
4799   MBB->addSuccessor(UpdateMBB);
4800
4801   //  UpdateMBB:
4802   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
4803   //                        [ %RotatedAltVal, UseAltMBB ]
4804   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
4805   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
4806   //   JNE LoopMBB
4807   //   # fall through to DoneMMB
4808   MBB = UpdateMBB;
4809   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
4810     .addReg(RotatedOldVal).addMBB(LoopMBB)
4811     .addReg(RotatedAltVal).addMBB(UseAltMBB);
4812   if (IsSubWord)
4813     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
4814       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
4815   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
4816     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
4817   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4818     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4819   MBB->addSuccessor(LoopMBB);
4820   MBB->addSuccessor(DoneMBB);
4821
4822   MI->eraseFromParent();
4823   return DoneMBB;
4824 }
4825
4826 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
4827 // instruction MI.
4828 MachineBasicBlock *
4829 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
4830                                           MachineBasicBlock *MBB) const {
4831   MachineFunction &MF = *MBB->getParent();
4832   const SystemZInstrInfo *TII =
4833       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4834   MachineRegisterInfo &MRI = MF.getRegInfo();
4835
4836   // Extract the operands.  Base can be a register or a frame index.
4837   unsigned Dest        = MI->getOperand(0).getReg();
4838   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
4839   int64_t  Disp        = MI->getOperand(2).getImm();
4840   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
4841   unsigned OrigSwapVal = MI->getOperand(4).getReg();
4842   unsigned BitShift    = MI->getOperand(5).getReg();
4843   unsigned NegBitShift = MI->getOperand(6).getReg();
4844   int64_t  BitSize     = MI->getOperand(7).getImm();
4845   DebugLoc DL          = MI->getDebugLoc();
4846
4847   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
4848
4849   // Get the right opcodes for the displacement.
4850   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
4851   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
4852   assert(LOpcode && CSOpcode && "Displacement out of range");
4853
4854   // Create virtual registers for temporary results.
4855   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
4856   unsigned OldVal       = MRI.createVirtualRegister(RC);
4857   unsigned CmpVal       = MRI.createVirtualRegister(RC);
4858   unsigned SwapVal      = MRI.createVirtualRegister(RC);
4859   unsigned StoreVal     = MRI.createVirtualRegister(RC);
4860   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
4861   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
4862   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
4863
4864   // Insert 2 basic blocks for the loop.
4865   MachineBasicBlock *StartMBB = MBB;
4866   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
4867   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
4868   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
4869
4870   //  StartMBB:
4871   //   ...
4872   //   %OrigOldVal     = L Disp(%Base)
4873   //   # fall through to LoopMMB
4874   MBB = StartMBB;
4875   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
4876     .addOperand(Base).addImm(Disp).addReg(0);
4877   MBB->addSuccessor(LoopMBB);
4878
4879   //  LoopMBB:
4880   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
4881   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
4882   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
4883   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
4884   //                      ^^ The low BitSize bits contain the field
4885   //                         of interest.
4886   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
4887   //                      ^^ Replace the upper 32-BitSize bits of the
4888   //                         comparison value with those that we loaded,
4889   //                         so that we can use a full word comparison.
4890   //   CR %Dest, %RetryCmpVal
4891   //   JNE DoneMBB
4892   //   # Fall through to SetMBB
4893   MBB = LoopMBB;
4894   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4895     .addReg(OrigOldVal).addMBB(StartMBB)
4896     .addReg(RetryOldVal).addMBB(SetMBB);
4897   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
4898     .addReg(OrigCmpVal).addMBB(StartMBB)
4899     .addReg(RetryCmpVal).addMBB(SetMBB);
4900   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
4901     .addReg(OrigSwapVal).addMBB(StartMBB)
4902     .addReg(RetrySwapVal).addMBB(SetMBB);
4903   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
4904     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
4905   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
4906     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
4907   BuildMI(MBB, DL, TII->get(SystemZ::CR))
4908     .addReg(Dest).addReg(RetryCmpVal);
4909   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4910     .addImm(SystemZ::CCMASK_ICMP)
4911     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
4912   MBB->addSuccessor(DoneMBB);
4913   MBB->addSuccessor(SetMBB);
4914
4915   //  SetMBB:
4916   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
4917   //                      ^^ Replace the upper 32-BitSize bits of the new
4918   //                         value with those that we loaded.
4919   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
4920   //                      ^^ Rotate the new field to its proper position.
4921   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
4922   //   JNE LoopMBB
4923   //   # fall through to ExitMMB
4924   MBB = SetMBB;
4925   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
4926     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
4927   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
4928     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
4929   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
4930     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
4931   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4932     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4933   MBB->addSuccessor(LoopMBB);
4934   MBB->addSuccessor(DoneMBB);
4935
4936   MI->eraseFromParent();
4937   return DoneMBB;
4938 }
4939
4940 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
4941 // if the high register of the GR128 value must be cleared or false if
4942 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
4943 // and subreg_l64 when extending a GR64.
4944 MachineBasicBlock *
4945 SystemZTargetLowering::emitExt128(MachineInstr *MI,
4946                                   MachineBasicBlock *MBB,
4947                                   bool ClearEven, unsigned SubReg) const {
4948   MachineFunction &MF = *MBB->getParent();
4949   const SystemZInstrInfo *TII =
4950       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4951   MachineRegisterInfo &MRI = MF.getRegInfo();
4952   DebugLoc DL = MI->getDebugLoc();
4953
4954   unsigned Dest  = MI->getOperand(0).getReg();
4955   unsigned Src   = MI->getOperand(1).getReg();
4956   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
4957
4958   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
4959   if (ClearEven) {
4960     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
4961     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
4962
4963     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
4964       .addImm(0);
4965     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
4966       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
4967     In128 = NewIn128;
4968   }
4969   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
4970     .addReg(In128).addReg(Src).addImm(SubReg);
4971
4972   MI->eraseFromParent();
4973   return MBB;
4974 }
4975
4976 MachineBasicBlock *
4977 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
4978                                          MachineBasicBlock *MBB,
4979                                          unsigned Opcode) const {
4980   MachineFunction &MF = *MBB->getParent();
4981   const SystemZInstrInfo *TII =
4982       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4983   MachineRegisterInfo &MRI = MF.getRegInfo();
4984   DebugLoc DL = MI->getDebugLoc();
4985
4986   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
4987   uint64_t       DestDisp = MI->getOperand(1).getImm();
4988   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
4989   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
4990   uint64_t       Length   = MI->getOperand(4).getImm();
4991
4992   // When generating more than one CLC, all but the last will need to
4993   // branch to the end when a difference is found.
4994   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
4995                                splitBlockAfter(MI, MBB) : nullptr);
4996
4997   // Check for the loop form, in which operand 5 is the trip count.
4998   if (MI->getNumExplicitOperands() > 5) {
4999     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5000
5001     uint64_t StartCountReg = MI->getOperand(5).getReg();
5002     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
5003     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
5004                               forceReg(MI, DestBase, TII));
5005
5006     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5007     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
5008     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5009                             MRI.createVirtualRegister(RC));
5010     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
5011     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5012                             MRI.createVirtualRegister(RC));
5013
5014     RC = &SystemZ::GR64BitRegClass;
5015     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5016     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5017
5018     MachineBasicBlock *StartMBB = MBB;
5019     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5020     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5021     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5022
5023     //  StartMBB:
5024     //   # fall through to LoopMMB
5025     MBB->addSuccessor(LoopMBB);
5026
5027     //  LoopMBB:
5028     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5029     //                      [ %NextDestReg, NextMBB ]
5030     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5031     //                     [ %NextSrcReg, NextMBB ]
5032     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5033     //                       [ %NextCountReg, NextMBB ]
5034     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
5035     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5036     //   ( JLH EndMBB )
5037     //
5038     // The prefetch is used only for MVC.  The JLH is used only for CLC.
5039     MBB = LoopMBB;
5040
5041     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5042       .addReg(StartDestReg).addMBB(StartMBB)
5043       .addReg(NextDestReg).addMBB(NextMBB);
5044     if (!HaveSingleBase)
5045       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5046         .addReg(StartSrcReg).addMBB(StartMBB)
5047         .addReg(NextSrcReg).addMBB(NextMBB);
5048     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5049       .addReg(StartCountReg).addMBB(StartMBB)
5050       .addReg(NextCountReg).addMBB(NextMBB);
5051     if (Opcode == SystemZ::MVC)
5052       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5053         .addImm(SystemZ::PFD_WRITE)
5054         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5055     BuildMI(MBB, DL, TII->get(Opcode))
5056       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5057       .addReg(ThisSrcReg).addImm(SrcDisp);
5058     if (EndMBB) {
5059       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5060         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5061         .addMBB(EndMBB);
5062       MBB->addSuccessor(EndMBB);
5063       MBB->addSuccessor(NextMBB);
5064     }
5065
5066     // NextMBB:
5067     //   %NextDestReg = LA 256(%ThisDestReg)
5068     //   %NextSrcReg = LA 256(%ThisSrcReg)
5069     //   %NextCountReg = AGHI %ThisCountReg, -1
5070     //   CGHI %NextCountReg, 0
5071     //   JLH LoopMBB
5072     //   # fall through to DoneMMB
5073     //
5074     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5075     MBB = NextMBB;
5076
5077     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5078       .addReg(ThisDestReg).addImm(256).addReg(0);
5079     if (!HaveSingleBase)
5080       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5081         .addReg(ThisSrcReg).addImm(256).addReg(0);
5082     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5083       .addReg(ThisCountReg).addImm(-1);
5084     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5085       .addReg(NextCountReg).addImm(0);
5086     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5087       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5088       .addMBB(LoopMBB);
5089     MBB->addSuccessor(LoopMBB);
5090     MBB->addSuccessor(DoneMBB);
5091
5092     DestBase = MachineOperand::CreateReg(NextDestReg, false);
5093     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5094     Length &= 255;
5095     MBB = DoneMBB;
5096   }
5097   // Handle any remaining bytes with straight-line code.
5098   while (Length > 0) {
5099     uint64_t ThisLength = std::min(Length, uint64_t(256));
5100     // The previous iteration might have created out-of-range displacements.
5101     // Apply them using LAY if so.
5102     if (!isUInt<12>(DestDisp)) {
5103       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5104       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5105         .addOperand(DestBase).addImm(DestDisp).addReg(0);
5106       DestBase = MachineOperand::CreateReg(Reg, false);
5107       DestDisp = 0;
5108     }
5109     if (!isUInt<12>(SrcDisp)) {
5110       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5111       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5112         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
5113       SrcBase = MachineOperand::CreateReg(Reg, false);
5114       SrcDisp = 0;
5115     }
5116     BuildMI(*MBB, MI, DL, TII->get(Opcode))
5117       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
5118       .addOperand(SrcBase).addImm(SrcDisp);
5119     DestDisp += ThisLength;
5120     SrcDisp += ThisLength;
5121     Length -= ThisLength;
5122     // If there's another CLC to go, branch to the end if a difference
5123     // was found.
5124     if (EndMBB && Length > 0) {
5125       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5126       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5127         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5128         .addMBB(EndMBB);
5129       MBB->addSuccessor(EndMBB);
5130       MBB->addSuccessor(NextMBB);
5131       MBB = NextMBB;
5132     }
5133   }
5134   if (EndMBB) {
5135     MBB->addSuccessor(EndMBB);
5136     MBB = EndMBB;
5137     MBB->addLiveIn(SystemZ::CC);
5138   }
5139
5140   MI->eraseFromParent();
5141   return MBB;
5142 }
5143
5144 // Decompose string pseudo-instruction MI into a loop that continually performs
5145 // Opcode until CC != 3.
5146 MachineBasicBlock *
5147 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
5148                                          MachineBasicBlock *MBB,
5149                                          unsigned Opcode) const {
5150   MachineFunction &MF = *MBB->getParent();
5151   const SystemZInstrInfo *TII =
5152       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5153   MachineRegisterInfo &MRI = MF.getRegInfo();
5154   DebugLoc DL = MI->getDebugLoc();
5155
5156   uint64_t End1Reg   = MI->getOperand(0).getReg();
5157   uint64_t Start1Reg = MI->getOperand(1).getReg();
5158   uint64_t Start2Reg = MI->getOperand(2).getReg();
5159   uint64_t CharReg   = MI->getOperand(3).getReg();
5160
5161   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5162   uint64_t This1Reg = MRI.createVirtualRegister(RC);
5163   uint64_t This2Reg = MRI.createVirtualRegister(RC);
5164   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
5165
5166   MachineBasicBlock *StartMBB = MBB;
5167   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5168   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5169
5170   //  StartMBB:
5171   //   # fall through to LoopMMB
5172   MBB->addSuccessor(LoopMBB);
5173
5174   //  LoopMBB:
5175   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5176   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5177   //   R0L = %CharReg
5178   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5179   //   JO LoopMBB
5180   //   # fall through to DoneMMB
5181   //
5182   // The load of R0L can be hoisted by post-RA LICM.
5183   MBB = LoopMBB;
5184
5185   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5186     .addReg(Start1Reg).addMBB(StartMBB)
5187     .addReg(End1Reg).addMBB(LoopMBB);
5188   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5189     .addReg(Start2Reg).addMBB(StartMBB)
5190     .addReg(End2Reg).addMBB(LoopMBB);
5191   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5192   BuildMI(MBB, DL, TII->get(Opcode))
5193     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5194     .addReg(This1Reg).addReg(This2Reg);
5195   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5196     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5197   MBB->addSuccessor(LoopMBB);
5198   MBB->addSuccessor(DoneMBB);
5199
5200   DoneMBB->addLiveIn(SystemZ::CC);
5201
5202   MI->eraseFromParent();
5203   return DoneMBB;
5204 }
5205
5206 // Update TBEGIN instruction with final opcode and register clobbers.
5207 MachineBasicBlock *
5208 SystemZTargetLowering::emitTransactionBegin(MachineInstr *MI,
5209                                             MachineBasicBlock *MBB,
5210                                             unsigned Opcode,
5211                                             bool NoFloat) const {
5212   MachineFunction &MF = *MBB->getParent();
5213   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
5214   const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
5215
5216   // Update opcode.
5217   MI->setDesc(TII->get(Opcode));
5218
5219   // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
5220   // Make sure to add the corresponding GRSM bits if they are missing.
5221   uint64_t Control = MI->getOperand(2).getImm();
5222   static const unsigned GPRControlBit[16] = {
5223     0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
5224     0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
5225   };
5226   Control |= GPRControlBit[15];
5227   if (TFI->hasFP(MF))
5228     Control |= GPRControlBit[11];
5229   MI->getOperand(2).setImm(Control);
5230
5231   // Add GPR clobbers.
5232   for (int I = 0; I < 16; I++) {
5233     if ((Control & GPRControlBit[I]) == 0) {
5234       unsigned Reg = SystemZMC::GR64Regs[I];
5235       MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5236     }
5237   }
5238
5239   // Add FPR/VR clobbers.
5240   if (!NoFloat && (Control & 4) != 0) {
5241     if (Subtarget.hasVector()) {
5242       for (int I = 0; I < 32; I++) {
5243         unsigned Reg = SystemZMC::VR128Regs[I];
5244         MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5245       }
5246     } else {
5247       for (int I = 0; I < 16; I++) {
5248         unsigned Reg = SystemZMC::FP64Regs[I];
5249         MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5250       }
5251     }
5252   }
5253
5254   return MBB;
5255 }
5256
5257 MachineBasicBlock *SystemZTargetLowering::
5258 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
5259   switch (MI->getOpcode()) {
5260   case SystemZ::Select32Mux:
5261   case SystemZ::Select32:
5262   case SystemZ::SelectF32:
5263   case SystemZ::Select64:
5264   case SystemZ::SelectF64:
5265   case SystemZ::SelectF128:
5266     return emitSelect(MI, MBB);
5267
5268   case SystemZ::CondStore8Mux:
5269     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
5270   case SystemZ::CondStore8MuxInv:
5271     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
5272   case SystemZ::CondStore16Mux:
5273     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
5274   case SystemZ::CondStore16MuxInv:
5275     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
5276   case SystemZ::CondStore8:
5277     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
5278   case SystemZ::CondStore8Inv:
5279     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
5280   case SystemZ::CondStore16:
5281     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
5282   case SystemZ::CondStore16Inv:
5283     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
5284   case SystemZ::CondStore32:
5285     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
5286   case SystemZ::CondStore32Inv:
5287     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
5288   case SystemZ::CondStore64:
5289     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
5290   case SystemZ::CondStore64Inv:
5291     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
5292   case SystemZ::CondStoreF32:
5293     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
5294   case SystemZ::CondStoreF32Inv:
5295     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
5296   case SystemZ::CondStoreF64:
5297     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
5298   case SystemZ::CondStoreF64Inv:
5299     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
5300
5301   case SystemZ::AEXT128_64:
5302     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
5303   case SystemZ::ZEXT128_32:
5304     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
5305   case SystemZ::ZEXT128_64:
5306     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
5307
5308   case SystemZ::ATOMIC_SWAPW:
5309     return emitAtomicLoadBinary(MI, MBB, 0, 0);
5310   case SystemZ::ATOMIC_SWAP_32:
5311     return emitAtomicLoadBinary(MI, MBB, 0, 32);
5312   case SystemZ::ATOMIC_SWAP_64:
5313     return emitAtomicLoadBinary(MI, MBB, 0, 64);
5314
5315   case SystemZ::ATOMIC_LOADW_AR:
5316     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
5317   case SystemZ::ATOMIC_LOADW_AFI:
5318     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
5319   case SystemZ::ATOMIC_LOAD_AR:
5320     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
5321   case SystemZ::ATOMIC_LOAD_AHI:
5322     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
5323   case SystemZ::ATOMIC_LOAD_AFI:
5324     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
5325   case SystemZ::ATOMIC_LOAD_AGR:
5326     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
5327   case SystemZ::ATOMIC_LOAD_AGHI:
5328     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
5329   case SystemZ::ATOMIC_LOAD_AGFI:
5330     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
5331
5332   case SystemZ::ATOMIC_LOADW_SR:
5333     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
5334   case SystemZ::ATOMIC_LOAD_SR:
5335     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
5336   case SystemZ::ATOMIC_LOAD_SGR:
5337     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
5338
5339   case SystemZ::ATOMIC_LOADW_NR:
5340     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
5341   case SystemZ::ATOMIC_LOADW_NILH:
5342     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
5343   case SystemZ::ATOMIC_LOAD_NR:
5344     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
5345   case SystemZ::ATOMIC_LOAD_NILL:
5346     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
5347   case SystemZ::ATOMIC_LOAD_NILH:
5348     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
5349   case SystemZ::ATOMIC_LOAD_NILF:
5350     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
5351   case SystemZ::ATOMIC_LOAD_NGR:
5352     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
5353   case SystemZ::ATOMIC_LOAD_NILL64:
5354     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
5355   case SystemZ::ATOMIC_LOAD_NILH64:
5356     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
5357   case SystemZ::ATOMIC_LOAD_NIHL64:
5358     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
5359   case SystemZ::ATOMIC_LOAD_NIHH64:
5360     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
5361   case SystemZ::ATOMIC_LOAD_NILF64:
5362     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
5363   case SystemZ::ATOMIC_LOAD_NIHF64:
5364     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
5365
5366   case SystemZ::ATOMIC_LOADW_OR:
5367     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
5368   case SystemZ::ATOMIC_LOADW_OILH:
5369     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
5370   case SystemZ::ATOMIC_LOAD_OR:
5371     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
5372   case SystemZ::ATOMIC_LOAD_OILL:
5373     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
5374   case SystemZ::ATOMIC_LOAD_OILH:
5375     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
5376   case SystemZ::ATOMIC_LOAD_OILF:
5377     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
5378   case SystemZ::ATOMIC_LOAD_OGR:
5379     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
5380   case SystemZ::ATOMIC_LOAD_OILL64:
5381     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
5382   case SystemZ::ATOMIC_LOAD_OILH64:
5383     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
5384   case SystemZ::ATOMIC_LOAD_OIHL64:
5385     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
5386   case SystemZ::ATOMIC_LOAD_OIHH64:
5387     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
5388   case SystemZ::ATOMIC_LOAD_OILF64:
5389     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
5390   case SystemZ::ATOMIC_LOAD_OIHF64:
5391     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
5392
5393   case SystemZ::ATOMIC_LOADW_XR:
5394     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
5395   case SystemZ::ATOMIC_LOADW_XILF:
5396     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
5397   case SystemZ::ATOMIC_LOAD_XR:
5398     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
5399   case SystemZ::ATOMIC_LOAD_XILF:
5400     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
5401   case SystemZ::ATOMIC_LOAD_XGR:
5402     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
5403   case SystemZ::ATOMIC_LOAD_XILF64:
5404     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
5405   case SystemZ::ATOMIC_LOAD_XIHF64:
5406     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
5407
5408   case SystemZ::ATOMIC_LOADW_NRi:
5409     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
5410   case SystemZ::ATOMIC_LOADW_NILHi:
5411     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
5412   case SystemZ::ATOMIC_LOAD_NRi:
5413     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
5414   case SystemZ::ATOMIC_LOAD_NILLi:
5415     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
5416   case SystemZ::ATOMIC_LOAD_NILHi:
5417     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
5418   case SystemZ::ATOMIC_LOAD_NILFi:
5419     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
5420   case SystemZ::ATOMIC_LOAD_NGRi:
5421     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
5422   case SystemZ::ATOMIC_LOAD_NILL64i:
5423     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
5424   case SystemZ::ATOMIC_LOAD_NILH64i:
5425     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
5426   case SystemZ::ATOMIC_LOAD_NIHL64i:
5427     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
5428   case SystemZ::ATOMIC_LOAD_NIHH64i:
5429     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
5430   case SystemZ::ATOMIC_LOAD_NILF64i:
5431     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
5432   case SystemZ::ATOMIC_LOAD_NIHF64i:
5433     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
5434
5435   case SystemZ::ATOMIC_LOADW_MIN:
5436     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5437                                 SystemZ::CCMASK_CMP_LE, 0);
5438   case SystemZ::ATOMIC_LOAD_MIN_32:
5439     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5440                                 SystemZ::CCMASK_CMP_LE, 32);
5441   case SystemZ::ATOMIC_LOAD_MIN_64:
5442     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5443                                 SystemZ::CCMASK_CMP_LE, 64);
5444
5445   case SystemZ::ATOMIC_LOADW_MAX:
5446     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5447                                 SystemZ::CCMASK_CMP_GE, 0);
5448   case SystemZ::ATOMIC_LOAD_MAX_32:
5449     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5450                                 SystemZ::CCMASK_CMP_GE, 32);
5451   case SystemZ::ATOMIC_LOAD_MAX_64:
5452     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5453                                 SystemZ::CCMASK_CMP_GE, 64);
5454
5455   case SystemZ::ATOMIC_LOADW_UMIN:
5456     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5457                                 SystemZ::CCMASK_CMP_LE, 0);
5458   case SystemZ::ATOMIC_LOAD_UMIN_32:
5459     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5460                                 SystemZ::CCMASK_CMP_LE, 32);
5461   case SystemZ::ATOMIC_LOAD_UMIN_64:
5462     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5463                                 SystemZ::CCMASK_CMP_LE, 64);
5464
5465   case SystemZ::ATOMIC_LOADW_UMAX:
5466     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5467                                 SystemZ::CCMASK_CMP_GE, 0);
5468   case SystemZ::ATOMIC_LOAD_UMAX_32:
5469     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5470                                 SystemZ::CCMASK_CMP_GE, 32);
5471   case SystemZ::ATOMIC_LOAD_UMAX_64:
5472     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5473                                 SystemZ::CCMASK_CMP_GE, 64);
5474
5475   case SystemZ::ATOMIC_CMP_SWAPW:
5476     return emitAtomicCmpSwapW(MI, MBB);
5477   case SystemZ::MVCSequence:
5478   case SystemZ::MVCLoop:
5479     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
5480   case SystemZ::NCSequence:
5481   case SystemZ::NCLoop:
5482     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
5483   case SystemZ::OCSequence:
5484   case SystemZ::OCLoop:
5485     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
5486   case SystemZ::XCSequence:
5487   case SystemZ::XCLoop:
5488     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
5489   case SystemZ::CLCSequence:
5490   case SystemZ::CLCLoop:
5491     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
5492   case SystemZ::CLSTLoop:
5493     return emitStringWrapper(MI, MBB, SystemZ::CLST);
5494   case SystemZ::MVSTLoop:
5495     return emitStringWrapper(MI, MBB, SystemZ::MVST);
5496   case SystemZ::SRSTLoop:
5497     return emitStringWrapper(MI, MBB, SystemZ::SRST);
5498   case SystemZ::TBEGIN:
5499     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
5500   case SystemZ::TBEGIN_nofloat:
5501     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
5502   case SystemZ::TBEGINC:
5503     return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
5504   default:
5505     llvm_unreachable("Unexpected instr type to insert");
5506   }
5507 }