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