1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SystemZTargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SystemZISelLowering.h"
14 #include "SystemZCallingConv.h"
15 #include "SystemZConstantPoolValue.h"
16 #include "SystemZMachineFunctionInfo.h"
17 #include "SystemZTargetMachine.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/IntrinsicsS390.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/KnownBits.h"
27 #include <cctype>
28 
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "systemz-lower"
32 
33 namespace {
34 // Represents information about a comparison.
35 struct Comparison {
36   Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
37     : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
38       Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
39 
40   // The operands to the comparison.
41   SDValue Op0, Op1;
42 
43   // Chain if this is a strict floating-point comparison.
44   SDValue Chain;
45 
46   // The opcode that should be used to compare Op0 and Op1.
47   unsigned Opcode;
48 
49   // A SystemZICMP value.  Only used for integer comparisons.
50   unsigned ICmpType;
51 
52   // The mask of CC values that Opcode can produce.
53   unsigned CCValid;
54 
55   // The mask of CC values for which the original condition is true.
56   unsigned CCMask;
57 };
58 } // end anonymous namespace
59 
60 // Classify VT as either 32 or 64 bit.
61 static bool is32Bit(EVT VT) {
62   switch (VT.getSimpleVT().SimpleTy) {
63   case MVT::i32:
64     return true;
65   case MVT::i64:
66     return false;
67   default:
68     llvm_unreachable("Unsupported type");
69   }
70 }
71 
72 // Return a version of MachineOperand that can be safely used before the
73 // final use.
74 static MachineOperand earlyUseOperand(MachineOperand Op) {
75   if (Op.isReg())
76     Op.setIsKill(false);
77   return Op;
78 }
79 
80 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
81                                              const SystemZSubtarget &STI)
82     : TargetLowering(TM), Subtarget(STI) {
83   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize(0));
84 
85   // Set up the register classes.
86   if (Subtarget.hasHighWord())
87     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
88   else
89     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
90   addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
91   if (Subtarget.hasVector()) {
92     addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
93     addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
94   } else {
95     addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
96     addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
97   }
98   if (Subtarget.hasVectorEnhancements1())
99     addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
100   else
101     addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
102 
103   if (Subtarget.hasVector()) {
104     addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
105     addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
106     addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
107     addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
108     addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
109     addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
110   }
111 
112   // Compute derived properties from the register classes
113   computeRegisterProperties(Subtarget.getRegisterInfo());
114 
115   // Set up special registers.
116   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
117 
118   // TODO: It may be better to default to latency-oriented scheduling, however
119   // LLVM's current latency-oriented scheduler can't handle physreg definitions
120   // such as SystemZ has with CC, so set this to the register-pressure
121   // scheduler, because it can.
122   setSchedulingPreference(Sched::RegPressure);
123 
124   setBooleanContents(ZeroOrOneBooleanContent);
125   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
126 
127   // Instructions are strings of 2-byte aligned 2-byte values.
128   setMinFunctionAlignment(Align(2));
129   // For performance reasons we prefer 16-byte alignment.
130   setPrefFunctionAlignment(Align(16));
131 
132   // Handle operations that are handled in a similar way for all types.
133   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
134        I <= MVT::LAST_FP_VALUETYPE;
135        ++I) {
136     MVT VT = MVT::SimpleValueType(I);
137     if (isTypeLegal(VT)) {
138       // Lower SET_CC into an IPM-based sequence.
139       setOperationAction(ISD::SETCC, VT, Custom);
140       setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
141       setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
142 
143       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
144       setOperationAction(ISD::SELECT, VT, Expand);
145 
146       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
147       setOperationAction(ISD::SELECT_CC, VT, Custom);
148       setOperationAction(ISD::BR_CC,     VT, Custom);
149     }
150   }
151 
152   // Expand jump table branches as address arithmetic followed by an
153   // indirect jump.
154   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
155 
156   // Expand BRCOND into a BR_CC (see above).
157   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
158 
159   // Handle integer types.
160   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
161        I <= MVT::LAST_INTEGER_VALUETYPE;
162        ++I) {
163     MVT VT = MVT::SimpleValueType(I);
164     if (isTypeLegal(VT)) {
165       // Expand individual DIV and REMs into DIVREMs.
166       setOperationAction(ISD::SDIV, VT, Expand);
167       setOperationAction(ISD::UDIV, VT, Expand);
168       setOperationAction(ISD::SREM, VT, Expand);
169       setOperationAction(ISD::UREM, VT, Expand);
170       setOperationAction(ISD::SDIVREM, VT, Custom);
171       setOperationAction(ISD::UDIVREM, VT, Custom);
172 
173       // Support addition/subtraction with overflow.
174       setOperationAction(ISD::SADDO, VT, Custom);
175       setOperationAction(ISD::SSUBO, VT, Custom);
176 
177       // Support addition/subtraction with carry.
178       setOperationAction(ISD::UADDO, VT, Custom);
179       setOperationAction(ISD::USUBO, VT, Custom);
180 
181       // Support carry in as value rather than glue.
182       setOperationAction(ISD::ADDCARRY, VT, Custom);
183       setOperationAction(ISD::SUBCARRY, VT, Custom);
184 
185       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
186       // stores, putting a serialization instruction after the stores.
187       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
188       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
189 
190       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
191       // available, or if the operand is constant.
192       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
193 
194       // Use POPCNT on z196 and above.
195       if (Subtarget.hasPopulationCount())
196         setOperationAction(ISD::CTPOP, VT, Custom);
197       else
198         setOperationAction(ISD::CTPOP, VT, Expand);
199 
200       // No special instructions for these.
201       setOperationAction(ISD::CTTZ,            VT, Expand);
202       setOperationAction(ISD::ROTR,            VT, Expand);
203 
204       // Use *MUL_LOHI where possible instead of MULH*.
205       setOperationAction(ISD::MULHS, VT, Expand);
206       setOperationAction(ISD::MULHU, VT, Expand);
207       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
208       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
209 
210       // Only z196 and above have native support for conversions to unsigned.
211       // On z10, promoting to i64 doesn't generate an inexact condition for
212       // values that are outside the i32 range but in the i64 range, so use
213       // the default expansion.
214       if (!Subtarget.hasFPExtension())
215         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
216 
217       // Mirror those settings for STRICT_FP_TO_[SU]INT.  Note that these all
218       // default to Expand, so need to be modified to Legal where appropriate.
219       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Legal);
220       if (Subtarget.hasFPExtension())
221         setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Legal);
222     }
223   }
224 
225   // Type legalization will convert 8- and 16-bit atomic operations into
226   // forms that operate on i32s (but still keeping the original memory VT).
227   // Lower them into full i32 operations.
228   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
229   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
230   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
231   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
232   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
233   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
234   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
235   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
236   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
237   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
238   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
239 
240   // Even though i128 is not a legal type, we still need to custom lower
241   // the atomic operations in order to exploit SystemZ instructions.
242   setOperationAction(ISD::ATOMIC_LOAD,     MVT::i128, Custom);
243   setOperationAction(ISD::ATOMIC_STORE,    MVT::i128, Custom);
244 
245   // We can use the CC result of compare-and-swap to implement
246   // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
247   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Custom);
248   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Custom);
249   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
250 
251   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
252 
253   // Traps are legal, as we will convert them to "j .+2".
254   setOperationAction(ISD::TRAP, MVT::Other, Legal);
255 
256   // z10 has instructions for signed but not unsigned FP conversion.
257   // Handle unsigned 32-bit types as signed 64-bit types.
258   if (!Subtarget.hasFPExtension()) {
259     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
260     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
261   }
262 
263   // We have native support for a 64-bit CTLZ, via FLOGR.
264   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
265   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Promote);
266   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
267 
268   // On z15 we have native support for a 64-bit CTPOP.
269   if (Subtarget.hasMiscellaneousExtensions3()) {
270     setOperationAction(ISD::CTPOP, MVT::i32, Promote);
271     setOperationAction(ISD::CTPOP, MVT::i64, Legal);
272   }
273 
274   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
275   setOperationAction(ISD::OR, MVT::i64, Custom);
276 
277   // FIXME: Can we support these natively?
278   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
279   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
280   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
281 
282   // We have native instructions for i8, i16 and i32 extensions, but not i1.
283   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
284   for (MVT VT : MVT::integer_valuetypes()) {
285     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
286     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
287     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
288   }
289 
290   // Handle the various types of symbolic address.
291   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
292   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
293   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
294   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
295   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
296 
297   // We need to handle dynamic allocations specially because of the
298   // 160-byte area at the bottom of the stack.
299   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
300   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
301 
302   // Use custom expanders so that we can force the function to use
303   // a frame pointer.
304   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
305   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
306 
307   // Handle prefetches with PFD or PFDRL.
308   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
309 
310   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
311     // Assume by default that all vector operations need to be expanded.
312     for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
313       if (getOperationAction(Opcode, VT) == Legal)
314         setOperationAction(Opcode, VT, Expand);
315 
316     // Likewise all truncating stores and extending loads.
317     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
318       setTruncStoreAction(VT, InnerVT, Expand);
319       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
320       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
321       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
322     }
323 
324     if (isTypeLegal(VT)) {
325       // These operations are legal for anything that can be stored in a
326       // vector register, even if there is no native support for the format
327       // as such.  In particular, we can do these for v4f32 even though there
328       // are no specific instructions for that format.
329       setOperationAction(ISD::LOAD, VT, Legal);
330       setOperationAction(ISD::STORE, VT, Legal);
331       setOperationAction(ISD::VSELECT, VT, Legal);
332       setOperationAction(ISD::BITCAST, VT, Legal);
333       setOperationAction(ISD::UNDEF, VT, Legal);
334 
335       // Likewise, except that we need to replace the nodes with something
336       // more specific.
337       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
338       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
339     }
340   }
341 
342   // Handle integer vector types.
343   for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
344     if (isTypeLegal(VT)) {
345       // These operations have direct equivalents.
346       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
347       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
348       setOperationAction(ISD::ADD, VT, Legal);
349       setOperationAction(ISD::SUB, VT, Legal);
350       if (VT != MVT::v2i64)
351         setOperationAction(ISD::MUL, VT, Legal);
352       setOperationAction(ISD::AND, VT, Legal);
353       setOperationAction(ISD::OR, VT, Legal);
354       setOperationAction(ISD::XOR, VT, Legal);
355       if (Subtarget.hasVectorEnhancements1())
356         setOperationAction(ISD::CTPOP, VT, Legal);
357       else
358         setOperationAction(ISD::CTPOP, VT, Custom);
359       setOperationAction(ISD::CTTZ, VT, Legal);
360       setOperationAction(ISD::CTLZ, VT, Legal);
361 
362       // Convert a GPR scalar to a vector by inserting it into element 0.
363       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
364 
365       // Use a series of unpacks for extensions.
366       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
367       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
368 
369       // Detect shifts by a scalar amount and convert them into
370       // V*_BY_SCALAR.
371       setOperationAction(ISD::SHL, VT, Custom);
372       setOperationAction(ISD::SRA, VT, Custom);
373       setOperationAction(ISD::SRL, VT, Custom);
374 
375       // At present ROTL isn't matched by DAGCombiner.  ROTR should be
376       // converted into ROTL.
377       setOperationAction(ISD::ROTL, VT, Expand);
378       setOperationAction(ISD::ROTR, VT, Expand);
379 
380       // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
381       // and inverting the result as necessary.
382       setOperationAction(ISD::SETCC, VT, Custom);
383       setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
384       if (Subtarget.hasVectorEnhancements1())
385         setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
386     }
387   }
388 
389   if (Subtarget.hasVector()) {
390     // There should be no need to check for float types other than v2f64
391     // since <2 x f32> isn't a legal type.
392     setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
393     setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal);
394     setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
395     setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal);
396     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
397     setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal);
398     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
399     setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal);
400 
401     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
402     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f64, Legal);
403     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
404     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f64, Legal);
405   }
406 
407   if (Subtarget.hasVectorEnhancements2()) {
408     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
409     setOperationAction(ISD::FP_TO_SINT, MVT::v4f32, Legal);
410     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
411     setOperationAction(ISD::FP_TO_UINT, MVT::v4f32, Legal);
412     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
413     setOperationAction(ISD::SINT_TO_FP, MVT::v4f32, Legal);
414     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
415     setOperationAction(ISD::UINT_TO_FP, MVT::v4f32, Legal);
416 
417     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
418     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f32, Legal);
419     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
420     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f32, Legal);
421   }
422 
423   // Handle floating-point types.
424   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
425        I <= MVT::LAST_FP_VALUETYPE;
426        ++I) {
427     MVT VT = MVT::SimpleValueType(I);
428     if (isTypeLegal(VT)) {
429       // We can use FI for FRINT.
430       setOperationAction(ISD::FRINT, VT, Legal);
431 
432       // We can use the extended form of FI for other rounding operations.
433       if (Subtarget.hasFPExtension()) {
434         setOperationAction(ISD::FNEARBYINT, VT, Legal);
435         setOperationAction(ISD::FFLOOR, VT, Legal);
436         setOperationAction(ISD::FCEIL, VT, Legal);
437         setOperationAction(ISD::FTRUNC, VT, Legal);
438         setOperationAction(ISD::FROUND, VT, Legal);
439       }
440 
441       // No special instructions for these.
442       setOperationAction(ISD::FSIN, VT, Expand);
443       setOperationAction(ISD::FCOS, VT, Expand);
444       setOperationAction(ISD::FSINCOS, VT, Expand);
445       setOperationAction(ISD::FREM, VT, Expand);
446       setOperationAction(ISD::FPOW, VT, Expand);
447 
448       // Handle constrained floating-point operations.
449       setOperationAction(ISD::STRICT_FADD, VT, Legal);
450       setOperationAction(ISD::STRICT_FSUB, VT, Legal);
451       setOperationAction(ISD::STRICT_FMUL, VT, Legal);
452       setOperationAction(ISD::STRICT_FDIV, VT, Legal);
453       setOperationAction(ISD::STRICT_FMA, VT, Legal);
454       setOperationAction(ISD::STRICT_FSQRT, VT, Legal);
455       setOperationAction(ISD::STRICT_FRINT, VT, Legal);
456       setOperationAction(ISD::STRICT_FP_ROUND, VT, Legal);
457       setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal);
458       if (Subtarget.hasFPExtension()) {
459         setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
460         setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
461         setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
462         setOperationAction(ISD::STRICT_FROUND, VT, Legal);
463         setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
464       }
465     }
466   }
467 
468   // Handle floating-point vector types.
469   if (Subtarget.hasVector()) {
470     // Scalar-to-vector conversion is just a subreg.
471     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
472     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
473 
474     // Some insertions and extractions can be done directly but others
475     // need to go via integers.
476     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
477     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
478     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
479     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
480 
481     // These operations have direct equivalents.
482     setOperationAction(ISD::FADD, MVT::v2f64, Legal);
483     setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
484     setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
485     setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
486     setOperationAction(ISD::FMA, MVT::v2f64, Legal);
487     setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
488     setOperationAction(ISD::FABS, MVT::v2f64, Legal);
489     setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
490     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
491     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
492     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
493     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
494     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
495     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
496 
497     // Handle constrained floating-point operations.
498     setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
499     setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
500     setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
501     setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
502     setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
503     setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
504     setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
505     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
506     setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
507     setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
508     setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
509     setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
510   }
511 
512   // The vector enhancements facility 1 has instructions for these.
513   if (Subtarget.hasVectorEnhancements1()) {
514     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
515     setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
516     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
517     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
518     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
519     setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
520     setOperationAction(ISD::FABS, MVT::v4f32, Legal);
521     setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
522     setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
523     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
524     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
525     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
526     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
527     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
528 
529     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
530     setOperationAction(ISD::FMAXIMUM, MVT::f64, Legal);
531     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
532     setOperationAction(ISD::FMINIMUM, MVT::f64, Legal);
533 
534     setOperationAction(ISD::FMAXNUM, MVT::v2f64, Legal);
535     setOperationAction(ISD::FMAXIMUM, MVT::v2f64, Legal);
536     setOperationAction(ISD::FMINNUM, MVT::v2f64, Legal);
537     setOperationAction(ISD::FMINIMUM, MVT::v2f64, Legal);
538 
539     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
540     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
541     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
542     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
543 
544     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
545     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
546     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
547     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
548 
549     setOperationAction(ISD::FMAXNUM, MVT::f128, Legal);
550     setOperationAction(ISD::FMAXIMUM, MVT::f128, Legal);
551     setOperationAction(ISD::FMINNUM, MVT::f128, Legal);
552     setOperationAction(ISD::FMINIMUM, MVT::f128, Legal);
553 
554     // Handle constrained floating-point operations.
555     setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
556     setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
557     setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
558     setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
559     setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
560     setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
561     setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
562     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
563     setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
564     setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
565     setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
566     setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
567     for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
568                      MVT::v4f32, MVT::v2f64 }) {
569       setOperationAction(ISD::STRICT_FMAXNUM, VT, Legal);
570       setOperationAction(ISD::STRICT_FMINNUM, VT, Legal);
571     }
572   }
573 
574   // We only have fused f128 multiply-addition on vector registers.
575   if (!Subtarget.hasVectorEnhancements1()) {
576     setOperationAction(ISD::FMA, MVT::f128, Expand);
577     setOperationAction(ISD::STRICT_FMA, MVT::f128, Expand);
578   }
579 
580   // We don't have a copysign instruction on vector registers.
581   if (Subtarget.hasVectorEnhancements1())
582     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
583 
584   // Needed so that we don't try to implement f128 constant loads using
585   // a load-and-extend of a f80 constant (in cases where the constant
586   // would fit in an f80).
587   for (MVT VT : MVT::fp_valuetypes())
588     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
589 
590   // We don't have extending load instruction on vector registers.
591   if (Subtarget.hasVectorEnhancements1()) {
592     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
593     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
594   }
595 
596   // Floating-point truncation and stores need to be done separately.
597   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
598   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
599   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
600 
601   // We have 64-bit FPR<->GPR moves, but need special handling for
602   // 32-bit forms.
603   if (!Subtarget.hasVector()) {
604     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
605     setOperationAction(ISD::BITCAST, MVT::f32, Custom);
606   }
607 
608   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
609   // structure, but VAEND is a no-op.
610   setOperationAction(ISD::VASTART, MVT::Other, Custom);
611   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
612   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
613 
614   // Codes for which we want to perform some z-specific combinations.
615   setTargetDAGCombine(ISD::ZERO_EXTEND);
616   setTargetDAGCombine(ISD::SIGN_EXTEND);
617   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
618   setTargetDAGCombine(ISD::LOAD);
619   setTargetDAGCombine(ISD::STORE);
620   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
621   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
622   setTargetDAGCombine(ISD::FP_ROUND);
623   setTargetDAGCombine(ISD::FP_EXTEND);
624   setTargetDAGCombine(ISD::BSWAP);
625   setTargetDAGCombine(ISD::SDIV);
626   setTargetDAGCombine(ISD::UDIV);
627   setTargetDAGCombine(ISD::SREM);
628   setTargetDAGCombine(ISD::UREM);
629 
630   // Handle intrinsics.
631   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
632   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
633 
634   // We want to use MVC in preference to even a single load/store pair.
635   MaxStoresPerMemcpy = 0;
636   MaxStoresPerMemcpyOptSize = 0;
637 
638   // The main memset sequence is a byte store followed by an MVC.
639   // Two STC or MV..I stores win over that, but the kind of fused stores
640   // generated by target-independent code don't when the byte value is
641   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
642   // than "STC;MVC".  Handle the choice in target-specific code instead.
643   MaxStoresPerMemset = 0;
644   MaxStoresPerMemsetOptSize = 0;
645 
646   // Default to having -disable-strictnode-mutation on
647   IsStrictFPEnabled = true;
648 }
649 
650 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
651                                               LLVMContext &, EVT VT) const {
652   if (!VT.isVector())
653     return MVT::i32;
654   return VT.changeVectorElementTypeToInteger();
655 }
656 
657 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(
658     const MachineFunction &MF, EVT VT) const {
659   VT = VT.getScalarType();
660 
661   if (!VT.isSimple())
662     return false;
663 
664   switch (VT.getSimpleVT().SimpleTy) {
665   case MVT::f32:
666   case MVT::f64:
667     return true;
668   case MVT::f128:
669     return Subtarget.hasVectorEnhancements1();
670   default:
671     break;
672   }
673 
674   return false;
675 }
676 
677 // Return true if the constant can be generated with a vector instruction,
678 // such as VGM, VGMB or VREPI.
679 bool SystemZVectorConstantInfo::isVectorConstantLegal(
680     const SystemZSubtarget &Subtarget) {
681   const SystemZInstrInfo *TII =
682       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
683   if (!Subtarget.hasVector() ||
684       (isFP128 && !Subtarget.hasVectorEnhancements1()))
685     return false;
686 
687   // Try using VECTOR GENERATE BYTE MASK.  This is the architecturally-
688   // preferred way of creating all-zero and all-one vectors so give it
689   // priority over other methods below.
690   unsigned Mask = 0;
691   unsigned I = 0;
692   for (; I < SystemZ::VectorBytes; ++I) {
693     uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
694     if (Byte == 0xff)
695       Mask |= 1ULL << I;
696     else if (Byte != 0)
697       break;
698   }
699   if (I == SystemZ::VectorBytes) {
700     Opcode = SystemZISD::BYTE_MASK;
701     OpVals.push_back(Mask);
702     VecVT = MVT::getVectorVT(MVT::getIntegerVT(8), 16);
703     return true;
704   }
705 
706   if (SplatBitSize > 64)
707     return false;
708 
709   auto tryValue = [&](uint64_t Value) -> bool {
710     // Try VECTOR REPLICATE IMMEDIATE
711     int64_t SignedValue = SignExtend64(Value, SplatBitSize);
712     if (isInt<16>(SignedValue)) {
713       OpVals.push_back(((unsigned) SignedValue));
714       Opcode = SystemZISD::REPLICATE;
715       VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
716                                SystemZ::VectorBits / SplatBitSize);
717       return true;
718     }
719     // Try VECTOR GENERATE MASK
720     unsigned Start, End;
721     if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
722       // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
723       // denoting 1 << 63 and 63 denoting 1.  Convert them to bit numbers for
724       // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
725       OpVals.push_back(Start - (64 - SplatBitSize));
726       OpVals.push_back(End - (64 - SplatBitSize));
727       Opcode = SystemZISD::ROTATE_MASK;
728       VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
729                                SystemZ::VectorBits / SplatBitSize);
730       return true;
731     }
732     return false;
733   };
734 
735   // First try assuming that any undefined bits above the highest set bit
736   // and below the lowest set bit are 1s.  This increases the likelihood of
737   // being able to use a sign-extended element value in VECTOR REPLICATE
738   // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
739   uint64_t SplatBitsZ = SplatBits.getZExtValue();
740   uint64_t SplatUndefZ = SplatUndef.getZExtValue();
741   uint64_t Lower =
742       (SplatUndefZ & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
743   uint64_t Upper =
744       (SplatUndefZ & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
745   if (tryValue(SplatBitsZ | Upper | Lower))
746     return true;
747 
748   // Now try assuming that any undefined bits between the first and
749   // last defined set bits are set.  This increases the chances of
750   // using a non-wraparound mask.
751   uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
752   return tryValue(SplatBitsZ | Middle);
753 }
754 
755 SystemZVectorConstantInfo::SystemZVectorConstantInfo(APFloat FPImm) {
756   IntBits = FPImm.bitcastToAPInt().zextOrSelf(128);
757   isFP128 = (&FPImm.getSemantics() == &APFloat::IEEEquad());
758 
759   // Find the smallest splat.
760   SplatBits = FPImm.bitcastToAPInt();
761   unsigned Width = SplatBits.getBitWidth();
762   while (Width > 8) {
763     unsigned HalfSize = Width / 2;
764     APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
765     APInt LowValue = SplatBits.trunc(HalfSize);
766 
767     // If the two halves do not match, stop here.
768     if (HighValue != LowValue || 8 > HalfSize)
769       break;
770 
771     SplatBits = HighValue;
772     Width = HalfSize;
773   }
774   SplatUndef = 0;
775   SplatBitSize = Width;
776 }
777 
778 SystemZVectorConstantInfo::SystemZVectorConstantInfo(BuildVectorSDNode *BVN) {
779   assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
780   bool HasAnyUndefs;
781 
782   // Get IntBits by finding the 128 bit splat.
783   BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
784                        true);
785 
786   // Get SplatBits by finding the 8 bit or greater splat.
787   BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
788                        true);
789 }
790 
791 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
792                                          bool ForCodeSize) const {
793   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
794   if (Imm.isZero() || Imm.isNegZero())
795     return true;
796 
797   return SystemZVectorConstantInfo(Imm).isVectorConstantLegal(Subtarget);
798 }
799 
800 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
801   // We can use CGFI or CLGFI.
802   return isInt<32>(Imm) || isUInt<32>(Imm);
803 }
804 
805 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
806   // We can use ALGFI or SLGFI.
807   return isUInt<32>(Imm) || isUInt<32>(-Imm);
808 }
809 
810 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(
811     EVT VT, unsigned, unsigned, MachineMemOperand::Flags, bool *Fast) const {
812   // Unaligned accesses should never be slower than the expanded version.
813   // We check specifically for aligned accesses in the few cases where
814   // they are required.
815   if (Fast)
816     *Fast = true;
817   return true;
818 }
819 
820 // Information about the addressing mode for a memory access.
821 struct AddressingMode {
822   // True if a long displacement is supported.
823   bool LongDisplacement;
824 
825   // True if use of index register is supported.
826   bool IndexReg;
827 
828   AddressingMode(bool LongDispl, bool IdxReg) :
829     LongDisplacement(LongDispl), IndexReg(IdxReg) {}
830 };
831 
832 // Return the desired addressing mode for a Load which has only one use (in
833 // the same block) which is a Store.
834 static AddressingMode getLoadStoreAddrMode(bool HasVector,
835                                           Type *Ty) {
836   // With vector support a Load->Store combination may be combined to either
837   // an MVC or vector operations and it seems to work best to allow the
838   // vector addressing mode.
839   if (HasVector)
840     return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
841 
842   // Otherwise only the MVC case is special.
843   bool MVC = Ty->isIntegerTy(8);
844   return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
845 }
846 
847 // Return the addressing mode which seems most desirable given an LLVM
848 // Instruction pointer.
849 static AddressingMode
850 supportedAddressingMode(Instruction *I, bool HasVector) {
851   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
852     switch (II->getIntrinsicID()) {
853     default: break;
854     case Intrinsic::memset:
855     case Intrinsic::memmove:
856     case Intrinsic::memcpy:
857       return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
858     }
859   }
860 
861   if (isa<LoadInst>(I) && I->hasOneUse()) {
862     auto *SingleUser = cast<Instruction>(*I->user_begin());
863     if (SingleUser->getParent() == I->getParent()) {
864       if (isa<ICmpInst>(SingleUser)) {
865         if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
866           if (C->getBitWidth() <= 64 &&
867               (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
868             // Comparison of memory with 16 bit signed / unsigned immediate
869             return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
870       } else if (isa<StoreInst>(SingleUser))
871         // Load->Store
872         return getLoadStoreAddrMode(HasVector, I->getType());
873     }
874   } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
875     if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
876       if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
877         // Load->Store
878         return getLoadStoreAddrMode(HasVector, LoadI->getType());
879   }
880 
881   if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
882 
883     // * Use LDE instead of LE/LEY for z13 to avoid partial register
884     //   dependencies (LDE only supports small offsets).
885     // * Utilize the vector registers to hold floating point
886     //   values (vector load / store instructions only support small
887     //   offsets).
888 
889     Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
890                          I->getOperand(0)->getType());
891     bool IsFPAccess = MemAccessTy->isFloatingPointTy();
892     bool IsVectorAccess = MemAccessTy->isVectorTy();
893 
894     // A store of an extracted vector element will be combined into a VSTE type
895     // instruction.
896     if (!IsVectorAccess && isa<StoreInst>(I)) {
897       Value *DataOp = I->getOperand(0);
898       if (isa<ExtractElementInst>(DataOp))
899         IsVectorAccess = true;
900     }
901 
902     // A load which gets inserted into a vector element will be combined into a
903     // VLE type instruction.
904     if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
905       User *LoadUser = *I->user_begin();
906       if (isa<InsertElementInst>(LoadUser))
907         IsVectorAccess = true;
908     }
909 
910     if (IsFPAccess || IsVectorAccess)
911       return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
912   }
913 
914   return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
915 }
916 
917 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
918        const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
919   // Punt on globals for now, although they can be used in limited
920   // RELATIVE LONG cases.
921   if (AM.BaseGV)
922     return false;
923 
924   // Require a 20-bit signed offset.
925   if (!isInt<20>(AM.BaseOffs))
926     return false;
927 
928   AddressingMode SupportedAM(true, true);
929   if (I != nullptr)
930     SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
931 
932   if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
933     return false;
934 
935   if (!SupportedAM.IndexReg)
936     // No indexing allowed.
937     return AM.Scale == 0;
938   else
939     // Indexing is OK but no scale factor can be applied.
940     return AM.Scale == 0 || AM.Scale == 1;
941 }
942 
943 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
944   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
945     return false;
946   unsigned FromBits = FromType->getPrimitiveSizeInBits();
947   unsigned ToBits = ToType->getPrimitiveSizeInBits();
948   return FromBits > ToBits;
949 }
950 
951 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
952   if (!FromVT.isInteger() || !ToVT.isInteger())
953     return false;
954   unsigned FromBits = FromVT.getSizeInBits();
955   unsigned ToBits = ToVT.getSizeInBits();
956   return FromBits > ToBits;
957 }
958 
959 //===----------------------------------------------------------------------===//
960 // Inline asm support
961 //===----------------------------------------------------------------------===//
962 
963 TargetLowering::ConstraintType
964 SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
965   if (Constraint.size() == 1) {
966     switch (Constraint[0]) {
967     case 'a': // Address register
968     case 'd': // Data register (equivalent to 'r')
969     case 'f': // Floating-point register
970     case 'h': // High-part register
971     case 'r': // General-purpose register
972     case 'v': // Vector register
973       return C_RegisterClass;
974 
975     case 'Q': // Memory with base and unsigned 12-bit displacement
976     case 'R': // Likewise, plus an index
977     case 'S': // Memory with base and signed 20-bit displacement
978     case 'T': // Likewise, plus an index
979     case 'm': // Equivalent to 'T'.
980       return C_Memory;
981 
982     case 'I': // Unsigned 8-bit constant
983     case 'J': // Unsigned 12-bit constant
984     case 'K': // Signed 16-bit constant
985     case 'L': // Signed 20-bit displacement (on all targets we support)
986     case 'M': // 0x7fffffff
987       return C_Immediate;
988 
989     default:
990       break;
991     }
992   }
993   return TargetLowering::getConstraintType(Constraint);
994 }
995 
996 TargetLowering::ConstraintWeight SystemZTargetLowering::
997 getSingleConstraintMatchWeight(AsmOperandInfo &info,
998                                const char *constraint) const {
999   ConstraintWeight weight = CW_Invalid;
1000   Value *CallOperandVal = info.CallOperandVal;
1001   // If we don't have a value, we can't do a match,
1002   // but allow it at the lowest weight.
1003   if (!CallOperandVal)
1004     return CW_Default;
1005   Type *type = CallOperandVal->getType();
1006   // Look at the constraint type.
1007   switch (*constraint) {
1008   default:
1009     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1010     break;
1011 
1012   case 'a': // Address register
1013   case 'd': // Data register (equivalent to 'r')
1014   case 'h': // High-part register
1015   case 'r': // General-purpose register
1016     if (CallOperandVal->getType()->isIntegerTy())
1017       weight = CW_Register;
1018     break;
1019 
1020   case 'f': // Floating-point register
1021     if (type->isFloatingPointTy())
1022       weight = CW_Register;
1023     break;
1024 
1025   case 'v': // Vector register
1026     if ((type->isVectorTy() || type->isFloatingPointTy()) &&
1027         Subtarget.hasVector())
1028       weight = CW_Register;
1029     break;
1030 
1031   case 'I': // Unsigned 8-bit constant
1032     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1033       if (isUInt<8>(C->getZExtValue()))
1034         weight = CW_Constant;
1035     break;
1036 
1037   case 'J': // Unsigned 12-bit constant
1038     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1039       if (isUInt<12>(C->getZExtValue()))
1040         weight = CW_Constant;
1041     break;
1042 
1043   case 'K': // Signed 16-bit constant
1044     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1045       if (isInt<16>(C->getSExtValue()))
1046         weight = CW_Constant;
1047     break;
1048 
1049   case 'L': // Signed 20-bit displacement (on all targets we support)
1050     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1051       if (isInt<20>(C->getSExtValue()))
1052         weight = CW_Constant;
1053     break;
1054 
1055   case 'M': // 0x7fffffff
1056     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1057       if (C->getZExtValue() == 0x7fffffff)
1058         weight = CW_Constant;
1059     break;
1060   }
1061   return weight;
1062 }
1063 
1064 // Parse a "{tNNN}" register constraint for which the register type "t"
1065 // has already been verified.  MC is the class associated with "t" and
1066 // Map maps 0-based register numbers to LLVM register numbers.
1067 static std::pair<unsigned, const TargetRegisterClass *>
1068 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
1069                     const unsigned *Map, unsigned Size) {
1070   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1071   if (isdigit(Constraint[2])) {
1072     unsigned Index;
1073     bool Failed =
1074         Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1075     if (!Failed && Index < Size && Map[Index])
1076       return std::make_pair(Map[Index], RC);
1077   }
1078   return std::make_pair(0U, nullptr);
1079 }
1080 
1081 std::pair<unsigned, const TargetRegisterClass *>
1082 SystemZTargetLowering::getRegForInlineAsmConstraint(
1083     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1084   if (Constraint.size() == 1) {
1085     // GCC Constraint Letters
1086     switch (Constraint[0]) {
1087     default: break;
1088     case 'd': // Data register (equivalent to 'r')
1089     case 'r': // General-purpose register
1090       if (VT == MVT::i64)
1091         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1092       else if (VT == MVT::i128)
1093         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1094       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1095 
1096     case 'a': // Address register
1097       if (VT == MVT::i64)
1098         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1099       else if (VT == MVT::i128)
1100         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1101       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1102 
1103     case 'h': // High-part register (an LLVM extension)
1104       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1105 
1106     case 'f': // Floating-point register
1107       if (VT == MVT::f64)
1108         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1109       else if (VT == MVT::f128)
1110         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1111       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1112 
1113     case 'v': // Vector register
1114       if (Subtarget.hasVector()) {
1115         if (VT == MVT::f32)
1116           return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1117         if (VT == MVT::f64)
1118           return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1119         return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1120       }
1121       break;
1122     }
1123   }
1124   if (Constraint.size() > 0 && Constraint[0] == '{') {
1125     // We need to override the default register parsing for GPRs and FPRs
1126     // because the interpretation depends on VT.  The internal names of
1127     // the registers are also different from the external names
1128     // (F0D and F0S instead of F0, etc.).
1129     if (Constraint[1] == 'r') {
1130       if (VT == MVT::i32)
1131         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1132                                    SystemZMC::GR32Regs, 16);
1133       if (VT == MVT::i128)
1134         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1135                                    SystemZMC::GR128Regs, 16);
1136       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1137                                  SystemZMC::GR64Regs, 16);
1138     }
1139     if (Constraint[1] == 'f') {
1140       if (VT == MVT::f32)
1141         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1142                                    SystemZMC::FP32Regs, 16);
1143       if (VT == MVT::f128)
1144         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1145                                    SystemZMC::FP128Regs, 16);
1146       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1147                                  SystemZMC::FP64Regs, 16);
1148     }
1149     if (Constraint[1] == 'v') {
1150       if (VT == MVT::f32)
1151         return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1152                                    SystemZMC::VR32Regs, 32);
1153       if (VT == MVT::f64)
1154         return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1155                                    SystemZMC::VR64Regs, 32);
1156       return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1157                                  SystemZMC::VR128Regs, 32);
1158     }
1159   }
1160   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1161 }
1162 
1163 void SystemZTargetLowering::
1164 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1165                              std::vector<SDValue> &Ops,
1166                              SelectionDAG &DAG) const {
1167   // Only support length 1 constraints for now.
1168   if (Constraint.length() == 1) {
1169     switch (Constraint[0]) {
1170     case 'I': // Unsigned 8-bit constant
1171       if (auto *C = dyn_cast<ConstantSDNode>(Op))
1172         if (isUInt<8>(C->getZExtValue()))
1173           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1174                                               Op.getValueType()));
1175       return;
1176 
1177     case 'J': // Unsigned 12-bit constant
1178       if (auto *C = dyn_cast<ConstantSDNode>(Op))
1179         if (isUInt<12>(C->getZExtValue()))
1180           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1181                                               Op.getValueType()));
1182       return;
1183 
1184     case 'K': // Signed 16-bit constant
1185       if (auto *C = dyn_cast<ConstantSDNode>(Op))
1186         if (isInt<16>(C->getSExtValue()))
1187           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1188                                               Op.getValueType()));
1189       return;
1190 
1191     case 'L': // Signed 20-bit displacement (on all targets we support)
1192       if (auto *C = dyn_cast<ConstantSDNode>(Op))
1193         if (isInt<20>(C->getSExtValue()))
1194           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1195                                               Op.getValueType()));
1196       return;
1197 
1198     case 'M': // 0x7fffffff
1199       if (auto *C = dyn_cast<ConstantSDNode>(Op))
1200         if (C->getZExtValue() == 0x7fffffff)
1201           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1202                                               Op.getValueType()));
1203       return;
1204     }
1205   }
1206   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1207 }
1208 
1209 //===----------------------------------------------------------------------===//
1210 // Calling conventions
1211 //===----------------------------------------------------------------------===//
1212 
1213 #include "SystemZGenCallingConv.inc"
1214 
1215 const MCPhysReg *SystemZTargetLowering::getScratchRegisters(
1216   CallingConv::ID) const {
1217   static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1218                                            SystemZ::R14D, 0 };
1219   return ScratchRegs;
1220 }
1221 
1222 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
1223                                                      Type *ToType) const {
1224   return isTruncateFree(FromType, ToType);
1225 }
1226 
1227 bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
1228   return CI->isTailCall();
1229 }
1230 
1231 // We do not yet support 128-bit single-element vector types.  If the user
1232 // attempts to use such types as function argument or return type, prefer
1233 // to error out instead of emitting code violating the ABI.
1234 static void VerifyVectorType(MVT VT, EVT ArgVT) {
1235   if (ArgVT.isVector() && !VT.isVector())
1236     report_fatal_error("Unsupported vector argument or return type");
1237 }
1238 
1239 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
1240   for (unsigned i = 0; i < Ins.size(); ++i)
1241     VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
1242 }
1243 
1244 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1245   for (unsigned i = 0; i < Outs.size(); ++i)
1246     VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
1247 }
1248 
1249 // Value is a value that has been passed to us in the location described by VA
1250 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
1251 // any loads onto Chain.
1252 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
1253                                    CCValAssign &VA, SDValue Chain,
1254                                    SDValue Value) {
1255   // If the argument has been promoted from a smaller type, insert an
1256   // assertion to capture this.
1257   if (VA.getLocInfo() == CCValAssign::SExt)
1258     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
1259                         DAG.getValueType(VA.getValVT()));
1260   else if (VA.getLocInfo() == CCValAssign::ZExt)
1261     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
1262                         DAG.getValueType(VA.getValVT()));
1263 
1264   if (VA.isExtInLoc())
1265     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1266   else if (VA.getLocInfo() == CCValAssign::BCvt) {
1267     // If this is a short vector argument loaded from the stack,
1268     // extend from i64 to full vector size and then bitcast.
1269     assert(VA.getLocVT() == MVT::i64);
1270     assert(VA.getValVT().isVector());
1271     Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1272     Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1273   } else
1274     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1275   return Value;
1276 }
1277 
1278 // Value is a value of type VA.getValVT() that we need to copy into
1279 // the location described by VA.  Return a copy of Value converted to
1280 // VA.getValVT().  The caller is responsible for handling indirect values.
1281 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
1282                                    CCValAssign &VA, SDValue Value) {
1283   switch (VA.getLocInfo()) {
1284   case CCValAssign::SExt:
1285     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1286   case CCValAssign::ZExt:
1287     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1288   case CCValAssign::AExt:
1289     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1290   case CCValAssign::BCvt:
1291     // If this is a short vector argument to be stored to the stack,
1292     // bitcast to v2i64 and then extract first element.
1293     assert(VA.getLocVT() == MVT::i64);
1294     assert(VA.getValVT().isVector());
1295     Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
1296     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1297                        DAG.getConstant(0, DL, MVT::i32));
1298   case CCValAssign::Full:
1299     return Value;
1300   default:
1301     llvm_unreachable("Unhandled getLocInfo()");
1302   }
1303 }
1304 
1305 SDValue SystemZTargetLowering::LowerFormalArguments(
1306     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1307     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1308     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1309   MachineFunction &MF = DAG.getMachineFunction();
1310   MachineFrameInfo &MFI = MF.getFrameInfo();
1311   MachineRegisterInfo &MRI = MF.getRegInfo();
1312   SystemZMachineFunctionInfo *FuncInfo =
1313       MF.getInfo<SystemZMachineFunctionInfo>();
1314   auto *TFL =
1315       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
1316   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1317 
1318   // Detect unsupported vector argument types.
1319   if (Subtarget.hasVector())
1320     VerifyVectorTypes(Ins);
1321 
1322   // Assign locations to all of the incoming arguments.
1323   SmallVector<CCValAssign, 16> ArgLocs;
1324   SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1325   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
1326 
1327   unsigned NumFixedGPRs = 0;
1328   unsigned NumFixedFPRs = 0;
1329   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1330     SDValue ArgValue;
1331     CCValAssign &VA = ArgLocs[I];
1332     EVT LocVT = VA.getLocVT();
1333     if (VA.isRegLoc()) {
1334       // Arguments passed in registers
1335       const TargetRegisterClass *RC;
1336       switch (LocVT.getSimpleVT().SimpleTy) {
1337       default:
1338         // Integers smaller than i64 should be promoted to i64.
1339         llvm_unreachable("Unexpected argument type");
1340       case MVT::i32:
1341         NumFixedGPRs += 1;
1342         RC = &SystemZ::GR32BitRegClass;
1343         break;
1344       case MVT::i64:
1345         NumFixedGPRs += 1;
1346         RC = &SystemZ::GR64BitRegClass;
1347         break;
1348       case MVT::f32:
1349         NumFixedFPRs += 1;
1350         RC = &SystemZ::FP32BitRegClass;
1351         break;
1352       case MVT::f64:
1353         NumFixedFPRs += 1;
1354         RC = &SystemZ::FP64BitRegClass;
1355         break;
1356       case MVT::v16i8:
1357       case MVT::v8i16:
1358       case MVT::v4i32:
1359       case MVT::v2i64:
1360       case MVT::v4f32:
1361       case MVT::v2f64:
1362         RC = &SystemZ::VR128BitRegClass;
1363         break;
1364       }
1365 
1366       Register VReg = MRI.createVirtualRegister(RC);
1367       MRI.addLiveIn(VA.getLocReg(), VReg);
1368       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1369     } else {
1370       assert(VA.isMemLoc() && "Argument not register or memory");
1371 
1372       // Create the frame index object for this incoming parameter.
1373       int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1374                                      VA.getLocMemOffset(), true);
1375 
1376       // Create the SelectionDAG nodes corresponding to a load
1377       // from this parameter.  Unpromoted ints and floats are
1378       // passed as right-justified 8-byte values.
1379       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1380       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1381         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1382                           DAG.getIntPtrConstant(4, DL));
1383       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1384                              MachinePointerInfo::getFixedStack(MF, FI));
1385     }
1386 
1387     // Convert the value of the argument register into the value that's
1388     // being passed.
1389     if (VA.getLocInfo() == CCValAssign::Indirect) {
1390       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1391                                    MachinePointerInfo()));
1392       // If the original argument was split (e.g. i128), we need
1393       // to load all parts of it here (using the same address).
1394       unsigned ArgIndex = Ins[I].OrigArgIndex;
1395       assert (Ins[I].PartOffset == 0);
1396       while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1397         CCValAssign &PartVA = ArgLocs[I + 1];
1398         unsigned PartOffset = Ins[I + 1].PartOffset;
1399         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1400                                       DAG.getIntPtrConstant(PartOffset, DL));
1401         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1402                                      MachinePointerInfo()));
1403         ++I;
1404       }
1405     } else
1406       InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1407   }
1408 
1409   if (IsVarArg) {
1410     // Save the number of non-varargs registers for later use by va_start, etc.
1411     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1412     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1413 
1414     // Likewise the address (in the form of a frame index) of where the
1415     // first stack vararg would be.  The 1-byte size here is arbitrary.
1416     int64_t StackSize = CCInfo.getNextStackOffset();
1417     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1418 
1419     // ...and a similar frame index for the caller-allocated save area
1420     // that will be used to store the incoming registers.
1421     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
1422     unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1423     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1424 
1425     // Store the FPR varargs in the reserved frame slots.  (We store the
1426     // GPRs as part of the prologue.)
1427     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
1428       SDValue MemOps[SystemZ::NumArgFPRs];
1429       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1430         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
1431         int FI = MFI.CreateFixedObject(8, RegSaveOffset + Offset, true);
1432         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1433         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1434                                      &SystemZ::FP64BitRegClass);
1435         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1436         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1437                                  MachinePointerInfo::getFixedStack(MF, FI));
1438       }
1439       // Join the stores, which are independent of one another.
1440       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1441                           makeArrayRef(&MemOps[NumFixedFPRs],
1442                                        SystemZ::NumArgFPRs-NumFixedFPRs));
1443     }
1444   }
1445 
1446   return Chain;
1447 }
1448 
1449 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1450                               SmallVectorImpl<CCValAssign> &ArgLocs,
1451                               SmallVectorImpl<ISD::OutputArg> &Outs) {
1452   // Punt if there are any indirect or stack arguments, or if the call
1453   // needs the callee-saved argument register R6, or if the call uses
1454   // the callee-saved register arguments SwiftSelf and SwiftError.
1455   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1456     CCValAssign &VA = ArgLocs[I];
1457     if (VA.getLocInfo() == CCValAssign::Indirect)
1458       return false;
1459     if (!VA.isRegLoc())
1460       return false;
1461     Register Reg = VA.getLocReg();
1462     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1463       return false;
1464     if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1465       return false;
1466   }
1467   return true;
1468 }
1469 
1470 SDValue
1471 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1472                                  SmallVectorImpl<SDValue> &InVals) const {
1473   SelectionDAG &DAG = CLI.DAG;
1474   SDLoc &DL = CLI.DL;
1475   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1476   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1477   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1478   SDValue Chain = CLI.Chain;
1479   SDValue Callee = CLI.Callee;
1480   bool &IsTailCall = CLI.IsTailCall;
1481   CallingConv::ID CallConv = CLI.CallConv;
1482   bool IsVarArg = CLI.IsVarArg;
1483   MachineFunction &MF = DAG.getMachineFunction();
1484   EVT PtrVT = getPointerTy(MF.getDataLayout());
1485 
1486   // Detect unsupported vector argument and return types.
1487   if (Subtarget.hasVector()) {
1488     VerifyVectorTypes(Outs);
1489     VerifyVectorTypes(Ins);
1490   }
1491 
1492   // Analyze the operands of the call, assigning locations to each operand.
1493   SmallVector<CCValAssign, 16> ArgLocs;
1494   SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1495   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1496 
1497   // We don't support GuaranteedTailCallOpt, only automatically-detected
1498   // sibling calls.
1499   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1500     IsTailCall = false;
1501 
1502   // Get a count of how many bytes are to be pushed on the stack.
1503   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1504 
1505   // Mark the start of the call.
1506   if (!IsTailCall)
1507     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1508 
1509   // Copy argument values to their designated locations.
1510   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1511   SmallVector<SDValue, 8> MemOpChains;
1512   SDValue StackPtr;
1513   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1514     CCValAssign &VA = ArgLocs[I];
1515     SDValue ArgValue = OutVals[I];
1516 
1517     if (VA.getLocInfo() == CCValAssign::Indirect) {
1518       // Store the argument in a stack slot and pass its address.
1519       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1520       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1521       MemOpChains.push_back(
1522           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1523                        MachinePointerInfo::getFixedStack(MF, FI)));
1524       // If the original argument was split (e.g. i128), we need
1525       // to store all parts of it here (and pass just one address).
1526       unsigned ArgIndex = Outs[I].OrigArgIndex;
1527       assert (Outs[I].PartOffset == 0);
1528       while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1529         SDValue PartValue = OutVals[I + 1];
1530         unsigned PartOffset = Outs[I + 1].PartOffset;
1531         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1532                                       DAG.getIntPtrConstant(PartOffset, DL));
1533         MemOpChains.push_back(
1534             DAG.getStore(Chain, DL, PartValue, Address,
1535                          MachinePointerInfo::getFixedStack(MF, FI)));
1536         ++I;
1537       }
1538       ArgValue = SpillSlot;
1539     } else
1540       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1541 
1542     if (VA.isRegLoc())
1543       // Queue up the argument copies and emit them at the end.
1544       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1545     else {
1546       assert(VA.isMemLoc() && "Argument not register or memory");
1547 
1548       // Work out the address of the stack slot.  Unpromoted ints and
1549       // floats are passed as right-justified 8-byte values.
1550       if (!StackPtr.getNode())
1551         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1552       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1553       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1554         Offset += 4;
1555       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1556                                     DAG.getIntPtrConstant(Offset, DL));
1557 
1558       // Emit the store.
1559       MemOpChains.push_back(
1560           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1561     }
1562   }
1563 
1564   // Join the stores, which are independent of one another.
1565   if (!MemOpChains.empty())
1566     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1567 
1568   // Accept direct calls by converting symbolic call addresses to the
1569   // associated Target* opcodes.  Force %r1 to be used for indirect
1570   // tail calls.
1571   SDValue Glue;
1572   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1573     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1574     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1575   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1576     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1577     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1578   } else if (IsTailCall) {
1579     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1580     Glue = Chain.getValue(1);
1581     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1582   }
1583 
1584   // Build a sequence of copy-to-reg nodes, chained and glued together.
1585   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1586     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1587                              RegsToPass[I].second, Glue);
1588     Glue = Chain.getValue(1);
1589   }
1590 
1591   // The first call operand is the chain and the second is the target address.
1592   SmallVector<SDValue, 8> Ops;
1593   Ops.push_back(Chain);
1594   Ops.push_back(Callee);
1595 
1596   // Add argument registers to the end of the list so that they are
1597   // known live into the call.
1598   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1599     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1600                                   RegsToPass[I].second.getValueType()));
1601 
1602   // Add a register mask operand representing the call-preserved registers.
1603   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1604   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1605   assert(Mask && "Missing call preserved mask for calling convention");
1606   Ops.push_back(DAG.getRegisterMask(Mask));
1607 
1608   // Glue the call to the argument copies, if any.
1609   if (Glue.getNode())
1610     Ops.push_back(Glue);
1611 
1612   // Emit the call.
1613   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1614   if (IsTailCall)
1615     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1616   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1617   Glue = Chain.getValue(1);
1618 
1619   // Mark the end of the call, which is glued to the call itself.
1620   Chain = DAG.getCALLSEQ_END(Chain,
1621                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1622                              DAG.getConstant(0, DL, PtrVT, true),
1623                              Glue, DL);
1624   Glue = Chain.getValue(1);
1625 
1626   // Assign locations to each value returned by this call.
1627   SmallVector<CCValAssign, 16> RetLocs;
1628   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1629   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1630 
1631   // Copy all of the result registers out of their specified physreg.
1632   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1633     CCValAssign &VA = RetLocs[I];
1634 
1635     // Copy the value out, gluing the copy to the end of the call sequence.
1636     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1637                                           VA.getLocVT(), Glue);
1638     Chain = RetValue.getValue(1);
1639     Glue = RetValue.getValue(2);
1640 
1641     // Convert the value of the return register into the value that's
1642     // being returned.
1643     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1644   }
1645 
1646   return Chain;
1647 }
1648 
1649 bool SystemZTargetLowering::
1650 CanLowerReturn(CallingConv::ID CallConv,
1651                MachineFunction &MF, bool isVarArg,
1652                const SmallVectorImpl<ISD::OutputArg> &Outs,
1653                LLVMContext &Context) const {
1654   // Detect unsupported vector return types.
1655   if (Subtarget.hasVector())
1656     VerifyVectorTypes(Outs);
1657 
1658   // Special case that we cannot easily detect in RetCC_SystemZ since
1659   // i128 is not a legal type.
1660   for (auto &Out : Outs)
1661     if (Out.ArgVT == MVT::i128)
1662       return false;
1663 
1664   SmallVector<CCValAssign, 16> RetLocs;
1665   CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1666   return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1667 }
1668 
1669 SDValue
1670 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1671                                    bool IsVarArg,
1672                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1673                                    const SmallVectorImpl<SDValue> &OutVals,
1674                                    const SDLoc &DL, SelectionDAG &DAG) const {
1675   MachineFunction &MF = DAG.getMachineFunction();
1676 
1677   // Detect unsupported vector return types.
1678   if (Subtarget.hasVector())
1679     VerifyVectorTypes(Outs);
1680 
1681   // Assign locations to each returned value.
1682   SmallVector<CCValAssign, 16> RetLocs;
1683   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1684   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1685 
1686   // Quick exit for void returns
1687   if (RetLocs.empty())
1688     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1689 
1690   if (CallConv == CallingConv::GHC)
1691     report_fatal_error("GHC functions return void only");
1692 
1693   // Copy the result values into the output registers.
1694   SDValue Glue;
1695   SmallVector<SDValue, 4> RetOps;
1696   RetOps.push_back(Chain);
1697   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1698     CCValAssign &VA = RetLocs[I];
1699     SDValue RetValue = OutVals[I];
1700 
1701     // Make the return register live on exit.
1702     assert(VA.isRegLoc() && "Can only return in registers!");
1703 
1704     // Promote the value as required.
1705     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1706 
1707     // Chain and glue the copies together.
1708     Register Reg = VA.getLocReg();
1709     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1710     Glue = Chain.getValue(1);
1711     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1712   }
1713 
1714   // Update chain and glue.
1715   RetOps[0] = Chain;
1716   if (Glue.getNode())
1717     RetOps.push_back(Glue);
1718 
1719   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1720 }
1721 
1722 // Return true if Op is an intrinsic node with chain that returns the CC value
1723 // as its only (other) argument.  Provide the associated SystemZISD opcode and
1724 // the mask of valid CC values if so.
1725 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1726                                       unsigned &CCValid) {
1727   unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1728   switch (Id) {
1729   case Intrinsic::s390_tbegin:
1730     Opcode = SystemZISD::TBEGIN;
1731     CCValid = SystemZ::CCMASK_TBEGIN;
1732     return true;
1733 
1734   case Intrinsic::s390_tbegin_nofloat:
1735     Opcode = SystemZISD::TBEGIN_NOFLOAT;
1736     CCValid = SystemZ::CCMASK_TBEGIN;
1737     return true;
1738 
1739   case Intrinsic::s390_tend:
1740     Opcode = SystemZISD::TEND;
1741     CCValid = SystemZ::CCMASK_TEND;
1742     return true;
1743 
1744   default:
1745     return false;
1746   }
1747 }
1748 
1749 // Return true if Op is an intrinsic node without chain that returns the
1750 // CC value as its final argument.  Provide the associated SystemZISD
1751 // opcode and the mask of valid CC values if so.
1752 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1753   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1754   switch (Id) {
1755   case Intrinsic::s390_vpkshs:
1756   case Intrinsic::s390_vpksfs:
1757   case Intrinsic::s390_vpksgs:
1758     Opcode = SystemZISD::PACKS_CC;
1759     CCValid = SystemZ::CCMASK_VCMP;
1760     return true;
1761 
1762   case Intrinsic::s390_vpklshs:
1763   case Intrinsic::s390_vpklsfs:
1764   case Intrinsic::s390_vpklsgs:
1765     Opcode = SystemZISD::PACKLS_CC;
1766     CCValid = SystemZ::CCMASK_VCMP;
1767     return true;
1768 
1769   case Intrinsic::s390_vceqbs:
1770   case Intrinsic::s390_vceqhs:
1771   case Intrinsic::s390_vceqfs:
1772   case Intrinsic::s390_vceqgs:
1773     Opcode = SystemZISD::VICMPES;
1774     CCValid = SystemZ::CCMASK_VCMP;
1775     return true;
1776 
1777   case Intrinsic::s390_vchbs:
1778   case Intrinsic::s390_vchhs:
1779   case Intrinsic::s390_vchfs:
1780   case Intrinsic::s390_vchgs:
1781     Opcode = SystemZISD::VICMPHS;
1782     CCValid = SystemZ::CCMASK_VCMP;
1783     return true;
1784 
1785   case Intrinsic::s390_vchlbs:
1786   case Intrinsic::s390_vchlhs:
1787   case Intrinsic::s390_vchlfs:
1788   case Intrinsic::s390_vchlgs:
1789     Opcode = SystemZISD::VICMPHLS;
1790     CCValid = SystemZ::CCMASK_VCMP;
1791     return true;
1792 
1793   case Intrinsic::s390_vtm:
1794     Opcode = SystemZISD::VTM;
1795     CCValid = SystemZ::CCMASK_VCMP;
1796     return true;
1797 
1798   case Intrinsic::s390_vfaebs:
1799   case Intrinsic::s390_vfaehs:
1800   case Intrinsic::s390_vfaefs:
1801     Opcode = SystemZISD::VFAE_CC;
1802     CCValid = SystemZ::CCMASK_ANY;
1803     return true;
1804 
1805   case Intrinsic::s390_vfaezbs:
1806   case Intrinsic::s390_vfaezhs:
1807   case Intrinsic::s390_vfaezfs:
1808     Opcode = SystemZISD::VFAEZ_CC;
1809     CCValid = SystemZ::CCMASK_ANY;
1810     return true;
1811 
1812   case Intrinsic::s390_vfeebs:
1813   case Intrinsic::s390_vfeehs:
1814   case Intrinsic::s390_vfeefs:
1815     Opcode = SystemZISD::VFEE_CC;
1816     CCValid = SystemZ::CCMASK_ANY;
1817     return true;
1818 
1819   case Intrinsic::s390_vfeezbs:
1820   case Intrinsic::s390_vfeezhs:
1821   case Intrinsic::s390_vfeezfs:
1822     Opcode = SystemZISD::VFEEZ_CC;
1823     CCValid = SystemZ::CCMASK_ANY;
1824     return true;
1825 
1826   case Intrinsic::s390_vfenebs:
1827   case Intrinsic::s390_vfenehs:
1828   case Intrinsic::s390_vfenefs:
1829     Opcode = SystemZISD::VFENE_CC;
1830     CCValid = SystemZ::CCMASK_ANY;
1831     return true;
1832 
1833   case Intrinsic::s390_vfenezbs:
1834   case Intrinsic::s390_vfenezhs:
1835   case Intrinsic::s390_vfenezfs:
1836     Opcode = SystemZISD::VFENEZ_CC;
1837     CCValid = SystemZ::CCMASK_ANY;
1838     return true;
1839 
1840   case Intrinsic::s390_vistrbs:
1841   case Intrinsic::s390_vistrhs:
1842   case Intrinsic::s390_vistrfs:
1843     Opcode = SystemZISD::VISTR_CC;
1844     CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1845     return true;
1846 
1847   case Intrinsic::s390_vstrcbs:
1848   case Intrinsic::s390_vstrchs:
1849   case Intrinsic::s390_vstrcfs:
1850     Opcode = SystemZISD::VSTRC_CC;
1851     CCValid = SystemZ::CCMASK_ANY;
1852     return true;
1853 
1854   case Intrinsic::s390_vstrczbs:
1855   case Intrinsic::s390_vstrczhs:
1856   case Intrinsic::s390_vstrczfs:
1857     Opcode = SystemZISD::VSTRCZ_CC;
1858     CCValid = SystemZ::CCMASK_ANY;
1859     return true;
1860 
1861   case Intrinsic::s390_vstrsb:
1862   case Intrinsic::s390_vstrsh:
1863   case Intrinsic::s390_vstrsf:
1864     Opcode = SystemZISD::VSTRS_CC;
1865     CCValid = SystemZ::CCMASK_ANY;
1866     return true;
1867 
1868   case Intrinsic::s390_vstrszb:
1869   case Intrinsic::s390_vstrszh:
1870   case Intrinsic::s390_vstrszf:
1871     Opcode = SystemZISD::VSTRSZ_CC;
1872     CCValid = SystemZ::CCMASK_ANY;
1873     return true;
1874 
1875   case Intrinsic::s390_vfcedbs:
1876   case Intrinsic::s390_vfcesbs:
1877     Opcode = SystemZISD::VFCMPES;
1878     CCValid = SystemZ::CCMASK_VCMP;
1879     return true;
1880 
1881   case Intrinsic::s390_vfchdbs:
1882   case Intrinsic::s390_vfchsbs:
1883     Opcode = SystemZISD::VFCMPHS;
1884     CCValid = SystemZ::CCMASK_VCMP;
1885     return true;
1886 
1887   case Intrinsic::s390_vfchedbs:
1888   case Intrinsic::s390_vfchesbs:
1889     Opcode = SystemZISD::VFCMPHES;
1890     CCValid = SystemZ::CCMASK_VCMP;
1891     return true;
1892 
1893   case Intrinsic::s390_vftcidb:
1894   case Intrinsic::s390_vftcisb:
1895     Opcode = SystemZISD::VFTCI;
1896     CCValid = SystemZ::CCMASK_VCMP;
1897     return true;
1898 
1899   case Intrinsic::s390_tdc:
1900     Opcode = SystemZISD::TDC;
1901     CCValid = SystemZ::CCMASK_TDC;
1902     return true;
1903 
1904   default:
1905     return false;
1906   }
1907 }
1908 
1909 // Emit an intrinsic with chain and an explicit CC register result.
1910 static SDNode *emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op,
1911                                            unsigned Opcode) {
1912   // Copy all operands except the intrinsic ID.
1913   unsigned NumOps = Op.getNumOperands();
1914   SmallVector<SDValue, 6> Ops;
1915   Ops.reserve(NumOps - 1);
1916   Ops.push_back(Op.getOperand(0));
1917   for (unsigned I = 2; I < NumOps; ++I)
1918     Ops.push_back(Op.getOperand(I));
1919 
1920   assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1921   SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
1922   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1923   SDValue OldChain = SDValue(Op.getNode(), 1);
1924   SDValue NewChain = SDValue(Intr.getNode(), 1);
1925   DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1926   return Intr.getNode();
1927 }
1928 
1929 // Emit an intrinsic with an explicit CC register result.
1930 static SDNode *emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op,
1931                                    unsigned Opcode) {
1932   // Copy all operands except the intrinsic ID.
1933   unsigned NumOps = Op.getNumOperands();
1934   SmallVector<SDValue, 6> Ops;
1935   Ops.reserve(NumOps - 1);
1936   for (unsigned I = 1; I < NumOps; ++I)
1937     Ops.push_back(Op.getOperand(I));
1938 
1939   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops);
1940   return Intr.getNode();
1941 }
1942 
1943 // CC is a comparison that will be implemented using an integer or
1944 // floating-point comparison.  Return the condition code mask for
1945 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
1946 // unsigned comparisons and clear for signed ones.  In the floating-point
1947 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1948 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1949 #define CONV(X) \
1950   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1951   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1952   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1953 
1954   switch (CC) {
1955   default:
1956     llvm_unreachable("Invalid integer condition!");
1957 
1958   CONV(EQ);
1959   CONV(NE);
1960   CONV(GT);
1961   CONV(GE);
1962   CONV(LT);
1963   CONV(LE);
1964 
1965   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
1966   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1967   }
1968 #undef CONV
1969 }
1970 
1971 // If C can be converted to a comparison against zero, adjust the operands
1972 // as necessary.
1973 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
1974   if (C.ICmpType == SystemZICMP::UnsignedOnly)
1975     return;
1976 
1977   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1978   if (!ConstOp1)
1979     return;
1980 
1981   int64_t Value = ConstOp1->getSExtValue();
1982   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1983       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1984       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1985       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1986     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1987     C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1988   }
1989 }
1990 
1991 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1992 // adjust the operands as necessary.
1993 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
1994                              Comparison &C) {
1995   // For us to make any changes, it must a comparison between a single-use
1996   // load and a constant.
1997   if (!C.Op0.hasOneUse() ||
1998       C.Op0.getOpcode() != ISD::LOAD ||
1999       C.Op1.getOpcode() != ISD::Constant)
2000     return;
2001 
2002   // We must have an 8- or 16-bit load.
2003   auto *Load = cast<LoadSDNode>(C.Op0);
2004   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
2005   if (NumBits != 8 && NumBits != 16)
2006     return;
2007 
2008   // The load must be an extending one and the constant must be within the
2009   // range of the unextended value.
2010   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2011   uint64_t Value = ConstOp1->getZExtValue();
2012   uint64_t Mask = (1 << NumBits) - 1;
2013   if (Load->getExtensionType() == ISD::SEXTLOAD) {
2014     // Make sure that ConstOp1 is in range of C.Op0.
2015     int64_t SignedValue = ConstOp1->getSExtValue();
2016     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
2017       return;
2018     if (C.ICmpType != SystemZICMP::SignedOnly) {
2019       // Unsigned comparison between two sign-extended values is equivalent
2020       // to unsigned comparison between two zero-extended values.
2021       Value &= Mask;
2022     } else if (NumBits == 8) {
2023       // Try to treat the comparison as unsigned, so that we can use CLI.
2024       // Adjust CCMask and Value as necessary.
2025       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
2026         // Test whether the high bit of the byte is set.
2027         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
2028       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
2029         // Test whether the high bit of the byte is clear.
2030         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
2031       else
2032         // No instruction exists for this combination.
2033         return;
2034       C.ICmpType = SystemZICMP::UnsignedOnly;
2035     }
2036   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
2037     if (Value > Mask)
2038       return;
2039     // If the constant is in range, we can use any comparison.
2040     C.ICmpType = SystemZICMP::Any;
2041   } else
2042     return;
2043 
2044   // Make sure that the first operand is an i32 of the right extension type.
2045   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
2046                               ISD::SEXTLOAD :
2047                               ISD::ZEXTLOAD);
2048   if (C.Op0.getValueType() != MVT::i32 ||
2049       Load->getExtensionType() != ExtType) {
2050     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
2051                            Load->getBasePtr(), Load->getPointerInfo(),
2052                            Load->getMemoryVT(), Load->getAlignment(),
2053                            Load->getMemOperand()->getFlags());
2054     // Update the chain uses.
2055     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
2056   }
2057 
2058   // Make sure that the second operand is an i32 with the right value.
2059   if (C.Op1.getValueType() != MVT::i32 ||
2060       Value != ConstOp1->getZExtValue())
2061     C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
2062 }
2063 
2064 // Return true if Op is either an unextended load, or a load suitable
2065 // for integer register-memory comparisons of type ICmpType.
2066 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
2067   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
2068   if (Load) {
2069     // There are no instructions to compare a register with a memory byte.
2070     if (Load->getMemoryVT() == MVT::i8)
2071       return false;
2072     // Otherwise decide on extension type.
2073     switch (Load->getExtensionType()) {
2074     case ISD::NON_EXTLOAD:
2075       return true;
2076     case ISD::SEXTLOAD:
2077       return ICmpType != SystemZICMP::UnsignedOnly;
2078     case ISD::ZEXTLOAD:
2079       return ICmpType != SystemZICMP::SignedOnly;
2080     default:
2081       break;
2082     }
2083   }
2084   return false;
2085 }
2086 
2087 // Return true if it is better to swap the operands of C.
2088 static bool shouldSwapCmpOperands(const Comparison &C) {
2089   // Leave f128 comparisons alone, since they have no memory forms.
2090   if (C.Op0.getValueType() == MVT::f128)
2091     return false;
2092 
2093   // Always keep a floating-point constant second, since comparisons with
2094   // zero can use LOAD TEST and comparisons with other constants make a
2095   // natural memory operand.
2096   if (isa<ConstantFPSDNode>(C.Op1))
2097     return false;
2098 
2099   // Never swap comparisons with zero since there are many ways to optimize
2100   // those later.
2101   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2102   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
2103     return false;
2104 
2105   // Also keep natural memory operands second if the loaded value is
2106   // only used here.  Several comparisons have memory forms.
2107   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
2108     return false;
2109 
2110   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
2111   // In that case we generally prefer the memory to be second.
2112   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
2113     // The only exceptions are when the second operand is a constant and
2114     // we can use things like CHHSI.
2115     if (!ConstOp1)
2116       return true;
2117     // The unsigned memory-immediate instructions can handle 16-bit
2118     // unsigned integers.
2119     if (C.ICmpType != SystemZICMP::SignedOnly &&
2120         isUInt<16>(ConstOp1->getZExtValue()))
2121       return false;
2122     // The signed memory-immediate instructions can handle 16-bit
2123     // signed integers.
2124     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
2125         isInt<16>(ConstOp1->getSExtValue()))
2126       return false;
2127     return true;
2128   }
2129 
2130   // Try to promote the use of CGFR and CLGFR.
2131   unsigned Opcode0 = C.Op0.getOpcode();
2132   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
2133     return true;
2134   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
2135     return true;
2136   if (C.ICmpType != SystemZICMP::SignedOnly &&
2137       Opcode0 == ISD::AND &&
2138       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
2139       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
2140     return true;
2141 
2142   return false;
2143 }
2144 
2145 // Return a version of comparison CC mask CCMask in which the LT and GT
2146 // actions are swapped.
2147 static unsigned reverseCCMask(unsigned CCMask) {
2148   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
2149           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
2150           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
2151           (CCMask & SystemZ::CCMASK_CMP_UO));
2152 }
2153 
2154 // Check whether C tests for equality between X and Y and whether X - Y
2155 // or Y - X is also computed.  In that case it's better to compare the
2156 // result of the subtraction against zero.
2157 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
2158                                  Comparison &C) {
2159   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2160       C.CCMask == SystemZ::CCMASK_CMP_NE) {
2161     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
2162       SDNode *N = *I;
2163       if (N->getOpcode() == ISD::SUB &&
2164           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
2165            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
2166         C.Op0 = SDValue(N, 0);
2167         C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
2168         return;
2169       }
2170     }
2171   }
2172 }
2173 
2174 // Check whether C compares a floating-point value with zero and if that
2175 // floating-point value is also negated.  In this case we can use the
2176 // negation to set CC, so avoiding separate LOAD AND TEST and
2177 // LOAD (NEGATIVE/COMPLEMENT) instructions.
2178 static void adjustForFNeg(Comparison &C) {
2179   // This optimization is invalid for strict comparisons, since FNEG
2180   // does not raise any exceptions.
2181   if (C.Chain)
2182     return;
2183   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
2184   if (C1 && C1->isZero()) {
2185     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
2186       SDNode *N = *I;
2187       if (N->getOpcode() == ISD::FNEG) {
2188         C.Op0 = SDValue(N, 0);
2189         C.CCMask = reverseCCMask(C.CCMask);
2190         return;
2191       }
2192     }
2193   }
2194 }
2195 
2196 // Check whether C compares (shl X, 32) with 0 and whether X is
2197 // also sign-extended.  In that case it is better to test the result
2198 // of the sign extension using LTGFR.
2199 //
2200 // This case is important because InstCombine transforms a comparison
2201 // with (sext (trunc X)) into a comparison with (shl X, 32).
2202 static void adjustForLTGFR(Comparison &C) {
2203   // Check for a comparison between (shl X, 32) and 0.
2204   if (C.Op0.getOpcode() == ISD::SHL &&
2205       C.Op0.getValueType() == MVT::i64 &&
2206       C.Op1.getOpcode() == ISD::Constant &&
2207       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2208     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2209     if (C1 && C1->getZExtValue() == 32) {
2210       SDValue ShlOp0 = C.Op0.getOperand(0);
2211       // See whether X has any SIGN_EXTEND_INREG uses.
2212       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
2213         SDNode *N = *I;
2214         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
2215             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
2216           C.Op0 = SDValue(N, 0);
2217           return;
2218         }
2219       }
2220     }
2221   }
2222 }
2223 
2224 // If C compares the truncation of an extending load, try to compare
2225 // the untruncated value instead.  This exposes more opportunities to
2226 // reuse CC.
2227 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
2228                                Comparison &C) {
2229   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
2230       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
2231       C.Op1.getOpcode() == ISD::Constant &&
2232       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2233     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
2234     if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) {
2235       unsigned Type = L->getExtensionType();
2236       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
2237           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
2238         C.Op0 = C.Op0.getOperand(0);
2239         C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
2240       }
2241     }
2242   }
2243 }
2244 
2245 // Return true if shift operation N has an in-range constant shift value.
2246 // Store it in ShiftVal if so.
2247 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
2248   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
2249   if (!Shift)
2250     return false;
2251 
2252   uint64_t Amount = Shift->getZExtValue();
2253   if (Amount >= N.getValueSizeInBits())
2254     return false;
2255 
2256   ShiftVal = Amount;
2257   return true;
2258 }
2259 
2260 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
2261 // instruction and whether the CC value is descriptive enough to handle
2262 // a comparison of type Opcode between the AND result and CmpVal.
2263 // CCMask says which comparison result is being tested and BitSize is
2264 // the number of bits in the operands.  If TEST UNDER MASK can be used,
2265 // return the corresponding CC mask, otherwise return 0.
2266 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
2267                                      uint64_t Mask, uint64_t CmpVal,
2268                                      unsigned ICmpType) {
2269   assert(Mask != 0 && "ANDs with zero should have been removed by now");
2270 
2271   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
2272   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
2273       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
2274     return 0;
2275 
2276   // Work out the masks for the lowest and highest bits.
2277   unsigned HighShift = 63 - countLeadingZeros(Mask);
2278   uint64_t High = uint64_t(1) << HighShift;
2279   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
2280 
2281   // Signed ordered comparisons are effectively unsigned if the sign
2282   // bit is dropped.
2283   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
2284 
2285   // Check for equality comparisons with 0, or the equivalent.
2286   if (CmpVal == 0) {
2287     if (CCMask == SystemZ::CCMASK_CMP_EQ)
2288       return SystemZ::CCMASK_TM_ALL_0;
2289     if (CCMask == SystemZ::CCMASK_CMP_NE)
2290       return SystemZ::CCMASK_TM_SOME_1;
2291   }
2292   if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2293     if (CCMask == SystemZ::CCMASK_CMP_LT)
2294       return SystemZ::CCMASK_TM_ALL_0;
2295     if (CCMask == SystemZ::CCMASK_CMP_GE)
2296       return SystemZ::CCMASK_TM_SOME_1;
2297   }
2298   if (EffectivelyUnsigned && CmpVal < Low) {
2299     if (CCMask == SystemZ::CCMASK_CMP_LE)
2300       return SystemZ::CCMASK_TM_ALL_0;
2301     if (CCMask == SystemZ::CCMASK_CMP_GT)
2302       return SystemZ::CCMASK_TM_SOME_1;
2303   }
2304 
2305   // Check for equality comparisons with the mask, or the equivalent.
2306   if (CmpVal == Mask) {
2307     if (CCMask == SystemZ::CCMASK_CMP_EQ)
2308       return SystemZ::CCMASK_TM_ALL_1;
2309     if (CCMask == SystemZ::CCMASK_CMP_NE)
2310       return SystemZ::CCMASK_TM_SOME_0;
2311   }
2312   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2313     if (CCMask == SystemZ::CCMASK_CMP_GT)
2314       return SystemZ::CCMASK_TM_ALL_1;
2315     if (CCMask == SystemZ::CCMASK_CMP_LE)
2316       return SystemZ::CCMASK_TM_SOME_0;
2317   }
2318   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2319     if (CCMask == SystemZ::CCMASK_CMP_GE)
2320       return SystemZ::CCMASK_TM_ALL_1;
2321     if (CCMask == SystemZ::CCMASK_CMP_LT)
2322       return SystemZ::CCMASK_TM_SOME_0;
2323   }
2324 
2325   // Check for ordered comparisons with the top bit.
2326   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2327     if (CCMask == SystemZ::CCMASK_CMP_LE)
2328       return SystemZ::CCMASK_TM_MSB_0;
2329     if (CCMask == SystemZ::CCMASK_CMP_GT)
2330       return SystemZ::CCMASK_TM_MSB_1;
2331   }
2332   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2333     if (CCMask == SystemZ::CCMASK_CMP_LT)
2334       return SystemZ::CCMASK_TM_MSB_0;
2335     if (CCMask == SystemZ::CCMASK_CMP_GE)
2336       return SystemZ::CCMASK_TM_MSB_1;
2337   }
2338 
2339   // If there are just two bits, we can do equality checks for Low and High
2340   // as well.
2341   if (Mask == Low + High) {
2342     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2343       return SystemZ::CCMASK_TM_MIXED_MSB_0;
2344     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2345       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
2346     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2347       return SystemZ::CCMASK_TM_MIXED_MSB_1;
2348     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2349       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
2350   }
2351 
2352   // Looks like we've exhausted our options.
2353   return 0;
2354 }
2355 
2356 // See whether C can be implemented as a TEST UNDER MASK instruction.
2357 // Update the arguments with the TM version if so.
2358 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2359                                    Comparison &C) {
2360   // Check that we have a comparison with a constant.
2361   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2362   if (!ConstOp1)
2363     return;
2364   uint64_t CmpVal = ConstOp1->getZExtValue();
2365 
2366   // Check whether the nonconstant input is an AND with a constant mask.
2367   Comparison NewC(C);
2368   uint64_t MaskVal;
2369   ConstantSDNode *Mask = nullptr;
2370   if (C.Op0.getOpcode() == ISD::AND) {
2371     NewC.Op0 = C.Op0.getOperand(0);
2372     NewC.Op1 = C.Op0.getOperand(1);
2373     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2374     if (!Mask)
2375       return;
2376     MaskVal = Mask->getZExtValue();
2377   } else {
2378     // There is no instruction to compare with a 64-bit immediate
2379     // so use TMHH instead if possible.  We need an unsigned ordered
2380     // comparison with an i64 immediate.
2381     if (NewC.Op0.getValueType() != MVT::i64 ||
2382         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2383         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2384         NewC.ICmpType == SystemZICMP::SignedOnly)
2385       return;
2386     // Convert LE and GT comparisons into LT and GE.
2387     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2388         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2389       if (CmpVal == uint64_t(-1))
2390         return;
2391       CmpVal += 1;
2392       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2393     }
2394     // If the low N bits of Op1 are zero than the low N bits of Op0 can
2395     // be masked off without changing the result.
2396     MaskVal = -(CmpVal & -CmpVal);
2397     NewC.ICmpType = SystemZICMP::UnsignedOnly;
2398   }
2399   if (!MaskVal)
2400     return;
2401 
2402   // Check whether the combination of mask, comparison value and comparison
2403   // type are suitable.
2404   unsigned BitSize = NewC.Op0.getValueSizeInBits();
2405   unsigned NewCCMask, ShiftVal;
2406   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2407       NewC.Op0.getOpcode() == ISD::SHL &&
2408       isSimpleShift(NewC.Op0, ShiftVal) &&
2409       (MaskVal >> ShiftVal != 0) &&
2410       ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
2411       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2412                                         MaskVal >> ShiftVal,
2413                                         CmpVal >> ShiftVal,
2414                                         SystemZICMP::Any))) {
2415     NewC.Op0 = NewC.Op0.getOperand(0);
2416     MaskVal >>= ShiftVal;
2417   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2418              NewC.Op0.getOpcode() == ISD::SRL &&
2419              isSimpleShift(NewC.Op0, ShiftVal) &&
2420              (MaskVal << ShiftVal != 0) &&
2421              ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
2422              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2423                                                MaskVal << ShiftVal,
2424                                                CmpVal << ShiftVal,
2425                                                SystemZICMP::UnsignedOnly))) {
2426     NewC.Op0 = NewC.Op0.getOperand(0);
2427     MaskVal <<= ShiftVal;
2428   } else {
2429     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2430                                      NewC.ICmpType);
2431     if (!NewCCMask)
2432       return;
2433   }
2434 
2435   // Go ahead and make the change.
2436   C.Opcode = SystemZISD::TM;
2437   C.Op0 = NewC.Op0;
2438   if (Mask && Mask->getZExtValue() == MaskVal)
2439     C.Op1 = SDValue(Mask, 0);
2440   else
2441     C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2442   C.CCValid = SystemZ::CCMASK_TM;
2443   C.CCMask = NewCCMask;
2444 }
2445 
2446 // See whether the comparison argument contains a redundant AND
2447 // and remove it if so.  This sometimes happens due to the generic
2448 // BRCOND expansion.
2449 static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL,
2450                                   Comparison &C) {
2451   if (C.Op0.getOpcode() != ISD::AND)
2452     return;
2453   auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2454   if (!Mask)
2455     return;
2456   KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
2457   if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
2458     return;
2459 
2460   C.Op0 = C.Op0.getOperand(0);
2461 }
2462 
2463 // Return a Comparison that tests the condition-code result of intrinsic
2464 // node Call against constant integer CC using comparison code Cond.
2465 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2466 // and CCValid is the set of possible condition-code results.
2467 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2468                                   SDValue Call, unsigned CCValid, uint64_t CC,
2469                                   ISD::CondCode Cond) {
2470   Comparison C(Call, SDValue(), SDValue());
2471   C.Opcode = Opcode;
2472   C.CCValid = CCValid;
2473   if (Cond == ISD::SETEQ)
2474     // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2475     C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2476   else if (Cond == ISD::SETNE)
2477     // ...and the inverse of that.
2478     C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2479   else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2480     // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2481     // always true for CC>3.
2482     C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2483   else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2484     // ...and the inverse of that.
2485     C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2486   else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2487     // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2488     // always true for CC>3.
2489     C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2490   else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2491     // ...and the inverse of that.
2492     C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2493   else
2494     llvm_unreachable("Unexpected integer comparison type");
2495   C.CCMask &= CCValid;
2496   return C;
2497 }
2498 
2499 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2500 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2501                          ISD::CondCode Cond, const SDLoc &DL,
2502                          SDValue Chain = SDValue(),
2503                          bool IsSignaling = false) {
2504   if (CmpOp1.getOpcode() == ISD::Constant) {
2505     assert(!Chain);
2506     uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2507     unsigned Opcode, CCValid;
2508     if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2509         CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2510         isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2511       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2512     if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2513         CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2514         isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2515       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2516   }
2517   Comparison C(CmpOp0, CmpOp1, Chain);
2518   C.CCMask = CCMaskForCondCode(Cond);
2519   if (C.Op0.getValueType().isFloatingPoint()) {
2520     C.CCValid = SystemZ::CCMASK_FCMP;
2521     if (!C.Chain)
2522       C.Opcode = SystemZISD::FCMP;
2523     else if (!IsSignaling)
2524       C.Opcode = SystemZISD::STRICT_FCMP;
2525     else
2526       C.Opcode = SystemZISD::STRICT_FCMPS;
2527     adjustForFNeg(C);
2528   } else {
2529     assert(!C.Chain);
2530     C.CCValid = SystemZ::CCMASK_ICMP;
2531     C.Opcode = SystemZISD::ICMP;
2532     // Choose the type of comparison.  Equality and inequality tests can
2533     // use either signed or unsigned comparisons.  The choice also doesn't
2534     // matter if both sign bits are known to be clear.  In those cases we
2535     // want to give the main isel code the freedom to choose whichever
2536     // form fits best.
2537     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2538         C.CCMask == SystemZ::CCMASK_CMP_NE ||
2539         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2540       C.ICmpType = SystemZICMP::Any;
2541     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2542       C.ICmpType = SystemZICMP::UnsignedOnly;
2543     else
2544       C.ICmpType = SystemZICMP::SignedOnly;
2545     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2546     adjustForRedundantAnd(DAG, DL, C);
2547     adjustZeroCmp(DAG, DL, C);
2548     adjustSubwordCmp(DAG, DL, C);
2549     adjustForSubtraction(DAG, DL, C);
2550     adjustForLTGFR(C);
2551     adjustICmpTruncate(DAG, DL, C);
2552   }
2553 
2554   if (shouldSwapCmpOperands(C)) {
2555     std::swap(C.Op0, C.Op1);
2556     C.CCMask = reverseCCMask(C.CCMask);
2557   }
2558 
2559   adjustForTestUnderMask(DAG, DL, C);
2560   return C;
2561 }
2562 
2563 // Emit the comparison instruction described by C.
2564 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2565   if (!C.Op1.getNode()) {
2566     SDNode *Node;
2567     switch (C.Op0.getOpcode()) {
2568     case ISD::INTRINSIC_W_CHAIN:
2569       Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
2570       return SDValue(Node, 0);
2571     case ISD::INTRINSIC_WO_CHAIN:
2572       Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
2573       return SDValue(Node, Node->getNumValues() - 1);
2574     default:
2575       llvm_unreachable("Invalid comparison operands");
2576     }
2577   }
2578   if (C.Opcode == SystemZISD::ICMP)
2579     return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
2580                        DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
2581   if (C.Opcode == SystemZISD::TM) {
2582     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2583                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2584     return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
2585                        DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
2586   }
2587   if (C.Chain) {
2588     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
2589     return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
2590   }
2591   return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
2592 }
2593 
2594 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2595 // 64 bits.  Extend is the extension type to use.  Store the high part
2596 // in Hi and the low part in Lo.
2597 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2598                             SDValue Op0, SDValue Op1, SDValue &Hi,
2599                             SDValue &Lo) {
2600   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2601   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2602   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2603   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2604                    DAG.getConstant(32, DL, MVT::i64));
2605   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2606   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2607 }
2608 
2609 // Lower a binary operation that produces two VT results, one in each
2610 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
2611 // and Opcode performs the GR128 operation.  Store the even register result
2612 // in Even and the odd register result in Odd.
2613 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2614                              unsigned Opcode, SDValue Op0, SDValue Op1,
2615                              SDValue &Even, SDValue &Odd) {
2616   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
2617   bool Is32Bit = is32Bit(VT);
2618   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2619   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2620 }
2621 
2622 // Return an i32 value that is 1 if the CC value produced by CCReg is
2623 // in the mask CCMask and 0 otherwise.  CC is known to have a value
2624 // in CCValid, so other values can be ignored.
2625 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
2626                          unsigned CCValid, unsigned CCMask) {
2627   SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
2628                    DAG.getConstant(0, DL, MVT::i32),
2629                    DAG.getTargetConstant(CCValid, DL, MVT::i32),
2630                    DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
2631   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
2632 }
2633 
2634 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2635 // be done directly.  Mode is CmpMode::Int for integer comparisons, CmpMode::FP
2636 // for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
2637 // floating-point comparisons, and CmpMode::SignalingFP for strict signaling
2638 // floating-point comparisons.
2639 enum class CmpMode { Int, FP, StrictFP, SignalingFP };
2640 static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode) {
2641   switch (CC) {
2642   case ISD::SETOEQ:
2643   case ISD::SETEQ:
2644     switch (Mode) {
2645     case CmpMode::Int:         return SystemZISD::VICMPE;
2646     case CmpMode::FP:          return SystemZISD::VFCMPE;
2647     case CmpMode::StrictFP:    return SystemZISD::STRICT_VFCMPE;
2648     case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
2649     }
2650     llvm_unreachable("Bad mode");
2651 
2652   case ISD::SETOGE:
2653   case ISD::SETGE:
2654     switch (Mode) {
2655     case CmpMode::Int:         return 0;
2656     case CmpMode::FP:          return SystemZISD::VFCMPHE;
2657     case CmpMode::StrictFP:    return SystemZISD::STRICT_VFCMPHE;
2658     case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
2659     }
2660     llvm_unreachable("Bad mode");
2661 
2662   case ISD::SETOGT:
2663   case ISD::SETGT:
2664     switch (Mode) {
2665     case CmpMode::Int:         return SystemZISD::VICMPH;
2666     case CmpMode::FP:          return SystemZISD::VFCMPH;
2667     case CmpMode::StrictFP:    return SystemZISD::STRICT_VFCMPH;
2668     case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
2669     }
2670     llvm_unreachable("Bad mode");
2671 
2672   case ISD::SETUGT:
2673     switch (Mode) {
2674     case CmpMode::Int:         return SystemZISD::VICMPHL;
2675     case CmpMode::FP:          return 0;
2676     case CmpMode::StrictFP:    return 0;
2677     case CmpMode::SignalingFP: return 0;
2678     }
2679     llvm_unreachable("Bad mode");
2680 
2681   default:
2682     return 0;
2683   }
2684 }
2685 
2686 // Return the SystemZISD vector comparison operation for CC or its inverse,
2687 // or 0 if neither can be done directly.  Indicate in Invert whether the
2688 // result is for the inverse of CC.  Mode is as above.
2689 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode,
2690                                             bool &Invert) {
2691   if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2692     Invert = false;
2693     return Opcode;
2694   }
2695 
2696   CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int);
2697   if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2698     Invert = true;
2699     return Opcode;
2700   }
2701 
2702   return 0;
2703 }
2704 
2705 // Return a v2f64 that contains the extended form of elements Start and Start+1
2706 // of v4f32 value Op.  If Chain is nonnull, return the strict form.
2707 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2708                                   SDValue Op, SDValue Chain) {
2709   int Mask[] = { Start, -1, Start + 1, -1 };
2710   Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2711   if (Chain) {
2712     SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
2713     return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
2714   }
2715   return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2716 }
2717 
2718 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2719 // producing a result of type VT.  If Chain is nonnull, return the strict form.
2720 SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
2721                                             const SDLoc &DL, EVT VT,
2722                                             SDValue CmpOp0,
2723                                             SDValue CmpOp1,
2724                                             SDValue Chain) const {
2725   // There is no hardware support for v4f32 (unless we have the vector
2726   // enhancements facility 1), so extend the vector into two v2f64s
2727   // and compare those.
2728   if (CmpOp0.getValueType() == MVT::v4f32 &&
2729       !Subtarget.hasVectorEnhancements1()) {
2730     SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
2731     SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
2732     SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
2733     SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
2734     if (Chain) {
2735       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
2736       SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
2737       SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
2738       SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2739       SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
2740                             H1.getValue(1), L1.getValue(1),
2741                             HRes.getValue(1), LRes.getValue(1) };
2742       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2743       SDValue Ops[2] = { Res, NewChain };
2744       return DAG.getMergeValues(Ops, DL);
2745     }
2746     SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2747     SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2748     return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2749   }
2750   if (Chain) {
2751     SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2752     return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
2753   }
2754   return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2755 }
2756 
2757 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2758 // an integer mask of type VT.  If Chain is nonnull, we have a strict
2759 // floating-point comparison.  If in addition IsSignaling is true, we have
2760 // a strict signaling floating-point comparison.
2761 SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
2762                                                 const SDLoc &DL, EVT VT,
2763                                                 ISD::CondCode CC,
2764                                                 SDValue CmpOp0,
2765                                                 SDValue CmpOp1,
2766                                                 SDValue Chain,
2767                                                 bool IsSignaling) const {
2768   bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2769   assert (!Chain || IsFP);
2770   assert (!IsSignaling || Chain);
2771   CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
2772                  Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
2773   bool Invert = false;
2774   SDValue Cmp;
2775   switch (CC) {
2776     // Handle tests for order using (or (ogt y x) (oge x y)).
2777   case ISD::SETUO:
2778     Invert = true;
2779     LLVM_FALLTHROUGH;
2780   case ISD::SETO: {
2781     assert(IsFP && "Unexpected integer comparison");
2782     SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2783                               DL, VT, CmpOp1, CmpOp0, Chain);
2784     SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
2785                               DL, VT, CmpOp0, CmpOp1, Chain);
2786     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2787     if (Chain)
2788       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2789                           LT.getValue(1), GE.getValue(1));
2790     break;
2791   }
2792 
2793     // Handle <> tests using (or (ogt y x) (ogt x y)).
2794   case ISD::SETUEQ:
2795     Invert = true;
2796     LLVM_FALLTHROUGH;
2797   case ISD::SETONE: {
2798     assert(IsFP && "Unexpected integer comparison");
2799     SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2800                               DL, VT, CmpOp1, CmpOp0, Chain);
2801     SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2802                               DL, VT, CmpOp0, CmpOp1, Chain);
2803     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2804     if (Chain)
2805       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2806                           LT.getValue(1), GT.getValue(1));
2807     break;
2808   }
2809 
2810     // Otherwise a single comparison is enough.  It doesn't really
2811     // matter whether we try the inversion or the swap first, since
2812     // there are no cases where both work.
2813   default:
2814     if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
2815       Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
2816     else {
2817       CC = ISD::getSetCCSwappedOperands(CC);
2818       if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
2819         Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
2820       else
2821         llvm_unreachable("Unhandled comparison");
2822     }
2823     if (Chain)
2824       Chain = Cmp.getValue(1);
2825     break;
2826   }
2827   if (Invert) {
2828     SDValue Mask =
2829       DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64));
2830     Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2831   }
2832   if (Chain && Chain.getNode() != Cmp.getNode()) {
2833     SDValue Ops[2] = { Cmp, Chain };
2834     Cmp = DAG.getMergeValues(Ops, DL);
2835   }
2836   return Cmp;
2837 }
2838 
2839 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2840                                           SelectionDAG &DAG) const {
2841   SDValue CmpOp0   = Op.getOperand(0);
2842   SDValue CmpOp1   = Op.getOperand(1);
2843   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2844   SDLoc DL(Op);
2845   EVT VT = Op.getValueType();
2846   if (VT.isVector())
2847     return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2848 
2849   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2850   SDValue CCReg = emitCmp(DAG, DL, C);
2851   return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
2852 }
2853 
2854 SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
2855                                                   SelectionDAG &DAG,
2856                                                   bool IsSignaling) const {
2857   SDValue Chain    = Op.getOperand(0);
2858   SDValue CmpOp0   = Op.getOperand(1);
2859   SDValue CmpOp1   = Op.getOperand(2);
2860   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
2861   SDLoc DL(Op);
2862   EVT VT = Op.getNode()->getValueType(0);
2863   if (VT.isVector()) {
2864     SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
2865                                    Chain, IsSignaling);
2866     return Res.getValue(Op.getResNo());
2867   }
2868 
2869   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
2870   SDValue CCReg = emitCmp(DAG, DL, C);
2871   CCReg->setFlags(Op->getFlags());
2872   SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
2873   SDValue Ops[2] = { Result, CCReg.getValue(1) };
2874   return DAG.getMergeValues(Ops, DL);
2875 }
2876 
2877 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2878   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2879   SDValue CmpOp0   = Op.getOperand(2);
2880   SDValue CmpOp1   = Op.getOperand(3);
2881   SDValue Dest     = Op.getOperand(4);
2882   SDLoc DL(Op);
2883 
2884   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2885   SDValue CCReg = emitCmp(DAG, DL, C);
2886   return DAG.getNode(
2887       SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
2888       DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
2889       DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
2890 }
2891 
2892 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2893 // allowing Pos and Neg to be wider than CmpOp.
2894 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2895   return (Neg.getOpcode() == ISD::SUB &&
2896           Neg.getOperand(0).getOpcode() == ISD::Constant &&
2897           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2898           Neg.getOperand(1) == Pos &&
2899           (Pos == CmpOp ||
2900            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2901             Pos.getOperand(0) == CmpOp)));
2902 }
2903 
2904 // Return the absolute or negative absolute of Op; IsNegative decides which.
2905 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2906                            bool IsNegative) {
2907   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2908   if (IsNegative)
2909     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2910                      DAG.getConstant(0, DL, Op.getValueType()), Op);
2911   return Op;
2912 }
2913 
2914 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2915                                               SelectionDAG &DAG) const {
2916   SDValue CmpOp0   = Op.getOperand(0);
2917   SDValue CmpOp1   = Op.getOperand(1);
2918   SDValue TrueOp   = Op.getOperand(2);
2919   SDValue FalseOp  = Op.getOperand(3);
2920   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2921   SDLoc DL(Op);
2922 
2923   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2924 
2925   // Check for absolute and negative-absolute selections, including those
2926   // where the comparison value is sign-extended (for LPGFR and LNGFR).
2927   // This check supplements the one in DAGCombiner.
2928   if (C.Opcode == SystemZISD::ICMP &&
2929       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2930       C.CCMask != SystemZ::CCMASK_CMP_NE &&
2931       C.Op1.getOpcode() == ISD::Constant &&
2932       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2933     if (isAbsolute(C.Op0, TrueOp, FalseOp))
2934       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2935     if (isAbsolute(C.Op0, FalseOp, TrueOp))
2936       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2937   }
2938 
2939   SDValue CCReg = emitCmp(DAG, DL, C);
2940   SDValue Ops[] = {TrueOp, FalseOp,
2941                    DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
2942                    DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
2943 
2944   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
2945 }
2946 
2947 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2948                                                   SelectionDAG &DAG) const {
2949   SDLoc DL(Node);
2950   const GlobalValue *GV = Node->getGlobal();
2951   int64_t Offset = Node->getOffset();
2952   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2953   CodeModel::Model CM = DAG.getTarget().getCodeModel();
2954 
2955   SDValue Result;
2956   if (Subtarget.isPC32DBLSymbol(GV, CM)) {
2957     if (isInt<32>(Offset)) {
2958       // Assign anchors at 1<<12 byte boundaries.
2959       uint64_t Anchor = Offset & ~uint64_t(0xfff);
2960       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2961       Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2962 
2963       // The offset can be folded into the address if it is aligned to a
2964       // halfword.
2965       Offset -= Anchor;
2966       if (Offset != 0 && (Offset & 1) == 0) {
2967         SDValue Full =
2968           DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2969         Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2970         Offset = 0;
2971       }
2972     } else {
2973       // Conservatively load a constant offset greater than 32 bits into a
2974       // register below.
2975       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
2976       Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2977     }
2978   } else {
2979     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2980     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2981     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2982                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2983   }
2984 
2985   // If there was a non-zero offset that we didn't fold, create an explicit
2986   // addition for it.
2987   if (Offset != 0)
2988     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2989                          DAG.getConstant(Offset, DL, PtrVT));
2990 
2991   return Result;
2992 }
2993 
2994 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2995                                                  SelectionDAG &DAG,
2996                                                  unsigned Opcode,
2997                                                  SDValue GOTOffset) const {
2998   SDLoc DL(Node);
2999   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3000   SDValue Chain = DAG.getEntryNode();
3001   SDValue Glue;
3002 
3003   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3004       CallingConv::GHC)
3005     report_fatal_error("In GHC calling convention TLS is not supported");
3006 
3007   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
3008   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
3009   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
3010   Glue = Chain.getValue(1);
3011   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
3012   Glue = Chain.getValue(1);
3013 
3014   // The first call operand is the chain and the second is the TLS symbol.
3015   SmallVector<SDValue, 8> Ops;
3016   Ops.push_back(Chain);
3017   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
3018                                            Node->getValueType(0),
3019                                            0, 0));
3020 
3021   // Add argument registers to the end of the list so that they are
3022   // known live into the call.
3023   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
3024   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
3025 
3026   // Add a register mask operand representing the call-preserved registers.
3027   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3028   const uint32_t *Mask =
3029       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3030   assert(Mask && "Missing call preserved mask for calling convention");
3031   Ops.push_back(DAG.getRegisterMask(Mask));
3032 
3033   // Glue the call to the argument copies.
3034   Ops.push_back(Glue);
3035 
3036   // Emit the call.
3037   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3038   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
3039   Glue = Chain.getValue(1);
3040 
3041   // Copy the return value from %r2.
3042   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
3043 }
3044 
3045 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
3046                                                   SelectionDAG &DAG) const {
3047   SDValue Chain = DAG.getEntryNode();
3048   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3049 
3050   // The high part of the thread pointer is in access register 0.
3051   SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
3052   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
3053 
3054   // The low part of the thread pointer is in access register 1.
3055   SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
3056   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
3057 
3058   // Merge them into a single 64-bit address.
3059   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
3060                                     DAG.getConstant(32, DL, PtrVT));
3061   return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
3062 }
3063 
3064 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
3065                                                      SelectionDAG &DAG) const {
3066   if (DAG.getTarget().useEmulatedTLS())
3067     return LowerToTLSEmulatedModel(Node, DAG);
3068   SDLoc DL(Node);
3069   const GlobalValue *GV = Node->getGlobal();
3070   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3071   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
3072 
3073   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3074       CallingConv::GHC)
3075     report_fatal_error("In GHC calling convention TLS is not supported");
3076 
3077   SDValue TP = lowerThreadPointer(DL, DAG);
3078 
3079   // Get the offset of GA from the thread pointer, based on the TLS model.
3080   SDValue Offset;
3081   switch (model) {
3082     case TLSModel::GeneralDynamic: {
3083       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
3084       SystemZConstantPoolValue *CPV =
3085         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
3086 
3087       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
3088       Offset = DAG.getLoad(
3089           PtrVT, DL, DAG.getEntryNode(), Offset,
3090           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3091 
3092       // Call __tls_get_offset to retrieve the offset.
3093       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
3094       break;
3095     }
3096 
3097     case TLSModel::LocalDynamic: {
3098       // Load the GOT offset of the module ID.
3099       SystemZConstantPoolValue *CPV =
3100         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
3101 
3102       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
3103       Offset = DAG.getLoad(
3104           PtrVT, DL, DAG.getEntryNode(), Offset,
3105           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3106 
3107       // Call __tls_get_offset to retrieve the module base offset.
3108       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
3109 
3110       // Note: The SystemZLDCleanupPass will remove redundant computations
3111       // of the module base offset.  Count total number of local-dynamic
3112       // accesses to trigger execution of that pass.
3113       SystemZMachineFunctionInfo* MFI =
3114         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
3115       MFI->incNumLocalDynamicTLSAccesses();
3116 
3117       // Add the per-symbol offset.
3118       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
3119 
3120       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
3121       DTPOffset = DAG.getLoad(
3122           PtrVT, DL, DAG.getEntryNode(), DTPOffset,
3123           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3124 
3125       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
3126       break;
3127     }
3128 
3129     case TLSModel::InitialExec: {
3130       // Load the offset from the GOT.
3131       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3132                                           SystemZII::MO_INDNTPOFF);
3133       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
3134       Offset =
3135           DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
3136                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3137       break;
3138     }
3139 
3140     case TLSModel::LocalExec: {
3141       // Force the offset into the constant pool and load it from there.
3142       SystemZConstantPoolValue *CPV =
3143         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
3144 
3145       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
3146       Offset = DAG.getLoad(
3147           PtrVT, DL, DAG.getEntryNode(), Offset,
3148           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3149       break;
3150     }
3151   }
3152 
3153   // Add the base and offset together.
3154   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
3155 }
3156 
3157 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
3158                                                  SelectionDAG &DAG) const {
3159   SDLoc DL(Node);
3160   const BlockAddress *BA = Node->getBlockAddress();
3161   int64_t Offset = Node->getOffset();
3162   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3163 
3164   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
3165   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3166   return Result;
3167 }
3168 
3169 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
3170                                               SelectionDAG &DAG) const {
3171   SDLoc DL(JT);
3172   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3173   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3174 
3175   // Use LARL to load the address of the table.
3176   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3177 }
3178 
3179 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
3180                                                  SelectionDAG &DAG) const {
3181   SDLoc DL(CP);
3182   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3183 
3184   SDValue Result;
3185   if (CP->isMachineConstantPoolEntry())
3186     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3187                                        CP->getAlignment());
3188   else
3189     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3190                                        CP->getAlignment(), CP->getOffset());
3191 
3192   // Use LARL to load the address of the constant pool entry.
3193   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3194 }
3195 
3196 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
3197                                               SelectionDAG &DAG) const {
3198   MachineFunction &MF = DAG.getMachineFunction();
3199   MachineFrameInfo &MFI = MF.getFrameInfo();
3200   MFI.setFrameAddressIsTaken(true);
3201 
3202   SDLoc DL(Op);
3203   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3204   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3205 
3206   // If the back chain frame index has not been allocated yet, do so.
3207   SystemZMachineFunctionInfo *FI = MF.getInfo<SystemZMachineFunctionInfo>();
3208   int BackChainIdx = FI->getFramePointerSaveIndex();
3209   if (!BackChainIdx) {
3210     // By definition, the frame address is the address of the back chain.
3211     BackChainIdx = MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
3212     FI->setFramePointerSaveIndex(BackChainIdx);
3213   }
3214   SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
3215 
3216   // FIXME The frontend should detect this case.
3217   if (Depth > 0) {
3218     report_fatal_error("Unsupported stack frame traversal count");
3219   }
3220 
3221   return BackChain;
3222 }
3223 
3224 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
3225                                                SelectionDAG &DAG) const {
3226   MachineFunction &MF = DAG.getMachineFunction();
3227   MachineFrameInfo &MFI = MF.getFrameInfo();
3228   MFI.setReturnAddressIsTaken(true);
3229 
3230   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3231     return SDValue();
3232 
3233   SDLoc DL(Op);
3234   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3235   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3236 
3237   // FIXME The frontend should detect this case.
3238   if (Depth > 0) {
3239     report_fatal_error("Unsupported stack frame traversal count");
3240   }
3241 
3242   // Return R14D, which has the return address. Mark it an implicit live-in.
3243   unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
3244   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
3245 }
3246 
3247 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
3248                                             SelectionDAG &DAG) const {
3249   SDLoc DL(Op);
3250   SDValue In = Op.getOperand(0);
3251   EVT InVT = In.getValueType();
3252   EVT ResVT = Op.getValueType();
3253 
3254   // Convert loads directly.  This is normally done by DAGCombiner,
3255   // but we need this case for bitcasts that are created during lowering
3256   // and which are then lowered themselves.
3257   if (auto *LoadN = dyn_cast<LoadSDNode>(In))
3258     if (ISD::isNormalLoad(LoadN)) {
3259       SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
3260                                     LoadN->getBasePtr(), LoadN->getMemOperand());
3261       // Update the chain uses.
3262       DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
3263       return NewLoad;
3264     }
3265 
3266   if (InVT == MVT::i32 && ResVT == MVT::f32) {
3267     SDValue In64;
3268     if (Subtarget.hasHighWord()) {
3269       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
3270                                        MVT::i64);
3271       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3272                                        MVT::i64, SDValue(U64, 0), In);
3273     } else {
3274       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
3275       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
3276                          DAG.getConstant(32, DL, MVT::i64));
3277     }
3278     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
3279     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
3280                                       DL, MVT::f32, Out64);
3281   }
3282   if (InVT == MVT::f32 && ResVT == MVT::i32) {
3283     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
3284     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3285                                              MVT::f64, SDValue(U64, 0), In);
3286     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
3287     if (Subtarget.hasHighWord())
3288       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
3289                                         MVT::i32, Out64);
3290     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
3291                                 DAG.getConstant(32, DL, MVT::i64));
3292     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
3293   }
3294   llvm_unreachable("Unexpected bitcast combination");
3295 }
3296 
3297 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
3298                                             SelectionDAG &DAG) const {
3299   MachineFunction &MF = DAG.getMachineFunction();
3300   SystemZMachineFunctionInfo *FuncInfo =
3301     MF.getInfo<SystemZMachineFunctionInfo>();
3302   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3303 
3304   SDValue Chain   = Op.getOperand(0);
3305   SDValue Addr    = Op.getOperand(1);
3306   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3307   SDLoc DL(Op);
3308 
3309   // The initial values of each field.
3310   const unsigned NumFields = 4;
3311   SDValue Fields[NumFields] = {
3312     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
3313     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
3314     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
3315     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
3316   };
3317 
3318   // Store each field into its respective slot.
3319   SDValue MemOps[NumFields];
3320   unsigned Offset = 0;
3321   for (unsigned I = 0; I < NumFields; ++I) {
3322     SDValue FieldAddr = Addr;
3323     if (Offset != 0)
3324       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
3325                               DAG.getIntPtrConstant(Offset, DL));
3326     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
3327                              MachinePointerInfo(SV, Offset));
3328     Offset += 8;
3329   }
3330   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3331 }
3332 
3333 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
3334                                            SelectionDAG &DAG) const {
3335   SDValue Chain      = Op.getOperand(0);
3336   SDValue DstPtr     = Op.getOperand(1);
3337   SDValue SrcPtr     = Op.getOperand(2);
3338   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3339   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3340   SDLoc DL(Op);
3341 
3342   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
3343                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
3344                        /*isTailCall*/false,
3345                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
3346 }
3347 
3348 SDValue SystemZTargetLowering::
3349 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
3350   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
3351   MachineFunction &MF = DAG.getMachineFunction();
3352   bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
3353   bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
3354 
3355   SDValue Chain = Op.getOperand(0);
3356   SDValue Size  = Op.getOperand(1);
3357   SDValue Align = Op.getOperand(2);
3358   SDLoc DL(Op);
3359 
3360   // If user has set the no alignment function attribute, ignore
3361   // alloca alignments.
3362   uint64_t AlignVal = (RealignOpt ?
3363                        dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
3364 
3365   uint64_t StackAlign = TFI->getStackAlignment();
3366   uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
3367   uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
3368 
3369   unsigned SPReg = getStackPointerRegisterToSaveRestore();
3370   SDValue NeededSpace = Size;
3371 
3372   // Get a reference to the stack pointer.
3373   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
3374 
3375   // If we need a backchain, save it now.
3376   SDValue Backchain;
3377   if (StoreBackchain)
3378     Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3379 
3380   // Add extra space for alignment if needed.
3381   if (ExtraAlignSpace)
3382     NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
3383                               DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3384 
3385   // Get the new stack pointer value.
3386   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
3387 
3388   // Copy the new stack pointer back.
3389   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
3390 
3391   // The allocated data lives above the 160 bytes allocated for the standard
3392   // frame, plus any outgoing stack arguments.  We don't know how much that
3393   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
3394   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3395   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
3396 
3397   // Dynamically realign if needed.
3398   if (RequiredAlign > StackAlign) {
3399     Result =
3400       DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
3401                   DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3402     Result =
3403       DAG.getNode(ISD::AND, DL, MVT::i64, Result,
3404                   DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
3405   }
3406 
3407   if (StoreBackchain)
3408     Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3409 
3410   SDValue Ops[2] = { Result, Chain };
3411   return DAG.getMergeValues(Ops, DL);
3412 }
3413 
3414 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
3415     SDValue Op, SelectionDAG &DAG) const {
3416   SDLoc DL(Op);
3417 
3418   return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3419 }
3420 
3421 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
3422                                               SelectionDAG &DAG) const {
3423   EVT VT = Op.getValueType();
3424   SDLoc DL(Op);
3425   SDValue Ops[2];
3426   if (is32Bit(VT))
3427     // Just do a normal 64-bit multiplication and extract the results.
3428     // We define this so that it can be used for constant division.
3429     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
3430                     Op.getOperand(1), Ops[1], Ops[0]);
3431   else if (Subtarget.hasMiscellaneousExtensions2())
3432     // SystemZISD::SMUL_LOHI returns the low result in the odd register and
3433     // the high result in the even register.  ISD::SMUL_LOHI is defined to
3434     // return the low half first, so the results are in reverse order.
3435     lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
3436                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3437   else {
3438     // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
3439     //
3440     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
3441     //
3442     // but using the fact that the upper halves are either all zeros
3443     // or all ones:
3444     //
3445     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
3446     //
3447     // and grouping the right terms together since they are quicker than the
3448     // multiplication:
3449     //
3450     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
3451     SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
3452     SDValue LL = Op.getOperand(0);
3453     SDValue RL = Op.getOperand(1);
3454     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
3455     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
3456     // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3457     // the high result in the even register.  ISD::SMUL_LOHI is defined to
3458     // return the low half first, so the results are in reverse order.
3459     lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
3460                      LL, RL, Ops[1], Ops[0]);
3461     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
3462     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
3463     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
3464     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
3465   }
3466   return DAG.getMergeValues(Ops, DL);
3467 }
3468 
3469 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
3470                                               SelectionDAG &DAG) const {
3471   EVT VT = Op.getValueType();
3472   SDLoc DL(Op);
3473   SDValue Ops[2];
3474   if (is32Bit(VT))
3475     // Just do a normal 64-bit multiplication and extract the results.
3476     // We define this so that it can be used for constant division.
3477     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
3478                     Op.getOperand(1), Ops[1], Ops[0]);
3479   else
3480     // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3481     // the high result in the even register.  ISD::UMUL_LOHI is defined to
3482     // return the low half first, so the results are in reverse order.
3483     lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
3484                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3485   return DAG.getMergeValues(Ops, DL);
3486 }
3487 
3488 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3489                                             SelectionDAG &DAG) const {
3490   SDValue Op0 = Op.getOperand(0);
3491   SDValue Op1 = Op.getOperand(1);
3492   EVT VT = Op.getValueType();
3493   SDLoc DL(Op);
3494 
3495   // We use DSGF for 32-bit division.  This means the first operand must
3496   // always be 64-bit, and the second operand should be 32-bit whenever
3497   // that is possible, to improve performance.
3498   if (is32Bit(VT))
3499     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3500   else if (DAG.ComputeNumSignBits(Op1) > 32)
3501     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3502 
3503   // DSG(F) returns the remainder in the even register and the
3504   // quotient in the odd register.
3505   SDValue Ops[2];
3506   lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
3507   return DAG.getMergeValues(Ops, DL);
3508 }
3509 
3510 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3511                                             SelectionDAG &DAG) const {
3512   EVT VT = Op.getValueType();
3513   SDLoc DL(Op);
3514 
3515   // DL(G) returns the remainder in the even register and the
3516   // quotient in the odd register.
3517   SDValue Ops[2];
3518   lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
3519                    Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3520   return DAG.getMergeValues(Ops, DL);
3521 }
3522 
3523 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3524   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3525 
3526   // Get the known-zero masks for each operand.
3527   SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
3528   KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
3529                         DAG.computeKnownBits(Ops[1])};
3530 
3531   // See if the upper 32 bits of one operand and the lower 32 bits of the
3532   // other are known zero.  They are the low and high operands respectively.
3533   uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
3534                        Known[1].Zero.getZExtValue() };
3535   unsigned High, Low;
3536   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3537     High = 1, Low = 0;
3538   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3539     High = 0, Low = 1;
3540   else
3541     return Op;
3542 
3543   SDValue LowOp = Ops[Low];
3544   SDValue HighOp = Ops[High];
3545 
3546   // If the high part is a constant, we're better off using IILH.
3547   if (HighOp.getOpcode() == ISD::Constant)
3548     return Op;
3549 
3550   // If the low part is a constant that is outside the range of LHI,
3551   // then we're better off using IILF.
3552   if (LowOp.getOpcode() == ISD::Constant) {
3553     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3554     if (!isInt<16>(Value))
3555       return Op;
3556   }
3557 
3558   // Check whether the high part is an AND that doesn't change the
3559   // high 32 bits and just masks out low bits.  We can skip it if so.
3560   if (HighOp.getOpcode() == ISD::AND &&
3561       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3562     SDValue HighOp0 = HighOp.getOperand(0);
3563     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3564     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3565       HighOp = HighOp0;
3566   }
3567 
3568   // Take advantage of the fact that all GR32 operations only change the
3569   // low 32 bits by truncating Low to an i32 and inserting it directly
3570   // using a subreg.  The interesting cases are those where the truncation
3571   // can be folded.
3572   SDLoc DL(Op);
3573   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3574   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3575                                    MVT::i64, HighOp, Low32);
3576 }
3577 
3578 // Lower SADDO/SSUBO/UADDO/USUBO nodes.
3579 SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
3580                                           SelectionDAG &DAG) const {
3581   SDNode *N = Op.getNode();
3582   SDValue LHS = N->getOperand(0);
3583   SDValue RHS = N->getOperand(1);
3584   SDLoc DL(N);
3585   unsigned BaseOp = 0;
3586   unsigned CCValid = 0;
3587   unsigned CCMask = 0;
3588 
3589   switch (Op.getOpcode()) {
3590   default: llvm_unreachable("Unknown instruction!");
3591   case ISD::SADDO:
3592     BaseOp = SystemZISD::SADDO;
3593     CCValid = SystemZ::CCMASK_ARITH;
3594     CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
3595     break;
3596   case ISD::SSUBO:
3597     BaseOp = SystemZISD::SSUBO;
3598     CCValid = SystemZ::CCMASK_ARITH;
3599     CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
3600     break;
3601   case ISD::UADDO:
3602     BaseOp = SystemZISD::UADDO;
3603     CCValid = SystemZ::CCMASK_LOGICAL;
3604     CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
3605     break;
3606   case ISD::USUBO:
3607     BaseOp = SystemZISD::USUBO;
3608     CCValid = SystemZ::CCMASK_LOGICAL;
3609     CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
3610     break;
3611   }
3612 
3613   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
3614   SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
3615 
3616   SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
3617   if (N->getValueType(1) == MVT::i1)
3618     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
3619 
3620   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
3621 }
3622 
3623 static bool isAddCarryChain(SDValue Carry) {
3624   while (Carry.getOpcode() == ISD::ADDCARRY)
3625     Carry = Carry.getOperand(2);
3626   return Carry.getOpcode() == ISD::UADDO;
3627 }
3628 
3629 static bool isSubBorrowChain(SDValue Carry) {
3630   while (Carry.getOpcode() == ISD::SUBCARRY)
3631     Carry = Carry.getOperand(2);
3632   return Carry.getOpcode() == ISD::USUBO;
3633 }
3634 
3635 // Lower ADDCARRY/SUBCARRY nodes.
3636 SDValue SystemZTargetLowering::lowerADDSUBCARRY(SDValue Op,
3637                                                 SelectionDAG &DAG) const {
3638 
3639   SDNode *N = Op.getNode();
3640   MVT VT = N->getSimpleValueType(0);
3641 
3642   // Let legalize expand this if it isn't a legal type yet.
3643   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3644     return SDValue();
3645 
3646   SDValue LHS = N->getOperand(0);
3647   SDValue RHS = N->getOperand(1);
3648   SDValue Carry = Op.getOperand(2);
3649   SDLoc DL(N);
3650   unsigned BaseOp = 0;
3651   unsigned CCValid = 0;
3652   unsigned CCMask = 0;
3653 
3654   switch (Op.getOpcode()) {
3655   default: llvm_unreachable("Unknown instruction!");
3656   case ISD::ADDCARRY:
3657     if (!isAddCarryChain(Carry))
3658       return SDValue();
3659 
3660     BaseOp = SystemZISD::ADDCARRY;
3661     CCValid = SystemZ::CCMASK_LOGICAL;
3662     CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
3663     break;
3664   case ISD::SUBCARRY:
3665     if (!isSubBorrowChain(Carry))
3666       return SDValue();
3667 
3668     BaseOp = SystemZISD::SUBCARRY;
3669     CCValid = SystemZ::CCMASK_LOGICAL;
3670     CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
3671     break;
3672   }
3673 
3674   // Set the condition code from the carry flag.
3675   Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
3676                       DAG.getConstant(CCValid, DL, MVT::i32),
3677                       DAG.getConstant(CCMask, DL, MVT::i32));
3678 
3679   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3680   SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
3681 
3682   SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
3683   if (N->getValueType(1) == MVT::i1)
3684     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
3685 
3686   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
3687 }
3688 
3689 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3690                                           SelectionDAG &DAG) const {
3691   EVT VT = Op.getValueType();
3692   SDLoc DL(Op);
3693   Op = Op.getOperand(0);
3694 
3695   // Handle vector types via VPOPCT.
3696   if (VT.isVector()) {
3697     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3698     Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3699     switch (VT.getScalarSizeInBits()) {
3700     case 8:
3701       break;
3702     case 16: {
3703       Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3704       SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3705       SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3706       Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3707       Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3708       break;
3709     }
3710     case 32: {
3711       SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
3712                                             DAG.getConstant(0, DL, MVT::i32));
3713       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3714       break;
3715     }
3716     case 64: {
3717       SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
3718                                             DAG.getConstant(0, DL, MVT::i32));
3719       Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3720       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3721       break;
3722     }
3723     default:
3724       llvm_unreachable("Unexpected type");
3725     }
3726     return Op;
3727   }
3728 
3729   // Get the known-zero mask for the operand.
3730   KnownBits Known = DAG.computeKnownBits(Op);
3731   unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
3732   if (NumSignificantBits == 0)
3733     return DAG.getConstant(0, DL, VT);
3734 
3735   // Skip known-zero high parts of the operand.
3736   int64_t OrigBitSize = VT.getSizeInBits();
3737   int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3738   BitSize = std::min(BitSize, OrigBitSize);
3739 
3740   // The POPCNT instruction counts the number of bits in each byte.
3741   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3742   Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3743   Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3744 
3745   // Add up per-byte counts in a binary tree.  All bits of Op at
3746   // position larger than BitSize remain zero throughout.
3747   for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3748     SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3749     if (BitSize != OrigBitSize)
3750       Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3751                         DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3752     Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3753   }
3754 
3755   // Extract overall result from high byte.
3756   if (BitSize > 8)
3757     Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3758                      DAG.getConstant(BitSize - 8, DL, VT));
3759 
3760   return Op;
3761 }
3762 
3763 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3764                                                  SelectionDAG &DAG) const {
3765   SDLoc DL(Op);
3766   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3767     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3768   SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
3769     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3770 
3771   // The only fence that needs an instruction is a sequentially-consistent
3772   // cross-thread fence.
3773   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3774       FenceSSID == SyncScope::System) {
3775     return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3776                                       Op.getOperand(0)),
3777                    0);
3778   }
3779 
3780   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3781   return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3782 }
3783 
3784 // Op is an atomic load.  Lower it into a normal volatile load.
3785 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3786                                                 SelectionDAG &DAG) const {
3787   auto *Node = cast<AtomicSDNode>(Op.getNode());
3788   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3789                         Node->getChain(), Node->getBasePtr(),
3790                         Node->getMemoryVT(), Node->getMemOperand());
3791 }
3792 
3793 // Op is an atomic store.  Lower it into a normal volatile store.
3794 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3795                                                  SelectionDAG &DAG) const {
3796   auto *Node = cast<AtomicSDNode>(Op.getNode());
3797   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3798                                     Node->getBasePtr(), Node->getMemoryVT(),
3799                                     Node->getMemOperand());
3800   // We have to enforce sequential consistency by performing a
3801   // serialization operation after the store.
3802   if (Node->getOrdering() == AtomicOrdering::SequentiallyConsistent)
3803     Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op),
3804                                        MVT::Other, Chain), 0);
3805   return Chain;
3806 }
3807 
3808 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
3809 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3810 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3811                                                    SelectionDAG &DAG,
3812                                                    unsigned Opcode) const {
3813   auto *Node = cast<AtomicSDNode>(Op.getNode());
3814 
3815   // 32-bit operations need no code outside the main loop.
3816   EVT NarrowVT = Node->getMemoryVT();
3817   EVT WideVT = MVT::i32;
3818   if (NarrowVT == WideVT)
3819     return Op;
3820 
3821   int64_t BitSize = NarrowVT.getSizeInBits();
3822   SDValue ChainIn = Node->getChain();
3823   SDValue Addr = Node->getBasePtr();
3824   SDValue Src2 = Node->getVal();
3825   MachineMemOperand *MMO = Node->getMemOperand();
3826   SDLoc DL(Node);
3827   EVT PtrVT = Addr.getValueType();
3828 
3829   // Convert atomic subtracts of constants into additions.
3830   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3831     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3832       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3833       Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3834     }
3835 
3836   // Get the address of the containing word.
3837   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3838                                     DAG.getConstant(-4, DL, PtrVT));
3839 
3840   // Get the number of bits that the word must be rotated left in order
3841   // to bring the field to the top bits of a GR32.
3842   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3843                                  DAG.getConstant(3, DL, PtrVT));
3844   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3845 
3846   // Get the complementing shift amount, for rotating a field in the top
3847   // bits back to its proper position.
3848   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3849                                     DAG.getConstant(0, DL, WideVT), BitShift);
3850 
3851   // Extend the source operand to 32 bits and prepare it for the inner loop.
3852   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3853   // operations require the source to be shifted in advance.  (This shift
3854   // can be folded if the source is constant.)  For AND and NAND, the lower
3855   // bits must be set, while for other opcodes they should be left clear.
3856   if (Opcode != SystemZISD::ATOMIC_SWAPW)
3857     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3858                        DAG.getConstant(32 - BitSize, DL, WideVT));
3859   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3860       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3861     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3862                        DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3863 
3864   // Construct the ATOMIC_LOADW_* node.
3865   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3866   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3867                     DAG.getConstant(BitSize, DL, WideVT) };
3868   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3869                                              NarrowVT, MMO);
3870 
3871   // Rotate the result of the final CS so that the field is in the lower
3872   // bits of a GR32, then truncate it.
3873   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3874                                     DAG.getConstant(BitSize, DL, WideVT));
3875   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3876 
3877   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3878   return DAG.getMergeValues(RetOps, DL);
3879 }
3880 
3881 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
3882 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3883 // operations into additions.
3884 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3885                                                     SelectionDAG &DAG) const {
3886   auto *Node = cast<AtomicSDNode>(Op.getNode());
3887   EVT MemVT = Node->getMemoryVT();
3888   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3889     // A full-width operation.
3890     assert(Op.getValueType() == MemVT && "Mismatched VTs");
3891     SDValue Src2 = Node->getVal();
3892     SDValue NegSrc2;
3893     SDLoc DL(Src2);
3894 
3895     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3896       // Use an addition if the operand is constant and either LAA(G) is
3897       // available or the negative value is in the range of A(G)FHI.
3898       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3899       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3900         NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3901     } else if (Subtarget.hasInterlockedAccess1())
3902       // Use LAA(G) if available.
3903       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3904                             Src2);
3905 
3906     if (NegSrc2.getNode())
3907       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3908                            Node->getChain(), Node->getBasePtr(), NegSrc2,
3909                            Node->getMemOperand());
3910 
3911     // Use the node as-is.
3912     return Op;
3913   }
3914 
3915   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3916 }
3917 
3918 // Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
3919 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3920                                                     SelectionDAG &DAG) const {
3921   auto *Node = cast<AtomicSDNode>(Op.getNode());
3922   SDValue ChainIn = Node->getOperand(0);
3923   SDValue Addr = Node->getOperand(1);
3924   SDValue CmpVal = Node->getOperand(2);
3925   SDValue SwapVal = Node->getOperand(3);
3926   MachineMemOperand *MMO = Node->getMemOperand();
3927   SDLoc DL(Node);
3928 
3929   // We have native support for 32-bit and 64-bit compare and swap, but we
3930   // still need to expand extracting the "success" result from the CC.
3931   EVT NarrowVT = Node->getMemoryVT();
3932   EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
3933   if (NarrowVT == WideVT) {
3934     SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
3935     SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
3936     SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
3937                                                DL, Tys, Ops, NarrowVT, MMO);
3938     SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
3939                                 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
3940 
3941     DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
3942     DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
3943     DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
3944     return SDValue();
3945   }
3946 
3947   // Convert 8-bit and 16-bit compare and swap to a loop, implemented
3948   // via a fullword ATOMIC_CMP_SWAPW operation.
3949   int64_t BitSize = NarrowVT.getSizeInBits();
3950   EVT PtrVT = Addr.getValueType();
3951 
3952   // Get the address of the containing word.
3953   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3954                                     DAG.getConstant(-4, DL, PtrVT));
3955 
3956   // Get the number of bits that the word must be rotated left in order
3957   // to bring the field to the top bits of a GR32.
3958   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3959                                  DAG.getConstant(3, DL, PtrVT));
3960   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3961 
3962   // Get the complementing shift amount, for rotating a field in the top
3963   // bits back to its proper position.
3964   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3965                                     DAG.getConstant(0, DL, WideVT), BitShift);
3966 
3967   // Construct the ATOMIC_CMP_SWAPW node.
3968   SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
3969   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3970                     NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3971   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
3972                                              VTList, Ops, NarrowVT, MMO);
3973   SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
3974                               SystemZ::CCMASK_ICMP, SystemZ::CCMASK_CMP_EQ);
3975 
3976   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
3977   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
3978   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
3979   return SDValue();
3980 }
3981 
3982 MachineMemOperand::Flags
3983 SystemZTargetLowering::getMMOFlags(const Instruction &I) const {
3984   // Because of how we convert atomic_load and atomic_store to normal loads and
3985   // stores in the DAG, we need to ensure that the MMOs are marked volatile
3986   // since DAGCombine hasn't been updated to account for atomic, but non
3987   // volatile loads.  (See D57601)
3988   if (auto *SI = dyn_cast<StoreInst>(&I))
3989     if (SI->isAtomic())
3990       return MachineMemOperand::MOVolatile;
3991   if (auto *LI = dyn_cast<LoadInst>(&I))
3992     if (LI->isAtomic())
3993       return MachineMemOperand::MOVolatile;
3994   if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
3995     if (AI->isAtomic())
3996       return MachineMemOperand::MOVolatile;
3997   if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
3998     if (AI->isAtomic())
3999       return MachineMemOperand::MOVolatile;
4000   return MachineMemOperand::MONone;
4001 }
4002 
4003 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
4004                                               SelectionDAG &DAG) const {
4005   MachineFunction &MF = DAG.getMachineFunction();
4006   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
4007   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
4008     report_fatal_error("Variable-sized stack allocations are not supported "
4009                        "in GHC calling convention");
4010   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
4011                             SystemZ::R15D, Op.getValueType());
4012 }
4013 
4014 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
4015                                                  SelectionDAG &DAG) const {
4016   MachineFunction &MF = DAG.getMachineFunction();
4017   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
4018   bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
4019 
4020   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
4021     report_fatal_error("Variable-sized stack allocations are not supported "
4022                        "in GHC calling convention");
4023 
4024   SDValue Chain = Op.getOperand(0);
4025   SDValue NewSP = Op.getOperand(1);
4026   SDValue Backchain;
4027   SDLoc DL(Op);
4028 
4029   if (StoreBackchain) {
4030     SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
4031     Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
4032   }
4033 
4034   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
4035 
4036   if (StoreBackchain)
4037     Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
4038 
4039   return Chain;
4040 }
4041 
4042 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
4043                                              SelectionDAG &DAG) const {
4044   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4045   if (!IsData)
4046     // Just preserve the chain.
4047     return Op.getOperand(0);
4048 
4049   SDLoc DL(Op);
4050   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
4051   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
4052   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
4053   SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
4054                    Op.getOperand(1)};
4055   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
4056                                  Node->getVTList(), Ops,
4057                                  Node->getMemoryVT(), Node->getMemOperand());
4058 }
4059 
4060 // Convert condition code in CCReg to an i32 value.
4061 static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg) {
4062   SDLoc DL(CCReg);
4063   SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
4064   return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
4065                      DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
4066 }
4067 
4068 SDValue
4069 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
4070                                               SelectionDAG &DAG) const {
4071   unsigned Opcode, CCValid;
4072   if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
4073     assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
4074     SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
4075     SDValue CC = getCCResult(DAG, SDValue(Node, 0));
4076     DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
4077     return SDValue();
4078   }
4079 
4080   return SDValue();
4081 }
4082 
4083 SDValue
4084 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
4085                                                SelectionDAG &DAG) const {
4086   unsigned Opcode, CCValid;
4087   if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
4088     SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
4089     if (Op->getNumValues() == 1)
4090       return getCCResult(DAG, SDValue(Node, 0));
4091     assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
4092     return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
4093                        SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
4094   }
4095 
4096   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4097   switch (Id) {
4098   case Intrinsic::thread_pointer:
4099     return lowerThreadPointer(SDLoc(Op), DAG);
4100 
4101   case Intrinsic::s390_vpdi:
4102     return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
4103                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4104 
4105   case Intrinsic::s390_vperm:
4106     return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
4107                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4108 
4109   case Intrinsic::s390_vuphb:
4110   case Intrinsic::s390_vuphh:
4111   case Intrinsic::s390_vuphf:
4112     return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
4113                        Op.getOperand(1));
4114 
4115   case Intrinsic::s390_vuplhb:
4116   case Intrinsic::s390_vuplhh:
4117   case Intrinsic::s390_vuplhf:
4118     return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
4119                        Op.getOperand(1));
4120 
4121   case Intrinsic::s390_vuplb:
4122   case Intrinsic::s390_vuplhw:
4123   case Intrinsic::s390_vuplf:
4124     return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
4125                        Op.getOperand(1));
4126 
4127   case Intrinsic::s390_vupllb:
4128   case Intrinsic::s390_vupllh:
4129   case Intrinsic::s390_vupllf:
4130     return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
4131                        Op.getOperand(1));
4132 
4133   case Intrinsic::s390_vsumb:
4134   case Intrinsic::s390_vsumh:
4135   case Intrinsic::s390_vsumgh:
4136   case Intrinsic::s390_vsumgf:
4137   case Intrinsic::s390_vsumqf:
4138   case Intrinsic::s390_vsumqg:
4139     return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
4140                        Op.getOperand(1), Op.getOperand(2));
4141   }
4142 
4143   return SDValue();
4144 }
4145 
4146 namespace {
4147 // Says that SystemZISD operation Opcode can be used to perform the equivalent
4148 // of a VPERM with permute vector Bytes.  If Opcode takes three operands,
4149 // Operand is the constant third operand, otherwise it is the number of
4150 // bytes in each element of the result.
4151 struct Permute {
4152   unsigned Opcode;
4153   unsigned Operand;
4154   unsigned char Bytes[SystemZ::VectorBytes];
4155 };
4156 }
4157 
4158 static const Permute PermuteForms[] = {
4159   // VMRHG
4160   { SystemZISD::MERGE_HIGH, 8,
4161     { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
4162   // VMRHF
4163   { SystemZISD::MERGE_HIGH, 4,
4164     { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
4165   // VMRHH
4166   { SystemZISD::MERGE_HIGH, 2,
4167     { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
4168   // VMRHB
4169   { SystemZISD::MERGE_HIGH, 1,
4170     { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
4171   // VMRLG
4172   { SystemZISD::MERGE_LOW, 8,
4173     { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
4174   // VMRLF
4175   { SystemZISD::MERGE_LOW, 4,
4176     { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
4177   // VMRLH
4178   { SystemZISD::MERGE_LOW, 2,
4179     { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
4180   // VMRLB
4181   { SystemZISD::MERGE_LOW, 1,
4182     { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
4183   // VPKG
4184   { SystemZISD::PACK, 4,
4185     { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
4186   // VPKF
4187   { SystemZISD::PACK, 2,
4188     { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
4189   // VPKH
4190   { SystemZISD::PACK, 1,
4191     { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
4192   // VPDI V1, V2, 4  (low half of V1, high half of V2)
4193   { SystemZISD::PERMUTE_DWORDS, 4,
4194     { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
4195   // VPDI V1, V2, 1  (high half of V1, low half of V2)
4196   { SystemZISD::PERMUTE_DWORDS, 1,
4197     { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
4198 };
4199 
4200 // Called after matching a vector shuffle against a particular pattern.
4201 // Both the original shuffle and the pattern have two vector operands.
4202 // OpNos[0] is the operand of the original shuffle that should be used for
4203 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
4204 // OpNos[1] is the same for operand 1 of the pattern.  Resolve these -1s and
4205 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
4206 // for operands 0 and 1 of the pattern.
4207 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
4208   if (OpNos[0] < 0) {
4209     if (OpNos[1] < 0)
4210       return false;
4211     OpNo0 = OpNo1 = OpNos[1];
4212   } else if (OpNos[1] < 0) {
4213     OpNo0 = OpNo1 = OpNos[0];
4214   } else {
4215     OpNo0 = OpNos[0];
4216     OpNo1 = OpNos[1];
4217   }
4218   return true;
4219 }
4220 
4221 // Bytes is a VPERM-like permute vector, except that -1 is used for
4222 // undefined bytes.  Return true if the VPERM can be implemented using P.
4223 // When returning true set OpNo0 to the VPERM operand that should be
4224 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
4225 //
4226 // For example, if swapping the VPERM operands allows P to match, OpNo0
4227 // will be 1 and OpNo1 will be 0.  If instead Bytes only refers to one
4228 // operand, but rewriting it to use two duplicated operands allows it to
4229 // match P, then OpNo0 and OpNo1 will be the same.
4230 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
4231                          unsigned &OpNo0, unsigned &OpNo1) {
4232   int OpNos[] = { -1, -1 };
4233   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
4234     int Elt = Bytes[I];
4235     if (Elt >= 0) {
4236       // Make sure that the two permute vectors use the same suboperand
4237       // byte number.  Only the operand numbers (the high bits) are
4238       // allowed to differ.
4239       if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
4240         return false;
4241       int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
4242       int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
4243       // Make sure that the operand mappings are consistent with previous
4244       // elements.
4245       if (OpNos[ModelOpNo] == 1 - RealOpNo)
4246         return false;
4247       OpNos[ModelOpNo] = RealOpNo;
4248     }
4249   }
4250   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
4251 }
4252 
4253 // As above, but search for a matching permute.
4254 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
4255                                    unsigned &OpNo0, unsigned &OpNo1) {
4256   for (auto &P : PermuteForms)
4257     if (matchPermute(Bytes, P, OpNo0, OpNo1))
4258       return &P;
4259   return nullptr;
4260 }
4261 
4262 // Bytes is a VPERM-like permute vector, except that -1 is used for
4263 // undefined bytes.  This permute is an operand of an outer permute.
4264 // See whether redistributing the -1 bytes gives a shuffle that can be
4265 // implemented using P.  If so, set Transform to a VPERM-like permute vector
4266 // that, when applied to the result of P, gives the original permute in Bytes.
4267 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
4268                                const Permute &P,
4269                                SmallVectorImpl<int> &Transform) {
4270   unsigned To = 0;
4271   for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
4272     int Elt = Bytes[From];
4273     if (Elt < 0)
4274       // Byte number From of the result is undefined.
4275       Transform[From] = -1;
4276     else {
4277       while (P.Bytes[To] != Elt) {
4278         To += 1;
4279         if (To == SystemZ::VectorBytes)
4280           return false;
4281       }
4282       Transform[From] = To;
4283     }
4284   }
4285   return true;
4286 }
4287 
4288 // As above, but search for a matching permute.
4289 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
4290                                          SmallVectorImpl<int> &Transform) {
4291   for (auto &P : PermuteForms)
4292     if (matchDoublePermute(Bytes, P, Transform))
4293       return &P;
4294   return nullptr;
4295 }
4296 
4297 // Convert the mask of the given shuffle op into a byte-level mask,
4298 // as if it had type vNi8.
4299 static bool getVPermMask(SDValue ShuffleOp,
4300                          SmallVectorImpl<int> &Bytes) {
4301   EVT VT = ShuffleOp.getValueType();
4302   unsigned NumElements = VT.getVectorNumElements();
4303   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4304 
4305   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
4306     Bytes.resize(NumElements * BytesPerElement, -1);
4307     for (unsigned I = 0; I < NumElements; ++I) {
4308       int Index = VSN->getMaskElt(I);
4309       if (Index >= 0)
4310         for (unsigned J = 0; J < BytesPerElement; ++J)
4311           Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
4312     }
4313     return true;
4314   }
4315   if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
4316       isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
4317     unsigned Index = ShuffleOp.getConstantOperandVal(1);
4318     Bytes.resize(NumElements * BytesPerElement, -1);
4319     for (unsigned I = 0; I < NumElements; ++I)
4320       for (unsigned J = 0; J < BytesPerElement; ++J)
4321         Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
4322     return true;
4323   }
4324   return false;
4325 }
4326 
4327 // Bytes is a VPERM-like permute vector, except that -1 is used for
4328 // undefined bytes.  See whether bytes [Start, Start + BytesPerElement) of
4329 // the result come from a contiguous sequence of bytes from one input.
4330 // Set Base to the selector for the first byte if so.
4331 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
4332                             unsigned BytesPerElement, int &Base) {
4333   Base = -1;
4334   for (unsigned I = 0; I < BytesPerElement; ++I) {
4335     if (Bytes[Start + I] >= 0) {
4336       unsigned Elem = Bytes[Start + I];
4337       if (Base < 0) {
4338         Base = Elem - I;
4339         // Make sure the bytes would come from one input operand.
4340         if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
4341           return false;
4342       } else if (unsigned(Base) != Elem - I)
4343         return false;
4344     }
4345   }
4346   return true;
4347 }
4348 
4349 // Bytes is a VPERM-like permute vector, except that -1 is used for
4350 // undefined bytes.  Return true if it can be performed using VSLDI.
4351 // When returning true, set StartIndex to the shift amount and OpNo0
4352 // and OpNo1 to the VPERM operands that should be used as the first
4353 // and second shift operand respectively.
4354 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
4355                                unsigned &StartIndex, unsigned &OpNo0,
4356                                unsigned &OpNo1) {
4357   int OpNos[] = { -1, -1 };
4358   int Shift = -1;
4359   for (unsigned I = 0; I < 16; ++I) {
4360     int Index = Bytes[I];
4361     if (Index >= 0) {
4362       int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
4363       int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
4364       int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
4365       if (Shift < 0)
4366         Shift = ExpectedShift;
4367       else if (Shift != ExpectedShift)
4368         return false;
4369       // Make sure that the operand mappings are consistent with previous
4370       // elements.
4371       if (OpNos[ModelOpNo] == 1 - RealOpNo)
4372         return false;
4373       OpNos[ModelOpNo] = RealOpNo;
4374     }
4375   }
4376   StartIndex = Shift;
4377   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
4378 }
4379 
4380 // Create a node that performs P on operands Op0 and Op1, casting the
4381 // operands to the appropriate type.  The type of the result is determined by P.
4382 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
4383                               const Permute &P, SDValue Op0, SDValue Op1) {
4384   // VPDI (PERMUTE_DWORDS) always operates on v2i64s.  The input
4385   // elements of a PACK are twice as wide as the outputs.
4386   unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
4387                       P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
4388                       P.Operand);
4389   // Cast both operands to the appropriate type.
4390   MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
4391                               SystemZ::VectorBytes / InBytes);
4392   Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
4393   Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
4394   SDValue Op;
4395   if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
4396     SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
4397     Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
4398   } else if (P.Opcode == SystemZISD::PACK) {
4399     MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
4400                                  SystemZ::VectorBytes / P.Operand);
4401     Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
4402   } else {
4403     Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
4404   }
4405   return Op;
4406 }
4407 
4408 // Bytes is a VPERM-like permute vector, except that -1 is used for
4409 // undefined bytes.  Implement it on operands Ops[0] and Ops[1] using
4410 // VSLDI or VPERM.
4411 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
4412                                      SDValue *Ops,
4413                                      const SmallVectorImpl<int> &Bytes) {
4414   for (unsigned I = 0; I < 2; ++I)
4415     Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
4416 
4417   // First see whether VSLDI can be used.
4418   unsigned StartIndex, OpNo0, OpNo1;
4419   if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
4420     return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
4421                        Ops[OpNo1],
4422                        DAG.getTargetConstant(StartIndex, DL, MVT::i32));
4423 
4424   // Fall back on VPERM.  Construct an SDNode for the permute vector.
4425   SDValue IndexNodes[SystemZ::VectorBytes];
4426   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4427     if (Bytes[I] >= 0)
4428       IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
4429     else
4430       IndexNodes[I] = DAG.getUNDEF(MVT::i32);
4431   SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
4432   return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
4433 }
4434 
4435 namespace {
4436 // Describes a general N-operand vector shuffle.
4437 struct GeneralShuffle {
4438   GeneralShuffle(EVT vt) : VT(vt) {}
4439   void addUndef();
4440   bool add(SDValue, unsigned);
4441   SDValue getNode(SelectionDAG &, const SDLoc &);
4442 
4443   // The operands of the shuffle.
4444   SmallVector<SDValue, SystemZ::VectorBytes> Ops;
4445 
4446   // Index I is -1 if byte I of the result is undefined.  Otherwise the
4447   // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
4448   // Bytes[I] / SystemZ::VectorBytes.
4449   SmallVector<int, SystemZ::VectorBytes> Bytes;
4450 
4451   // The type of the shuffle result.
4452   EVT VT;
4453 };
4454 }
4455 
4456 // Add an extra undefined element to the shuffle.
4457 void GeneralShuffle::addUndef() {
4458   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4459   for (unsigned I = 0; I < BytesPerElement; ++I)
4460     Bytes.push_back(-1);
4461 }
4462 
4463 // Add an extra element to the shuffle, taking it from element Elem of Op.
4464 // A null Op indicates a vector input whose value will be calculated later;
4465 // there is at most one such input per shuffle and it always has the same
4466 // type as the result. Aborts and returns false if the source vector elements
4467 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
4468 // LLVM they become implicitly extended, but this is rare and not optimized.
4469 bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
4470   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4471 
4472   // The source vector can have wider elements than the result,
4473   // either through an explicit TRUNCATE or because of type legalization.
4474   // We want the least significant part.
4475   EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
4476   unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
4477 
4478   // Return false if the source elements are smaller than their destination
4479   // elements.
4480   if (FromBytesPerElement < BytesPerElement)
4481     return false;
4482 
4483   unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
4484                    (FromBytesPerElement - BytesPerElement));
4485 
4486   // Look through things like shuffles and bitcasts.
4487   while (Op.getNode()) {
4488     if (Op.getOpcode() == ISD::BITCAST)
4489       Op = Op.getOperand(0);
4490     else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
4491       // See whether the bytes we need come from a contiguous part of one
4492       // operand.
4493       SmallVector<int, SystemZ::VectorBytes> OpBytes;
4494       if (!getVPermMask(Op, OpBytes))
4495         break;
4496       int NewByte;
4497       if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
4498         break;
4499       if (NewByte < 0) {
4500         addUndef();
4501         return true;
4502       }
4503       Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
4504       Byte = unsigned(NewByte) % SystemZ::VectorBytes;
4505     } else if (Op.isUndef()) {
4506       addUndef();
4507       return true;
4508     } else
4509       break;
4510   }
4511 
4512   // Make sure that the source of the extraction is in Ops.
4513   unsigned OpNo = 0;
4514   for (; OpNo < Ops.size(); ++OpNo)
4515     if (Ops[OpNo] == Op)
4516       break;
4517   if (OpNo == Ops.size())
4518     Ops.push_back(Op);
4519 
4520   // Add the element to Bytes.
4521   unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
4522   for (unsigned I = 0; I < BytesPerElement; ++I)
4523     Bytes.push_back(Base + I);
4524 
4525   return true;
4526 }
4527 
4528 // Return SDNodes for the completed shuffle.
4529 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
4530   assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
4531 
4532   if (Ops.size() == 0)
4533     return DAG.getUNDEF(VT);
4534 
4535   // Make sure that there are at least two shuffle operands.
4536   if (Ops.size() == 1)
4537     Ops.push_back(DAG.getUNDEF(MVT::v16i8));
4538 
4539   // Create a tree of shuffles, deferring root node until after the loop.
4540   // Try to redistribute the undefined elements of non-root nodes so that
4541   // the non-root shuffles match something like a pack or merge, then adjust
4542   // the parent node's permute vector to compensate for the new order.
4543   // Among other things, this copes with vectors like <2 x i16> that were
4544   // padded with undefined elements during type legalization.
4545   //
4546   // In the best case this redistribution will lead to the whole tree
4547   // using packs and merges.  It should rarely be a loss in other cases.
4548   unsigned Stride = 1;
4549   for (; Stride * 2 < Ops.size(); Stride *= 2) {
4550     for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
4551       SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
4552 
4553       // Create a mask for just these two operands.
4554       SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
4555       for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4556         unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
4557         unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
4558         if (OpNo == I)
4559           NewBytes[J] = Byte;
4560         else if (OpNo == I + Stride)
4561           NewBytes[J] = SystemZ::VectorBytes + Byte;
4562         else
4563           NewBytes[J] = -1;
4564       }
4565       // See if it would be better to reorganize NewMask to avoid using VPERM.
4566       SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
4567       if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
4568         Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
4569         // Applying NewBytesMap to Ops[I] gets back to NewBytes.
4570         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4571           if (NewBytes[J] >= 0) {
4572             assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
4573                    "Invalid double permute");
4574             Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
4575           } else
4576             assert(NewBytesMap[J] < 0 && "Invalid double permute");
4577         }
4578       } else {
4579         // Just use NewBytes on the operands.
4580         Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
4581         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
4582           if (NewBytes[J] >= 0)
4583             Bytes[J] = I * SystemZ::VectorBytes + J;
4584       }
4585     }
4586   }
4587 
4588   // Now we just have 2 inputs.  Put the second operand in Ops[1].
4589   if (Stride > 1) {
4590     Ops[1] = Ops[Stride];
4591     for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4592       if (Bytes[I] >= int(SystemZ::VectorBytes))
4593         Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
4594   }
4595 
4596   // Look for an instruction that can do the permute without resorting
4597   // to VPERM.
4598   unsigned OpNo0, OpNo1;
4599   SDValue Op;
4600   if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
4601     Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
4602   else
4603     Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
4604   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4605 }
4606 
4607 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
4608 static bool isScalarToVector(SDValue Op) {
4609   for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
4610     if (!Op.getOperand(I).isUndef())
4611       return false;
4612   return true;
4613 }
4614 
4615 // Return a vector of type VT that contains Value in the first element.
4616 // The other elements don't matter.
4617 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4618                                    SDValue Value) {
4619   // If we have a constant, replicate it to all elements and let the
4620   // BUILD_VECTOR lowering take care of it.
4621   if (Value.getOpcode() == ISD::Constant ||
4622       Value.getOpcode() == ISD::ConstantFP) {
4623     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
4624     return DAG.getBuildVector(VT, DL, Ops);
4625   }
4626   if (Value.isUndef())
4627     return DAG.getUNDEF(VT);
4628   return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4629 }
4630 
4631 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
4632 // element 1.  Used for cases in which replication is cheap.
4633 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4634                                  SDValue Op0, SDValue Op1) {
4635   if (Op0.isUndef()) {
4636     if (Op1.isUndef())
4637       return DAG.getUNDEF(VT);
4638     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4639   }
4640   if (Op1.isUndef())
4641     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4642   return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4643                      buildScalarToVector(DAG, DL, VT, Op0),
4644                      buildScalarToVector(DAG, DL, VT, Op1));
4645 }
4646 
4647 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4648 // vector for them.
4649 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4650                           SDValue Op1) {
4651   if (Op0.isUndef() && Op1.isUndef())
4652     return DAG.getUNDEF(MVT::v2i64);
4653   // If one of the two inputs is undefined then replicate the other one,
4654   // in order to avoid using another register unnecessarily.
4655   if (Op0.isUndef())
4656     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4657   else if (Op1.isUndef())
4658     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4659   else {
4660     Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4661     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4662   }
4663   return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4664 }
4665 
4666 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4667 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4668 // the non-EXTRACT_VECTOR_ELT elements.  See if the given BUILD_VECTOR
4669 // would benefit from this representation and return it if so.
4670 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4671                                      BuildVectorSDNode *BVN) {
4672   EVT VT = BVN->getValueType(0);
4673   unsigned NumElements = VT.getVectorNumElements();
4674 
4675   // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4676   // on byte vectors.  If there are non-EXTRACT_VECTOR_ELT elements that still
4677   // need a BUILD_VECTOR, add an additional placeholder operand for that
4678   // BUILD_VECTOR and store its operands in ResidueOps.
4679   GeneralShuffle GS(VT);
4680   SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4681   bool FoundOne = false;
4682   for (unsigned I = 0; I < NumElements; ++I) {
4683     SDValue Op = BVN->getOperand(I);
4684     if (Op.getOpcode() == ISD::TRUNCATE)
4685       Op = Op.getOperand(0);
4686     if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4687         Op.getOperand(1).getOpcode() == ISD::Constant) {
4688       unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4689       if (!GS.add(Op.getOperand(0), Elem))
4690         return SDValue();
4691       FoundOne = true;
4692     } else if (Op.isUndef()) {
4693       GS.addUndef();
4694     } else {
4695       if (!GS.add(SDValue(), ResidueOps.size()))
4696         return SDValue();
4697       ResidueOps.push_back(BVN->getOperand(I));
4698     }
4699   }
4700 
4701   // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4702   if (!FoundOne)
4703     return SDValue();
4704 
4705   // Create the BUILD_VECTOR for the remaining elements, if any.
4706   if (!ResidueOps.empty()) {
4707     while (ResidueOps.size() < NumElements)
4708       ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4709     for (auto &Op : GS.Ops) {
4710       if (!Op.getNode()) {
4711         Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4712         break;
4713       }
4714     }
4715   }
4716   return GS.getNode(DAG, SDLoc(BVN));
4717 }
4718 
4719 bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
4720   if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
4721     return true;
4722   if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
4723     return true;
4724   return false;
4725 }
4726 
4727 // Combine GPR scalar values Elems into a vector of type VT.
4728 SDValue
4729 SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4730                                    SmallVectorImpl<SDValue> &Elems) const {
4731   // See whether there is a single replicated value.
4732   SDValue Single;
4733   unsigned int NumElements = Elems.size();
4734   unsigned int Count = 0;
4735   for (auto Elem : Elems) {
4736     if (!Elem.isUndef()) {
4737       if (!Single.getNode())
4738         Single = Elem;
4739       else if (Elem != Single) {
4740         Single = SDValue();
4741         break;
4742       }
4743       Count += 1;
4744     }
4745   }
4746   // There are three cases here:
4747   //
4748   // - if the only defined element is a loaded one, the best sequence
4749   //   is a replicating load.
4750   //
4751   // - otherwise, if the only defined element is an i64 value, we will
4752   //   end up with the same VLVGP sequence regardless of whether we short-cut
4753   //   for replication or fall through to the later code.
4754   //
4755   // - otherwise, if the only defined element is an i32 or smaller value,
4756   //   we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4757   //   This is only a win if the single defined element is used more than once.
4758   //   In other cases we're better off using a single VLVGx.
4759   if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
4760     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4761 
4762   // If all elements are loads, use VLREP/VLEs (below).
4763   bool AllLoads = true;
4764   for (auto Elem : Elems)
4765     if (!isVectorElementLoad(Elem)) {
4766       AllLoads = false;
4767       break;
4768     }
4769 
4770   // The best way of building a v2i64 from two i64s is to use VLVGP.
4771   if (VT == MVT::v2i64 && !AllLoads)
4772     return joinDwords(DAG, DL, Elems[0], Elems[1]);
4773 
4774   // Use a 64-bit merge high to combine two doubles.
4775   if (VT == MVT::v2f64 && !AllLoads)
4776     return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4777 
4778   // Build v4f32 values directly from the FPRs:
4779   //
4780   //   <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4781   //         V              V         VMRHF
4782   //      <ABxx>         <CDxx>
4783   //                V                 VMRHG
4784   //              <ABCD>
4785   if (VT == MVT::v4f32 && !AllLoads) {
4786     SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4787     SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4788     // Avoid unnecessary undefs by reusing the other operand.
4789     if (Op01.isUndef())
4790       Op01 = Op23;
4791     else if (Op23.isUndef())
4792       Op23 = Op01;
4793     // Merging identical replications is a no-op.
4794     if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4795       return Op01;
4796     Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4797     Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4798     SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
4799                              DL, MVT::v2i64, Op01, Op23);
4800     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4801   }
4802 
4803   // Collect the constant terms.
4804   SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
4805   SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4806 
4807   unsigned NumConstants = 0;
4808   for (unsigned I = 0; I < NumElements; ++I) {
4809     SDValue Elem = Elems[I];
4810     if (Elem.getOpcode() == ISD::Constant ||
4811         Elem.getOpcode() == ISD::ConstantFP) {
4812       NumConstants += 1;
4813       Constants[I] = Elem;
4814       Done[I] = true;
4815     }
4816   }
4817   // If there was at least one constant, fill in the other elements of
4818   // Constants with undefs to get a full vector constant and use that
4819   // as the starting point.
4820   SDValue Result;
4821   SDValue ReplicatedVal;
4822   if (NumConstants > 0) {
4823     for (unsigned I = 0; I < NumElements; ++I)
4824       if (!Constants[I].getNode())
4825         Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4826     Result = DAG.getBuildVector(VT, DL, Constants);
4827   } else {
4828     // Otherwise try to use VLREP or VLVGP to start the sequence in order to
4829     // avoid a false dependency on any previous contents of the vector
4830     // register.
4831 
4832     // Use a VLREP if at least one element is a load. Make sure to replicate
4833     // the load with the most elements having its value.
4834     std::map<const SDNode*, unsigned> UseCounts;
4835     SDNode *LoadMaxUses = nullptr;
4836     for (unsigned I = 0; I < NumElements; ++I)
4837       if (isVectorElementLoad(Elems[I])) {
4838         SDNode *Ld = Elems[I].getNode();
4839         UseCounts[Ld]++;
4840         if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < UseCounts[Ld])
4841           LoadMaxUses = Ld;
4842       }
4843     if (LoadMaxUses != nullptr) {
4844       ReplicatedVal = SDValue(LoadMaxUses, 0);
4845       Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
4846     } else {
4847       // Try to use VLVGP.
4848       unsigned I1 = NumElements / 2 - 1;
4849       unsigned I2 = NumElements - 1;
4850       bool Def1 = !Elems[I1].isUndef();
4851       bool Def2 = !Elems[I2].isUndef();
4852       if (Def1 || Def2) {
4853         SDValue Elem1 = Elems[Def1 ? I1 : I2];
4854         SDValue Elem2 = Elems[Def2 ? I2 : I1];
4855         Result = DAG.getNode(ISD::BITCAST, DL, VT,
4856                              joinDwords(DAG, DL, Elem1, Elem2));
4857         Done[I1] = true;
4858         Done[I2] = true;
4859       } else
4860         Result = DAG.getUNDEF(VT);
4861     }
4862   }
4863 
4864   // Use VLVGx to insert the other elements.
4865   for (unsigned I = 0; I < NumElements; ++I)
4866     if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
4867       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4868                            DAG.getConstant(I, DL, MVT::i32));
4869   return Result;
4870 }
4871 
4872 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4873                                                  SelectionDAG &DAG) const {
4874   auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4875   SDLoc DL(Op);
4876   EVT VT = Op.getValueType();
4877 
4878   if (BVN->isConstant()) {
4879     if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
4880       return Op;
4881 
4882     // Fall back to loading it from memory.
4883     return SDValue();
4884   }
4885 
4886   // See if we should use shuffles to construct the vector from other vectors.
4887   if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4888     return Res;
4889 
4890   // Detect SCALAR_TO_VECTOR conversions.
4891   if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4892     return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4893 
4894   // Otherwise use buildVector to build the vector up from GPRs.
4895   unsigned NumElements = Op.getNumOperands();
4896   SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4897   for (unsigned I = 0; I < NumElements; ++I)
4898     Ops[I] = Op.getOperand(I);
4899   return buildVector(DAG, DL, VT, Ops);
4900 }
4901 
4902 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4903                                                    SelectionDAG &DAG) const {
4904   auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4905   SDLoc DL(Op);
4906   EVT VT = Op.getValueType();
4907   unsigned NumElements = VT.getVectorNumElements();
4908 
4909   if (VSN->isSplat()) {
4910     SDValue Op0 = Op.getOperand(0);
4911     unsigned Index = VSN->getSplatIndex();
4912     assert(Index < VT.getVectorNumElements() &&
4913            "Splat index should be defined and in first operand");
4914     // See whether the value we're splatting is directly available as a scalar.
4915     if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4916         Op0.getOpcode() == ISD::BUILD_VECTOR)
4917       return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4918     // Otherwise keep it as a vector-to-vector operation.
4919     return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4920                        DAG.getTargetConstant(Index, DL, MVT::i32));
4921   }
4922 
4923   GeneralShuffle GS(VT);
4924   for (unsigned I = 0; I < NumElements; ++I) {
4925     int Elt = VSN->getMaskElt(I);
4926     if (Elt < 0)
4927       GS.addUndef();
4928     else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4929                      unsigned(Elt) % NumElements))
4930       return SDValue();
4931   }
4932   return GS.getNode(DAG, SDLoc(VSN));
4933 }
4934 
4935 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4936                                                      SelectionDAG &DAG) const {
4937   SDLoc DL(Op);
4938   // Just insert the scalar into element 0 of an undefined vector.
4939   return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4940                      Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4941                      Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4942 }
4943 
4944 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4945                                                       SelectionDAG &DAG) const {
4946   // Handle insertions of floating-point values.
4947   SDLoc DL(Op);
4948   SDValue Op0 = Op.getOperand(0);
4949   SDValue Op1 = Op.getOperand(1);
4950   SDValue Op2 = Op.getOperand(2);
4951   EVT VT = Op.getValueType();
4952 
4953   // Insertions into constant indices of a v2f64 can be done using VPDI.
4954   // However, if the inserted value is a bitcast or a constant then it's
4955   // better to use GPRs, as below.
4956   if (VT == MVT::v2f64 &&
4957       Op1.getOpcode() != ISD::BITCAST &&
4958       Op1.getOpcode() != ISD::ConstantFP &&
4959       Op2.getOpcode() == ISD::Constant) {
4960     uint64_t Index = cast<ConstantSDNode>(Op2)->getZExtValue();
4961     unsigned Mask = VT.getVectorNumElements() - 1;
4962     if (Index <= Mask)
4963       return Op;
4964   }
4965 
4966   // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4967   MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
4968   MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4969   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4970                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4971                             DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4972   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4973 }
4974 
4975 SDValue
4976 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4977                                                SelectionDAG &DAG) const {
4978   // Handle extractions of floating-point values.
4979   SDLoc DL(Op);
4980   SDValue Op0 = Op.getOperand(0);
4981   SDValue Op1 = Op.getOperand(1);
4982   EVT VT = Op.getValueType();
4983   EVT VecVT = Op0.getValueType();
4984 
4985   // Extractions of constant indices can be done directly.
4986   if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4987     uint64_t Index = CIndexN->getZExtValue();
4988     unsigned Mask = VecVT.getVectorNumElements() - 1;
4989     if (Index <= Mask)
4990       return Op;
4991   }
4992 
4993   // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4994   MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4995   MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4996   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4997                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4998   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4999 }
5000 
5001 SDValue
5002 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
5003                                               unsigned UnpackHigh) const {
5004   SDValue PackedOp = Op.getOperand(0);
5005   EVT OutVT = Op.getValueType();
5006   EVT InVT = PackedOp.getValueType();
5007   unsigned ToBits = OutVT.getScalarSizeInBits();
5008   unsigned FromBits = InVT.getScalarSizeInBits();
5009   do {
5010     FromBits *= 2;
5011     EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
5012                                  SystemZ::VectorBits / FromBits);
5013     PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
5014   } while (FromBits != ToBits);
5015   return PackedOp;
5016 }
5017 
5018 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
5019                                           unsigned ByScalar) const {
5020   // Look for cases where a vector shift can use the *_BY_SCALAR form.
5021   SDValue Op0 = Op.getOperand(0);
5022   SDValue Op1 = Op.getOperand(1);
5023   SDLoc DL(Op);
5024   EVT VT = Op.getValueType();
5025   unsigned ElemBitSize = VT.getScalarSizeInBits();
5026 
5027   // See whether the shift vector is a splat represented as BUILD_VECTOR.
5028   if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
5029     APInt SplatBits, SplatUndef;
5030     unsigned SplatBitSize;
5031     bool HasAnyUndefs;
5032     // Check for constant splats.  Use ElemBitSize as the minimum element
5033     // width and reject splats that need wider elements.
5034     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5035                              ElemBitSize, true) &&
5036         SplatBitSize == ElemBitSize) {
5037       SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
5038                                       DL, MVT::i32);
5039       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5040     }
5041     // Check for variable splats.
5042     BitVector UndefElements;
5043     SDValue Splat = BVN->getSplatValue(&UndefElements);
5044     if (Splat) {
5045       // Since i32 is the smallest legal type, we either need a no-op
5046       // or a truncation.
5047       SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
5048       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5049     }
5050   }
5051 
5052   // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
5053   // and the shift amount is directly available in a GPR.
5054   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
5055     if (VSN->isSplat()) {
5056       SDValue VSNOp0 = VSN->getOperand(0);
5057       unsigned Index = VSN->getSplatIndex();
5058       assert(Index < VT.getVectorNumElements() &&
5059              "Splat index should be defined and in first operand");
5060       if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
5061           VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
5062         // Since i32 is the smallest legal type, we either need a no-op
5063         // or a truncation.
5064         SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
5065                                     VSNOp0.getOperand(Index));
5066         return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5067       }
5068     }
5069   }
5070 
5071   // Otherwise just treat the current form as legal.
5072   return Op;
5073 }
5074 
5075 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
5076                                               SelectionDAG &DAG) const {
5077   switch (Op.getOpcode()) {
5078   case ISD::FRAMEADDR:
5079     return lowerFRAMEADDR(Op, DAG);
5080   case ISD::RETURNADDR:
5081     return lowerRETURNADDR(Op, DAG);
5082   case ISD::BR_CC:
5083     return lowerBR_CC(Op, DAG);
5084   case ISD::SELECT_CC:
5085     return lowerSELECT_CC(Op, DAG);
5086   case ISD::SETCC:
5087     return lowerSETCC(Op, DAG);
5088   case ISD::STRICT_FSETCC:
5089     return lowerSTRICT_FSETCC(Op, DAG, false);
5090   case ISD::STRICT_FSETCCS:
5091     return lowerSTRICT_FSETCC(Op, DAG, true);
5092   case ISD::GlobalAddress:
5093     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
5094   case ISD::GlobalTLSAddress:
5095     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
5096   case ISD::BlockAddress:
5097     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
5098   case ISD::JumpTable:
5099     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
5100   case ISD::ConstantPool:
5101     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
5102   case ISD::BITCAST:
5103     return lowerBITCAST(Op, DAG);
5104   case ISD::VASTART:
5105     return lowerVASTART(Op, DAG);
5106   case ISD::VACOPY:
5107     return lowerVACOPY(Op, DAG);
5108   case ISD::DYNAMIC_STACKALLOC:
5109     return lowerDYNAMIC_STACKALLOC(Op, DAG);
5110   case ISD::GET_DYNAMIC_AREA_OFFSET:
5111     return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
5112   case ISD::SMUL_LOHI:
5113     return lowerSMUL_LOHI(Op, DAG);
5114   case ISD::UMUL_LOHI:
5115     return lowerUMUL_LOHI(Op, DAG);
5116   case ISD::SDIVREM:
5117     return lowerSDIVREM(Op, DAG);
5118   case ISD::UDIVREM:
5119     return lowerUDIVREM(Op, DAG);
5120   case ISD::SADDO:
5121   case ISD::SSUBO:
5122   case ISD::UADDO:
5123   case ISD::USUBO:
5124     return lowerXALUO(Op, DAG);
5125   case ISD::ADDCARRY:
5126   case ISD::SUBCARRY:
5127     return lowerADDSUBCARRY(Op, DAG);
5128   case ISD::OR:
5129     return lowerOR(Op, DAG);
5130   case ISD::CTPOP:
5131     return lowerCTPOP(Op, DAG);
5132   case ISD::ATOMIC_FENCE:
5133     return lowerATOMIC_FENCE(Op, DAG);
5134   case ISD::ATOMIC_SWAP:
5135     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
5136   case ISD::ATOMIC_STORE:
5137     return lowerATOMIC_STORE(Op, DAG);
5138   case ISD::ATOMIC_LOAD:
5139     return lowerATOMIC_LOAD(Op, DAG);
5140   case ISD::ATOMIC_LOAD_ADD:
5141     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
5142   case ISD::ATOMIC_LOAD_SUB:
5143     return lowerATOMIC_LOAD_SUB(Op, DAG);
5144   case ISD::ATOMIC_LOAD_AND:
5145     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
5146   case ISD::ATOMIC_LOAD_OR:
5147     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
5148   case ISD::ATOMIC_LOAD_XOR:
5149     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
5150   case ISD::ATOMIC_LOAD_NAND:
5151     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
5152   case ISD::ATOMIC_LOAD_MIN:
5153     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
5154   case ISD::ATOMIC_LOAD_MAX:
5155     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
5156   case ISD::ATOMIC_LOAD_UMIN:
5157     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
5158   case ISD::ATOMIC_LOAD_UMAX:
5159     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
5160   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
5161     return lowerATOMIC_CMP_SWAP(Op, DAG);
5162   case ISD::STACKSAVE:
5163     return lowerSTACKSAVE(Op, DAG);
5164   case ISD::STACKRESTORE:
5165     return lowerSTACKRESTORE(Op, DAG);
5166   case ISD::PREFETCH:
5167     return lowerPREFETCH(Op, DAG);
5168   case ISD::INTRINSIC_W_CHAIN:
5169     return lowerINTRINSIC_W_CHAIN(Op, DAG);
5170   case ISD::INTRINSIC_WO_CHAIN:
5171     return lowerINTRINSIC_WO_CHAIN(Op, DAG);
5172   case ISD::BUILD_VECTOR:
5173     return lowerBUILD_VECTOR(Op, DAG);
5174   case ISD::VECTOR_SHUFFLE:
5175     return lowerVECTOR_SHUFFLE(Op, DAG);
5176   case ISD::SCALAR_TO_VECTOR:
5177     return lowerSCALAR_TO_VECTOR(Op, DAG);
5178   case ISD::INSERT_VECTOR_ELT:
5179     return lowerINSERT_VECTOR_ELT(Op, DAG);
5180   case ISD::EXTRACT_VECTOR_ELT:
5181     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
5182   case ISD::SIGN_EXTEND_VECTOR_INREG:
5183     return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
5184   case ISD::ZERO_EXTEND_VECTOR_INREG:
5185     return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
5186   case ISD::SHL:
5187     return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
5188   case ISD::SRL:
5189     return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
5190   case ISD::SRA:
5191     return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
5192   default:
5193     llvm_unreachable("Unexpected node to lower");
5194   }
5195 }
5196 
5197 // Lower operations with invalid operand or result types (currently used
5198 // only for 128-bit integer types).
5199 
5200 static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In) {
5201   SDLoc DL(In);
5202   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
5203                            DAG.getIntPtrConstant(0, DL));
5204   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
5205                            DAG.getIntPtrConstant(1, DL));
5206   SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
5207                                     MVT::Untyped, Hi, Lo);
5208   return SDValue(Pair, 0);
5209 }
5210 
5211 static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In) {
5212   SDLoc DL(In);
5213   SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
5214                                           DL, MVT::i64, In);
5215   SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
5216                                           DL, MVT::i64, In);
5217   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
5218 }
5219 
5220 void
5221 SystemZTargetLowering::LowerOperationWrapper(SDNode *N,
5222                                              SmallVectorImpl<SDValue> &Results,
5223                                              SelectionDAG &DAG) const {
5224   switch (N->getOpcode()) {
5225   case ISD::ATOMIC_LOAD: {
5226     SDLoc DL(N);
5227     SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other);
5228     SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
5229     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5230     SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
5231                                           DL, Tys, Ops, MVT::i128, MMO);
5232     Results.push_back(lowerGR128ToI128(DAG, Res));
5233     Results.push_back(Res.getValue(1));
5234     break;
5235   }
5236   case ISD::ATOMIC_STORE: {
5237     SDLoc DL(N);
5238     SDVTList Tys = DAG.getVTList(MVT::Other);
5239     SDValue Ops[] = { N->getOperand(0),
5240                       lowerI128ToGR128(DAG, N->getOperand(2)),
5241                       N->getOperand(1) };
5242     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5243     SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
5244                                           DL, Tys, Ops, MVT::i128, MMO);
5245     // We have to enforce sequential consistency by performing a
5246     // serialization operation after the store.
5247     if (cast<AtomicSDNode>(N)->getOrdering() ==
5248         AtomicOrdering::SequentiallyConsistent)
5249       Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
5250                                        MVT::Other, Res), 0);
5251     Results.push_back(Res);
5252     break;
5253   }
5254   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
5255     SDLoc DL(N);
5256     SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other);
5257     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
5258                       lowerI128ToGR128(DAG, N->getOperand(2)),
5259                       lowerI128ToGR128(DAG, N->getOperand(3)) };
5260     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5261     SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
5262                                           DL, Tys, Ops, MVT::i128, MMO);
5263     SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
5264                                 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
5265     Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
5266     Results.push_back(lowerGR128ToI128(DAG, Res));
5267     Results.push_back(Success);
5268     Results.push_back(Res.getValue(2));
5269     break;
5270   }
5271   default:
5272     llvm_unreachable("Unexpected node to lower");
5273   }
5274 }
5275 
5276 void
5277 SystemZTargetLowering::ReplaceNodeResults(SDNode *N,
5278                                           SmallVectorImpl<SDValue> &Results,
5279                                           SelectionDAG &DAG) const {
5280   return LowerOperationWrapper(N, Results, DAG);
5281 }
5282 
5283 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
5284 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
5285   switch ((SystemZISD::NodeType)Opcode) {
5286     case SystemZISD::FIRST_NUMBER: break;
5287     OPCODE(RET_FLAG);
5288     OPCODE(CALL);
5289     OPCODE(SIBCALL);
5290     OPCODE(TLS_GDCALL);
5291     OPCODE(TLS_LDCALL);
5292     OPCODE(PCREL_WRAPPER);
5293     OPCODE(PCREL_OFFSET);
5294     OPCODE(IABS);
5295     OPCODE(ICMP);
5296     OPCODE(FCMP);
5297     OPCODE(STRICT_FCMP);
5298     OPCODE(STRICT_FCMPS);
5299     OPCODE(TM);
5300     OPCODE(BR_CCMASK);
5301     OPCODE(SELECT_CCMASK);
5302     OPCODE(ADJDYNALLOC);
5303     OPCODE(POPCNT);
5304     OPCODE(SMUL_LOHI);
5305     OPCODE(UMUL_LOHI);
5306     OPCODE(SDIVREM);
5307     OPCODE(UDIVREM);
5308     OPCODE(SADDO);
5309     OPCODE(SSUBO);
5310     OPCODE(UADDO);
5311     OPCODE(USUBO);
5312     OPCODE(ADDCARRY);
5313     OPCODE(SUBCARRY);
5314     OPCODE(GET_CCMASK);
5315     OPCODE(MVC);
5316     OPCODE(MVC_LOOP);
5317     OPCODE(NC);
5318     OPCODE(NC_LOOP);
5319     OPCODE(OC);
5320     OPCODE(OC_LOOP);
5321     OPCODE(XC);
5322     OPCODE(XC_LOOP);
5323     OPCODE(CLC);
5324     OPCODE(CLC_LOOP);
5325     OPCODE(STPCPY);
5326     OPCODE(STRCMP);
5327     OPCODE(SEARCH_STRING);
5328     OPCODE(IPM);
5329     OPCODE(MEMBARRIER);
5330     OPCODE(TBEGIN);
5331     OPCODE(TBEGIN_NOFLOAT);
5332     OPCODE(TEND);
5333     OPCODE(BYTE_MASK);
5334     OPCODE(ROTATE_MASK);
5335     OPCODE(REPLICATE);
5336     OPCODE(JOIN_DWORDS);
5337     OPCODE(SPLAT);
5338     OPCODE(MERGE_HIGH);
5339     OPCODE(MERGE_LOW);
5340     OPCODE(SHL_DOUBLE);
5341     OPCODE(PERMUTE_DWORDS);
5342     OPCODE(PERMUTE);
5343     OPCODE(PACK);
5344     OPCODE(PACKS_CC);
5345     OPCODE(PACKLS_CC);
5346     OPCODE(UNPACK_HIGH);
5347     OPCODE(UNPACKL_HIGH);
5348     OPCODE(UNPACK_LOW);
5349     OPCODE(UNPACKL_LOW);
5350     OPCODE(VSHL_BY_SCALAR);
5351     OPCODE(VSRL_BY_SCALAR);
5352     OPCODE(VSRA_BY_SCALAR);
5353     OPCODE(VSUM);
5354     OPCODE(VICMPE);
5355     OPCODE(VICMPH);
5356     OPCODE(VICMPHL);
5357     OPCODE(VICMPES);
5358     OPCODE(VICMPHS);
5359     OPCODE(VICMPHLS);
5360     OPCODE(VFCMPE);
5361     OPCODE(STRICT_VFCMPE);
5362     OPCODE(STRICT_VFCMPES);
5363     OPCODE(VFCMPH);
5364     OPCODE(STRICT_VFCMPH);
5365     OPCODE(STRICT_VFCMPHS);
5366     OPCODE(VFCMPHE);
5367     OPCODE(STRICT_VFCMPHE);
5368     OPCODE(STRICT_VFCMPHES);
5369     OPCODE(VFCMPES);
5370     OPCODE(VFCMPHS);
5371     OPCODE(VFCMPHES);
5372     OPCODE(VFTCI);
5373     OPCODE(VEXTEND);
5374     OPCODE(STRICT_VEXTEND);
5375     OPCODE(VROUND);
5376     OPCODE(VTM);
5377     OPCODE(VFAE_CC);
5378     OPCODE(VFAEZ_CC);
5379     OPCODE(VFEE_CC);
5380     OPCODE(VFEEZ_CC);
5381     OPCODE(VFENE_CC);
5382     OPCODE(VFENEZ_CC);
5383     OPCODE(VISTR_CC);
5384     OPCODE(VSTRC_CC);
5385     OPCODE(VSTRCZ_CC);
5386     OPCODE(VSTRS_CC);
5387     OPCODE(VSTRSZ_CC);
5388     OPCODE(TDC);
5389     OPCODE(ATOMIC_SWAPW);
5390     OPCODE(ATOMIC_LOADW_ADD);
5391     OPCODE(ATOMIC_LOADW_SUB);
5392     OPCODE(ATOMIC_LOADW_AND);
5393     OPCODE(ATOMIC_LOADW_OR);
5394     OPCODE(ATOMIC_LOADW_XOR);
5395     OPCODE(ATOMIC_LOADW_NAND);
5396     OPCODE(ATOMIC_LOADW_MIN);
5397     OPCODE(ATOMIC_LOADW_MAX);
5398     OPCODE(ATOMIC_LOADW_UMIN);
5399     OPCODE(ATOMIC_LOADW_UMAX);
5400     OPCODE(ATOMIC_CMP_SWAPW);
5401     OPCODE(ATOMIC_CMP_SWAP);
5402     OPCODE(ATOMIC_LOAD_128);
5403     OPCODE(ATOMIC_STORE_128);
5404     OPCODE(ATOMIC_CMP_SWAP_128);
5405     OPCODE(LRV);
5406     OPCODE(STRV);
5407     OPCODE(VLER);
5408     OPCODE(VSTER);
5409     OPCODE(PREFETCH);
5410   }
5411   return nullptr;
5412 #undef OPCODE
5413 }
5414 
5415 // Return true if VT is a vector whose elements are a whole number of bytes
5416 // in width. Also check for presence of vector support.
5417 bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
5418   if (!Subtarget.hasVector())
5419     return false;
5420 
5421   return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
5422 }
5423 
5424 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
5425 // producing a result of type ResVT.  Op is a possibly bitcast version
5426 // of the input vector and Index is the index (based on type VecVT) that
5427 // should be extracted.  Return the new extraction if a simplification
5428 // was possible or if Force is true.
5429 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
5430                                               EVT VecVT, SDValue Op,
5431                                               unsigned Index,
5432                                               DAGCombinerInfo &DCI,
5433                                               bool Force) const {
5434   SelectionDAG &DAG = DCI.DAG;
5435 
5436   // The number of bytes being extracted.
5437   unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
5438 
5439   for (;;) {
5440     unsigned Opcode = Op.getOpcode();
5441     if (Opcode == ISD::BITCAST)
5442       // Look through bitcasts.
5443       Op = Op.getOperand(0);
5444     else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
5445              canTreatAsByteVector(Op.getValueType())) {
5446       // Get a VPERM-like permute mask and see whether the bytes covered
5447       // by the extracted element are a contiguous sequence from one
5448       // source operand.
5449       SmallVector<int, SystemZ::VectorBytes> Bytes;
5450       if (!getVPermMask(Op, Bytes))
5451         break;
5452       int First;
5453       if (!getShuffleInput(Bytes, Index * BytesPerElement,
5454                            BytesPerElement, First))
5455         break;
5456       if (First < 0)
5457         return DAG.getUNDEF(ResVT);
5458       // Make sure the contiguous sequence starts at a multiple of the
5459       // original element size.
5460       unsigned Byte = unsigned(First) % Bytes.size();
5461       if (Byte % BytesPerElement != 0)
5462         break;
5463       // We can get the extracted value directly from an input.
5464       Index = Byte / BytesPerElement;
5465       Op = Op.getOperand(unsigned(First) / Bytes.size());
5466       Force = true;
5467     } else if (Opcode == ISD::BUILD_VECTOR &&
5468                canTreatAsByteVector(Op.getValueType())) {
5469       // We can only optimize this case if the BUILD_VECTOR elements are
5470       // at least as wide as the extracted value.
5471       EVT OpVT = Op.getValueType();
5472       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
5473       if (OpBytesPerElement < BytesPerElement)
5474         break;
5475       // Make sure that the least-significant bit of the extracted value
5476       // is the least significant bit of an input.
5477       unsigned End = (Index + 1) * BytesPerElement;
5478       if (End % OpBytesPerElement != 0)
5479         break;
5480       // We're extracting the low part of one operand of the BUILD_VECTOR.
5481       Op = Op.getOperand(End / OpBytesPerElement - 1);
5482       if (!Op.getValueType().isInteger()) {
5483         EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
5484         Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5485         DCI.AddToWorklist(Op.getNode());
5486       }
5487       EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
5488       Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5489       if (VT != ResVT) {
5490         DCI.AddToWorklist(Op.getNode());
5491         Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
5492       }
5493       return Op;
5494     } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5495                 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
5496                 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
5497                canTreatAsByteVector(Op.getValueType()) &&
5498                canTreatAsByteVector(Op.getOperand(0).getValueType())) {
5499       // Make sure that only the unextended bits are significant.
5500       EVT ExtVT = Op.getValueType();
5501       EVT OpVT = Op.getOperand(0).getValueType();
5502       unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
5503       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
5504       unsigned Byte = Index * BytesPerElement;
5505       unsigned SubByte = Byte % ExtBytesPerElement;
5506       unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
5507       if (SubByte < MinSubByte ||
5508           SubByte + BytesPerElement > ExtBytesPerElement)
5509         break;
5510       // Get the byte offset of the unextended element
5511       Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
5512       // ...then add the byte offset relative to that element.
5513       Byte += SubByte - MinSubByte;
5514       if (Byte % BytesPerElement != 0)
5515         break;
5516       Op = Op.getOperand(0);
5517       Index = Byte / BytesPerElement;
5518       Force = true;
5519     } else
5520       break;
5521   }
5522   if (Force) {
5523     if (Op.getValueType() != VecVT) {
5524       Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
5525       DCI.AddToWorklist(Op.getNode());
5526     }
5527     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
5528                        DAG.getConstant(Index, DL, MVT::i32));
5529   }
5530   return SDValue();
5531 }
5532 
5533 // Optimize vector operations in scalar value Op on the basis that Op
5534 // is truncated to TruncVT.
5535 SDValue SystemZTargetLowering::combineTruncateExtract(
5536     const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
5537   // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
5538   // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
5539   // of type TruncVT.
5540   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5541       TruncVT.getSizeInBits() % 8 == 0) {
5542     SDValue Vec = Op.getOperand(0);
5543     EVT VecVT = Vec.getValueType();
5544     if (canTreatAsByteVector(VecVT)) {
5545       if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
5546         unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
5547         unsigned TruncBytes = TruncVT.getStoreSize();
5548         if (BytesPerElement % TruncBytes == 0) {
5549           // Calculate the value of Y' in the above description.  We are
5550           // splitting the original elements into Scale equal-sized pieces
5551           // and for truncation purposes want the last (least-significant)
5552           // of these pieces for IndexN.  This is easiest to do by calculating
5553           // the start index of the following element and then subtracting 1.
5554           unsigned Scale = BytesPerElement / TruncBytes;
5555           unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
5556 
5557           // Defer the creation of the bitcast from X to combineExtract,
5558           // which might be able to optimize the extraction.
5559           VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
5560                                    VecVT.getStoreSize() / TruncBytes);
5561           EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
5562           return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
5563         }
5564       }
5565     }
5566   }
5567   return SDValue();
5568 }
5569 
5570 SDValue SystemZTargetLowering::combineZERO_EXTEND(
5571     SDNode *N, DAGCombinerInfo &DCI) const {
5572   // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
5573   SelectionDAG &DAG = DCI.DAG;
5574   SDValue N0 = N->getOperand(0);
5575   EVT VT = N->getValueType(0);
5576   if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
5577     auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
5578     auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5579     if (TrueOp && FalseOp) {
5580       SDLoc DL(N0);
5581       SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
5582                         DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
5583                         N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
5584       SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
5585       // If N0 has multiple uses, change other uses as well.
5586       if (!N0.hasOneUse()) {
5587         SDValue TruncSelect =
5588           DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
5589         DCI.CombineTo(N0.getNode(), TruncSelect);
5590       }
5591       return NewSelect;
5592     }
5593   }
5594   return SDValue();
5595 }
5596 
5597 SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
5598     SDNode *N, DAGCombinerInfo &DCI) const {
5599   // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
5600   // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
5601   // into (select_cc LHS, RHS, -1, 0, COND)
5602   SelectionDAG &DAG = DCI.DAG;
5603   SDValue N0 = N->getOperand(0);
5604   EVT VT = N->getValueType(0);
5605   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5606   if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
5607     N0 = N0.getOperand(0);
5608   if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
5609     SDLoc DL(N0);
5610     SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
5611                       DAG.getConstant(-1, DL, VT), DAG.getConstant(0, DL, VT),
5612                       N0.getOperand(2) };
5613     return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
5614   }
5615   return SDValue();
5616 }
5617 
5618 SDValue SystemZTargetLowering::combineSIGN_EXTEND(
5619     SDNode *N, DAGCombinerInfo &DCI) const {
5620   // Convert (sext (ashr (shl X, C1), C2)) to
5621   // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
5622   // cheap as narrower ones.
5623   SelectionDAG &DAG = DCI.DAG;
5624   SDValue N0 = N->getOperand(0);
5625   EVT VT = N->getValueType(0);
5626   if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
5627     auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5628     SDValue Inner = N0.getOperand(0);
5629     if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
5630       if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
5631         unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
5632         unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
5633         unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
5634         EVT ShiftVT = N0.getOperand(1).getValueType();
5635         SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
5636                                   Inner.getOperand(0));
5637         SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
5638                                   DAG.getConstant(NewShlAmt, SDLoc(Inner),
5639                                                   ShiftVT));
5640         return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
5641                            DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
5642       }
5643     }
5644   }
5645   return SDValue();
5646 }
5647 
5648 SDValue SystemZTargetLowering::combineMERGE(
5649     SDNode *N, DAGCombinerInfo &DCI) const {
5650   SelectionDAG &DAG = DCI.DAG;
5651   unsigned Opcode = N->getOpcode();
5652   SDValue Op0 = N->getOperand(0);
5653   SDValue Op1 = N->getOperand(1);
5654   if (Op0.getOpcode() == ISD::BITCAST)
5655     Op0 = Op0.getOperand(0);
5656   if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5657     // (z_merge_* 0, 0) -> 0.  This is mostly useful for using VLLEZF
5658     // for v4f32.
5659     if (Op1 == N->getOperand(0))
5660       return Op1;
5661     // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
5662     EVT VT = Op1.getValueType();
5663     unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
5664     if (ElemBytes <= 4) {
5665       Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
5666                 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
5667       EVT InVT = VT.changeVectorElementTypeToInteger();
5668       EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
5669                                    SystemZ::VectorBytes / ElemBytes / 2);
5670       if (VT != InVT) {
5671         Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
5672         DCI.AddToWorklist(Op1.getNode());
5673       }
5674       SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
5675       DCI.AddToWorklist(Op.getNode());
5676       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
5677     }
5678   }
5679   return SDValue();
5680 }
5681 
5682 SDValue SystemZTargetLowering::combineLOAD(
5683     SDNode *N, DAGCombinerInfo &DCI) const {
5684   SelectionDAG &DAG = DCI.DAG;
5685   EVT LdVT = N->getValueType(0);
5686   if (LdVT.isVector() || LdVT.isInteger())
5687     return SDValue();
5688   // Transform a scalar load that is REPLICATEd as well as having other
5689   // use(s) to the form where the other use(s) use the first element of the
5690   // REPLICATE instead of the load. Otherwise instruction selection will not
5691   // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
5692   // point loads.
5693 
5694   SDValue Replicate;
5695   SmallVector<SDNode*, 8> OtherUses;
5696   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5697        UI != UE; ++UI) {
5698     if (UI->getOpcode() == SystemZISD::REPLICATE) {
5699       if (Replicate)
5700         return SDValue(); // Should never happen
5701       Replicate = SDValue(*UI, 0);
5702     }
5703     else if (UI.getUse().getResNo() == 0)
5704       OtherUses.push_back(*UI);
5705   }
5706   if (!Replicate || OtherUses.empty())
5707     return SDValue();
5708 
5709   SDLoc DL(N);
5710   SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
5711                               Replicate, DAG.getConstant(0, DL, MVT::i32));
5712   // Update uses of the loaded Value while preserving old chains.
5713   for (SDNode *U : OtherUses) {
5714     SmallVector<SDValue, 8> Ops;
5715     for (SDValue Op : U->ops())
5716       Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
5717     DAG.UpdateNodeOperands(U, Ops);
5718   }
5719   return SDValue(N, 0);
5720 }
5721 
5722 bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
5723   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
5724     return true;
5725   if (Subtarget.hasVectorEnhancements2())
5726     if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64)
5727       return true;
5728   return false;
5729 }
5730 
5731 static bool isVectorElementSwap(ArrayRef<int> M, EVT VT) {
5732   if (!VT.isVector() || !VT.isSimple() ||
5733       VT.getSizeInBits() != 128 ||
5734       VT.getScalarSizeInBits() % 8 != 0)
5735     return false;
5736 
5737   unsigned NumElts = VT.getVectorNumElements();
5738   for (unsigned i = 0; i < NumElts; ++i) {
5739     if (M[i] < 0) continue; // ignore UNDEF indices
5740     if ((unsigned) M[i] != NumElts - 1 - i)
5741       return false;
5742   }
5743 
5744   return true;
5745 }
5746 
5747 SDValue SystemZTargetLowering::combineSTORE(
5748     SDNode *N, DAGCombinerInfo &DCI) const {
5749   SelectionDAG &DAG = DCI.DAG;
5750   auto *SN = cast<StoreSDNode>(N);
5751   auto &Op1 = N->getOperand(1);
5752   EVT MemVT = SN->getMemoryVT();
5753   // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
5754   // for the extraction to be done on a vMiN value, so that we can use VSTE.
5755   // If X has wider elements then convert it to:
5756   // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
5757   if (MemVT.isInteger() && SN->isTruncatingStore()) {
5758     if (SDValue Value =
5759             combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
5760       DCI.AddToWorklist(Value.getNode());
5761 
5762       // Rewrite the store with the new form of stored value.
5763       return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
5764                                SN->getBasePtr(), SN->getMemoryVT(),
5765                                SN->getMemOperand());
5766     }
5767   }
5768   // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
5769   if (!SN->isTruncatingStore() &&
5770       Op1.getOpcode() == ISD::BSWAP &&
5771       Op1.getNode()->hasOneUse() &&
5772       canLoadStoreByteSwapped(Op1.getValueType())) {
5773 
5774       SDValue BSwapOp = Op1.getOperand(0);
5775 
5776       if (BSwapOp.getValueType() == MVT::i16)
5777         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
5778 
5779       SDValue Ops[] = {
5780         N->getOperand(0), BSwapOp, N->getOperand(2)
5781       };
5782 
5783       return
5784         DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
5785                                 Ops, MemVT, SN->getMemOperand());
5786     }
5787   // Combine STORE (element-swap) into VSTER
5788   if (!SN->isTruncatingStore() &&
5789       Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
5790       Op1.getNode()->hasOneUse() &&
5791       Subtarget.hasVectorEnhancements2()) {
5792     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
5793     ArrayRef<int> ShuffleMask = SVN->getMask();
5794     if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
5795       SDValue Ops[] = {
5796         N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
5797       };
5798 
5799       return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
5800                                      DAG.getVTList(MVT::Other),
5801                                      Ops, MemVT, SN->getMemOperand());
5802     }
5803   }
5804 
5805   return SDValue();
5806 }
5807 
5808 SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
5809     SDNode *N, DAGCombinerInfo &DCI) const {
5810   SelectionDAG &DAG = DCI.DAG;
5811   // Combine element-swap (LOAD) into VLER
5812   if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
5813       N->getOperand(0).hasOneUse() &&
5814       Subtarget.hasVectorEnhancements2()) {
5815     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5816     ArrayRef<int> ShuffleMask = SVN->getMask();
5817     if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
5818       SDValue Load = N->getOperand(0);
5819       LoadSDNode *LD = cast<LoadSDNode>(Load);
5820 
5821       // Create the element-swapping load.
5822       SDValue Ops[] = {
5823         LD->getChain(),    // Chain
5824         LD->getBasePtr()   // Ptr
5825       };
5826       SDValue ESLoad =
5827         DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
5828                                 DAG.getVTList(LD->getValueType(0), MVT::Other),
5829                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
5830 
5831       // First, combine the VECTOR_SHUFFLE away.  This makes the value produced
5832       // by the load dead.
5833       DCI.CombineTo(N, ESLoad);
5834 
5835       // Next, combine the load away, we give it a bogus result value but a real
5836       // chain result.  The result value is dead because the shuffle is dead.
5837       DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
5838 
5839       // Return N so it doesn't get rechecked!
5840       return SDValue(N, 0);
5841     }
5842   }
5843 
5844   return SDValue();
5845 }
5846 
5847 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
5848     SDNode *N, DAGCombinerInfo &DCI) const {
5849   SelectionDAG &DAG = DCI.DAG;
5850 
5851   if (!Subtarget.hasVector())
5852     return SDValue();
5853 
5854   // Look through bitcasts that retain the number of vector elements.
5855   SDValue Op = N->getOperand(0);
5856   if (Op.getOpcode() == ISD::BITCAST &&
5857       Op.getValueType().isVector() &&
5858       Op.getOperand(0).getValueType().isVector() &&
5859       Op.getValueType().getVectorNumElements() ==
5860       Op.getOperand(0).getValueType().getVectorNumElements())
5861     Op = Op.getOperand(0);
5862 
5863   // Pull BSWAP out of a vector extraction.
5864   if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
5865     EVT VecVT = Op.getValueType();
5866     EVT EltVT = VecVT.getVectorElementType();
5867     Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
5868                      Op.getOperand(0), N->getOperand(1));
5869     DCI.AddToWorklist(Op.getNode());
5870     Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
5871     if (EltVT != N->getValueType(0)) {
5872       DCI.AddToWorklist(Op.getNode());
5873       Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
5874     }
5875     return Op;
5876   }
5877 
5878   // Try to simplify a vector extraction.
5879   if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5880     SDValue Op0 = N->getOperand(0);
5881     EVT VecVT = Op0.getValueType();
5882     return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
5883                           IndexN->getZExtValue(), DCI, false);
5884   }
5885   return SDValue();
5886 }
5887 
5888 SDValue SystemZTargetLowering::combineJOIN_DWORDS(
5889     SDNode *N, DAGCombinerInfo &DCI) const {
5890   SelectionDAG &DAG = DCI.DAG;
5891   // (join_dwords X, X) == (replicate X)
5892   if (N->getOperand(0) == N->getOperand(1))
5893     return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
5894                        N->getOperand(0));
5895   return SDValue();
5896 }
5897 
5898 SDValue SystemZTargetLowering::combineFP_ROUND(
5899     SDNode *N, DAGCombinerInfo &DCI) const {
5900 
5901   if (!Subtarget.hasVector())
5902     return SDValue();
5903 
5904   // (fpround (extract_vector_elt X 0))
5905   // (fpround (extract_vector_elt X 1)) ->
5906   // (extract_vector_elt (VROUND X) 0)
5907   // (extract_vector_elt (VROUND X) 2)
5908   //
5909   // This is a special case since the target doesn't really support v2f32s.
5910   SelectionDAG &DAG = DCI.DAG;
5911   SDValue Op0 = N->getOperand(0);
5912   if (N->getValueType(0) == MVT::f32 &&
5913       Op0.hasOneUse() &&
5914       Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5915       Op0.getOperand(0).getValueType() == MVT::v2f64 &&
5916       Op0.getOperand(1).getOpcode() == ISD::Constant &&
5917       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
5918     SDValue Vec = Op0.getOperand(0);
5919     for (auto *U : Vec->uses()) {
5920       if (U != Op0.getNode() &&
5921           U->hasOneUse() &&
5922           U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5923           U->getOperand(0) == Vec &&
5924           U->getOperand(1).getOpcode() == ISD::Constant &&
5925           cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
5926         SDValue OtherRound = SDValue(*U->use_begin(), 0);
5927         if (OtherRound.getOpcode() == ISD::FP_ROUND &&
5928             OtherRound.getOperand(0) == SDValue(U, 0) &&
5929             OtherRound.getValueType() == MVT::f32) {
5930           SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
5931                                        MVT::v4f32, Vec);
5932           DCI.AddToWorklist(VRound.getNode());
5933           SDValue Extract1 =
5934             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
5935                         VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
5936           DCI.AddToWorklist(Extract1.getNode());
5937           DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
5938           SDValue Extract0 =
5939             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
5940                         VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
5941           return Extract0;
5942         }
5943       }
5944     }
5945   }
5946   return SDValue();
5947 }
5948 
5949 SDValue SystemZTargetLowering::combineFP_EXTEND(
5950     SDNode *N, DAGCombinerInfo &DCI) const {
5951 
5952   if (!Subtarget.hasVector())
5953     return SDValue();
5954 
5955   // (fpextend (extract_vector_elt X 0))
5956   // (fpextend (extract_vector_elt X 2)) ->
5957   // (extract_vector_elt (VEXTEND X) 0)
5958   // (extract_vector_elt (VEXTEND X) 1)
5959   //
5960   // This is a special case since the target doesn't really support v2f32s.
5961   SelectionDAG &DAG = DCI.DAG;
5962   SDValue Op0 = N->getOperand(0);
5963   if (N->getValueType(0) == MVT::f64 &&
5964       Op0.hasOneUse() &&
5965       Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5966       Op0.getOperand(0).getValueType() == MVT::v4f32 &&
5967       Op0.getOperand(1).getOpcode() == ISD::Constant &&
5968       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
5969     SDValue Vec = Op0.getOperand(0);
5970     for (auto *U : Vec->uses()) {
5971       if (U != Op0.getNode() &&
5972           U->hasOneUse() &&
5973           U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5974           U->getOperand(0) == Vec &&
5975           U->getOperand(1).getOpcode() == ISD::Constant &&
5976           cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 2) {
5977         SDValue OtherExtend = SDValue(*U->use_begin(), 0);
5978         if (OtherExtend.getOpcode() == ISD::FP_EXTEND &&
5979             OtherExtend.getOperand(0) == SDValue(U, 0) &&
5980             OtherExtend.getValueType() == MVT::f64) {
5981           SDValue VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
5982                                         MVT::v2f64, Vec);
5983           DCI.AddToWorklist(VExtend.getNode());
5984           SDValue Extract1 =
5985             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
5986                         VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
5987           DCI.AddToWorklist(Extract1.getNode());
5988           DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
5989           SDValue Extract0 =
5990             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
5991                         VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
5992           return Extract0;
5993         }
5994       }
5995     }
5996   }
5997   return SDValue();
5998 }
5999 
6000 SDValue SystemZTargetLowering::combineBSWAP(
6001     SDNode *N, DAGCombinerInfo &DCI) const {
6002   SelectionDAG &DAG = DCI.DAG;
6003   // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
6004   if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6005       N->getOperand(0).hasOneUse() &&
6006       canLoadStoreByteSwapped(N->getValueType(0))) {
6007       SDValue Load = N->getOperand(0);
6008       LoadSDNode *LD = cast<LoadSDNode>(Load);
6009 
6010       // Create the byte-swapping load.
6011       SDValue Ops[] = {
6012         LD->getChain(),    // Chain
6013         LD->getBasePtr()   // Ptr
6014       };
6015       EVT LoadVT = N->getValueType(0);
6016       if (LoadVT == MVT::i16)
6017         LoadVT = MVT::i32;
6018       SDValue BSLoad =
6019         DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
6020                                 DAG.getVTList(LoadVT, MVT::Other),
6021                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
6022 
6023       // If this is an i16 load, insert the truncate.
6024       SDValue ResVal = BSLoad;
6025       if (N->getValueType(0) == MVT::i16)
6026         ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
6027 
6028       // First, combine the bswap away.  This makes the value produced by the
6029       // load dead.
6030       DCI.CombineTo(N, ResVal);
6031 
6032       // Next, combine the load away, we give it a bogus result value but a real
6033       // chain result.  The result value is dead because the bswap is dead.
6034       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6035 
6036       // Return N so it doesn't get rechecked!
6037       return SDValue(N, 0);
6038     }
6039 
6040   // Look through bitcasts that retain the number of vector elements.
6041   SDValue Op = N->getOperand(0);
6042   if (Op.getOpcode() == ISD::BITCAST &&
6043       Op.getValueType().isVector() &&
6044       Op.getOperand(0).getValueType().isVector() &&
6045       Op.getValueType().getVectorNumElements() ==
6046       Op.getOperand(0).getValueType().getVectorNumElements())
6047     Op = Op.getOperand(0);
6048 
6049   // Push BSWAP into a vector insertion if at least one side then simplifies.
6050   if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
6051     SDValue Vec = Op.getOperand(0);
6052     SDValue Elt = Op.getOperand(1);
6053     SDValue Idx = Op.getOperand(2);
6054 
6055     if (DAG.isConstantIntBuildVectorOrConstantInt(Vec) ||
6056         Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
6057         DAG.isConstantIntBuildVectorOrConstantInt(Elt) ||
6058         Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
6059         (canLoadStoreByteSwapped(N->getValueType(0)) &&
6060          ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
6061       EVT VecVT = N->getValueType(0);
6062       EVT EltVT = N->getValueType(0).getVectorElementType();
6063       if (VecVT != Vec.getValueType()) {
6064         Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
6065         DCI.AddToWorklist(Vec.getNode());
6066       }
6067       if (EltVT != Elt.getValueType()) {
6068         Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
6069         DCI.AddToWorklist(Elt.getNode());
6070       }
6071       Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
6072       DCI.AddToWorklist(Vec.getNode());
6073       Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
6074       DCI.AddToWorklist(Elt.getNode());
6075       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
6076                          Vec, Elt, Idx);
6077     }
6078   }
6079 
6080   // Push BSWAP into a vector shuffle if at least one side then simplifies.
6081   ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
6082   if (SV && Op.hasOneUse()) {
6083     SDValue Op0 = Op.getOperand(0);
6084     SDValue Op1 = Op.getOperand(1);
6085 
6086     if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
6087         Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
6088         DAG.isConstantIntBuildVectorOrConstantInt(Op1) ||
6089         Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
6090       EVT VecVT = N->getValueType(0);
6091       if (VecVT != Op0.getValueType()) {
6092         Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
6093         DCI.AddToWorklist(Op0.getNode());
6094       }
6095       if (VecVT != Op1.getValueType()) {
6096         Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
6097         DCI.AddToWorklist(Op1.getNode());
6098       }
6099       Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
6100       DCI.AddToWorklist(Op0.getNode());
6101       Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
6102       DCI.AddToWorklist(Op1.getNode());
6103       return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
6104     }
6105   }
6106 
6107   return SDValue();
6108 }
6109 
6110 static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask) {
6111   // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
6112   // set by the CCReg instruction using the CCValid / CCMask masks,
6113   // If the CCReg instruction is itself a ICMP testing the condition
6114   // code set by some other instruction, see whether we can directly
6115   // use that condition code.
6116 
6117   // Verify that we have an ICMP against some constant.
6118   if (CCValid != SystemZ::CCMASK_ICMP)
6119     return false;
6120   auto *ICmp = CCReg.getNode();
6121   if (ICmp->getOpcode() != SystemZISD::ICMP)
6122     return false;
6123   auto *CompareLHS = ICmp->getOperand(0).getNode();
6124   auto *CompareRHS = dyn_cast<ConstantSDNode>(ICmp->getOperand(1));
6125   if (!CompareRHS)
6126     return false;
6127 
6128   // Optimize the case where CompareLHS is a SELECT_CCMASK.
6129   if (CompareLHS->getOpcode() == SystemZISD::SELECT_CCMASK) {
6130     // Verify that we have an appropriate mask for a EQ or NE comparison.
6131     bool Invert = false;
6132     if (CCMask == SystemZ::CCMASK_CMP_NE)
6133       Invert = !Invert;
6134     else if (CCMask != SystemZ::CCMASK_CMP_EQ)
6135       return false;
6136 
6137     // Verify that the ICMP compares against one of select values.
6138     auto *TrueVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(0));
6139     if (!TrueVal)
6140       return false;
6141     auto *FalseVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1));
6142     if (!FalseVal)
6143       return false;
6144     if (CompareRHS->getZExtValue() == FalseVal->getZExtValue())
6145       Invert = !Invert;
6146     else if (CompareRHS->getZExtValue() != TrueVal->getZExtValue())
6147       return false;
6148 
6149     // Compute the effective CC mask for the new branch or select.
6150     auto *NewCCValid = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(2));
6151     auto *NewCCMask = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(3));
6152     if (!NewCCValid || !NewCCMask)
6153       return false;
6154     CCValid = NewCCValid->getZExtValue();
6155     CCMask = NewCCMask->getZExtValue();
6156     if (Invert)
6157       CCMask ^= CCValid;
6158 
6159     // Return the updated CCReg link.
6160     CCReg = CompareLHS->getOperand(4);
6161     return true;
6162   }
6163 
6164   // Optimize the case where CompareRHS is (SRA (SHL (IPM))).
6165   if (CompareLHS->getOpcode() == ISD::SRA) {
6166     auto *SRACount = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1));
6167     if (!SRACount || SRACount->getZExtValue() != 30)
6168       return false;
6169     auto *SHL = CompareLHS->getOperand(0).getNode();
6170     if (SHL->getOpcode() != ISD::SHL)
6171       return false;
6172     auto *SHLCount = dyn_cast<ConstantSDNode>(SHL->getOperand(1));
6173     if (!SHLCount || SHLCount->getZExtValue() != 30 - SystemZ::IPM_CC)
6174       return false;
6175     auto *IPM = SHL->getOperand(0).getNode();
6176     if (IPM->getOpcode() != SystemZISD::IPM)
6177       return false;
6178 
6179     // Avoid introducing CC spills (because SRA would clobber CC).
6180     if (!CompareLHS->hasOneUse())
6181       return false;
6182     // Verify that the ICMP compares against zero.
6183     if (CompareRHS->getZExtValue() != 0)
6184       return false;
6185 
6186     // Compute the effective CC mask for the new branch or select.
6187     switch (CCMask) {
6188     case SystemZ::CCMASK_CMP_EQ: break;
6189     case SystemZ::CCMASK_CMP_NE: break;
6190     case SystemZ::CCMASK_CMP_LT: CCMask = SystemZ::CCMASK_CMP_GT; break;
6191     case SystemZ::CCMASK_CMP_GT: CCMask = SystemZ::CCMASK_CMP_LT; break;
6192     case SystemZ::CCMASK_CMP_LE: CCMask = SystemZ::CCMASK_CMP_GE; break;
6193     case SystemZ::CCMASK_CMP_GE: CCMask = SystemZ::CCMASK_CMP_LE; break;
6194     default: return false;
6195     }
6196 
6197     // Return the updated CCReg link.
6198     CCReg = IPM->getOperand(0);
6199     return true;
6200   }
6201 
6202   return false;
6203 }
6204 
6205 SDValue SystemZTargetLowering::combineBR_CCMASK(
6206     SDNode *N, DAGCombinerInfo &DCI) const {
6207   SelectionDAG &DAG = DCI.DAG;
6208 
6209   // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
6210   auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
6211   auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
6212   if (!CCValid || !CCMask)
6213     return SDValue();
6214 
6215   int CCValidVal = CCValid->getZExtValue();
6216   int CCMaskVal = CCMask->getZExtValue();
6217   SDValue Chain = N->getOperand(0);
6218   SDValue CCReg = N->getOperand(4);
6219 
6220   if (combineCCMask(CCReg, CCValidVal, CCMaskVal))
6221     return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
6222                        Chain,
6223                        DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
6224                        DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
6225                        N->getOperand(3), CCReg);
6226   return SDValue();
6227 }
6228 
6229 SDValue SystemZTargetLowering::combineSELECT_CCMASK(
6230     SDNode *N, DAGCombinerInfo &DCI) const {
6231   SelectionDAG &DAG = DCI.DAG;
6232 
6233   // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
6234   auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
6235   auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
6236   if (!CCValid || !CCMask)
6237     return SDValue();
6238 
6239   int CCValidVal = CCValid->getZExtValue();
6240   int CCMaskVal = CCMask->getZExtValue();
6241   SDValue CCReg = N->getOperand(4);
6242 
6243   if (combineCCMask(CCReg, CCValidVal, CCMaskVal))
6244     return DAG.getNode(SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0),
6245                        N->getOperand(0), N->getOperand(1),
6246                        DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
6247                        DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
6248                        CCReg);
6249   return SDValue();
6250 }
6251 
6252 
6253 SDValue SystemZTargetLowering::combineGET_CCMASK(
6254     SDNode *N, DAGCombinerInfo &DCI) const {
6255 
6256   // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
6257   auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
6258   auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
6259   if (!CCValid || !CCMask)
6260     return SDValue();
6261   int CCValidVal = CCValid->getZExtValue();
6262   int CCMaskVal = CCMask->getZExtValue();
6263 
6264   SDValue Select = N->getOperand(0);
6265   if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
6266     return SDValue();
6267 
6268   auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
6269   auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
6270   if (!SelectCCValid || !SelectCCMask)
6271     return SDValue();
6272   int SelectCCValidVal = SelectCCValid->getZExtValue();
6273   int SelectCCMaskVal = SelectCCMask->getZExtValue();
6274 
6275   auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
6276   auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
6277   if (!TrueVal || !FalseVal)
6278     return SDValue();
6279   if (TrueVal->getZExtValue() != 0 && FalseVal->getZExtValue() == 0)
6280     ;
6281   else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() != 0)
6282     SelectCCMaskVal ^= SelectCCValidVal;
6283   else
6284     return SDValue();
6285 
6286   if (SelectCCValidVal & ~CCValidVal)
6287     return SDValue();
6288   if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
6289     return SDValue();
6290 
6291   return Select->getOperand(4);
6292 }
6293 
6294 SDValue SystemZTargetLowering::combineIntDIVREM(
6295     SDNode *N, DAGCombinerInfo &DCI) const {
6296   SelectionDAG &DAG = DCI.DAG;
6297   EVT VT = N->getValueType(0);
6298   // In the case where the divisor is a vector of constants a cheaper
6299   // sequence of instructions can replace the divide. BuildSDIV is called to
6300   // do this during DAG combining, but it only succeeds when it can build a
6301   // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
6302   // since it is not Legal but Custom it can only happen before
6303   // legalization. Therefore we must scalarize this early before Combine
6304   // 1. For widened vectors, this is already the result of type legalization.
6305   if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
6306       DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
6307     return DAG.UnrollVectorOp(N);
6308   return SDValue();
6309 }
6310 
6311 SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
6312   if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
6313     return N->getOperand(0);
6314   return N;
6315 }
6316 
6317 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
6318                                                  DAGCombinerInfo &DCI) const {
6319   switch(N->getOpcode()) {
6320   default: break;
6321   case ISD::ZERO_EXTEND:        return combineZERO_EXTEND(N, DCI);
6322   case ISD::SIGN_EXTEND:        return combineSIGN_EXTEND(N, DCI);
6323   case ISD::SIGN_EXTEND_INREG:  return combineSIGN_EXTEND_INREG(N, DCI);
6324   case SystemZISD::MERGE_HIGH:
6325   case SystemZISD::MERGE_LOW:   return combineMERGE(N, DCI);
6326   case ISD::LOAD:               return combineLOAD(N, DCI);
6327   case ISD::STORE:              return combineSTORE(N, DCI);
6328   case ISD::VECTOR_SHUFFLE:     return combineVECTOR_SHUFFLE(N, DCI);
6329   case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
6330   case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
6331   case ISD::FP_ROUND:           return combineFP_ROUND(N, DCI);
6332   case ISD::FP_EXTEND:          return combineFP_EXTEND(N, DCI);
6333   case ISD::BSWAP:              return combineBSWAP(N, DCI);
6334   case SystemZISD::BR_CCMASK:   return combineBR_CCMASK(N, DCI);
6335   case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
6336   case SystemZISD::GET_CCMASK:  return combineGET_CCMASK(N, DCI);
6337   case ISD::SDIV:
6338   case ISD::UDIV:
6339   case ISD::SREM:
6340   case ISD::UREM:               return combineIntDIVREM(N, DCI);
6341   }
6342 
6343   return SDValue();
6344 }
6345 
6346 // Return the demanded elements for the OpNo source operand of Op. DemandedElts
6347 // are for Op.
6348 static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
6349                                     unsigned OpNo) {
6350   EVT VT = Op.getValueType();
6351   unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
6352   APInt SrcDemE;
6353   unsigned Opcode = Op.getOpcode();
6354   if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
6355     unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6356     switch (Id) {
6357     case Intrinsic::s390_vpksh:   // PACKS
6358     case Intrinsic::s390_vpksf:
6359     case Intrinsic::s390_vpksg:
6360     case Intrinsic::s390_vpkshs:  // PACKS_CC
6361     case Intrinsic::s390_vpksfs:
6362     case Intrinsic::s390_vpksgs:
6363     case Intrinsic::s390_vpklsh:  // PACKLS
6364     case Intrinsic::s390_vpklsf:
6365     case Intrinsic::s390_vpklsg:
6366     case Intrinsic::s390_vpklshs: // PACKLS_CC
6367     case Intrinsic::s390_vpklsfs:
6368     case Intrinsic::s390_vpklsgs:
6369       // VECTOR PACK truncates the elements of two source vectors into one.
6370       SrcDemE = DemandedElts;
6371       if (OpNo == 2)
6372         SrcDemE.lshrInPlace(NumElts / 2);
6373       SrcDemE = SrcDemE.trunc(NumElts / 2);
6374       break;
6375       // VECTOR UNPACK extends half the elements of the source vector.
6376     case Intrinsic::s390_vuphb:  // VECTOR UNPACK HIGH
6377     case Intrinsic::s390_vuphh:
6378     case Intrinsic::s390_vuphf:
6379     case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
6380     case Intrinsic::s390_vuplhh:
6381     case Intrinsic::s390_vuplhf:
6382       SrcDemE = APInt(NumElts * 2, 0);
6383       SrcDemE.insertBits(DemandedElts, 0);
6384       break;
6385     case Intrinsic::s390_vuplb:  // VECTOR UNPACK LOW
6386     case Intrinsic::s390_vuplhw:
6387     case Intrinsic::s390_vuplf:
6388     case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
6389     case Intrinsic::s390_vupllh:
6390     case Intrinsic::s390_vupllf:
6391       SrcDemE = APInt(NumElts * 2, 0);
6392       SrcDemE.insertBits(DemandedElts, NumElts);
6393       break;
6394     case Intrinsic::s390_vpdi: {
6395       // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
6396       SrcDemE = APInt(NumElts, 0);
6397       if (!DemandedElts[OpNo - 1])
6398         break;
6399       unsigned Mask = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6400       unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
6401       // Demand input element 0 or 1, given by the mask bit value.
6402       SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
6403       break;
6404     }
6405     case Intrinsic::s390_vsldb: {
6406       // VECTOR SHIFT LEFT DOUBLE BY BYTE
6407       assert(VT == MVT::v16i8 && "Unexpected type.");
6408       unsigned FirstIdx = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6409       assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
6410       unsigned NumSrc0Els = 16 - FirstIdx;
6411       SrcDemE = APInt(NumElts, 0);
6412       if (OpNo == 1) {
6413         APInt DemEls = DemandedElts.trunc(NumSrc0Els);
6414         SrcDemE.insertBits(DemEls, FirstIdx);
6415       } else {
6416         APInt DemEls = DemandedElts.lshr(NumSrc0Els);
6417         SrcDemE.insertBits(DemEls, 0);
6418       }
6419       break;
6420     }
6421     case Intrinsic::s390_vperm:
6422       SrcDemE = APInt(NumElts, 1);
6423       break;
6424     default:
6425       llvm_unreachable("Unhandled intrinsic.");
6426       break;
6427     }
6428   } else {
6429     switch (Opcode) {
6430     case SystemZISD::JOIN_DWORDS:
6431       // Scalar operand.
6432       SrcDemE = APInt(1, 1);
6433       break;
6434     case SystemZISD::SELECT_CCMASK:
6435       SrcDemE = DemandedElts;
6436       break;
6437     default:
6438       llvm_unreachable("Unhandled opcode.");
6439       break;
6440     }
6441   }
6442   return SrcDemE;
6443 }
6444 
6445 static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known,
6446                                   const APInt &DemandedElts,
6447                                   const SelectionDAG &DAG, unsigned Depth,
6448                                   unsigned OpNo) {
6449   APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
6450   APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
6451   KnownBits LHSKnown =
6452       DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
6453   KnownBits RHSKnown =
6454       DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
6455   Known.Zero = LHSKnown.Zero & RHSKnown.Zero;
6456   Known.One = LHSKnown.One & RHSKnown.One;
6457 }
6458 
6459 void
6460 SystemZTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
6461                                                      KnownBits &Known,
6462                                                      const APInt &DemandedElts,
6463                                                      const SelectionDAG &DAG,
6464                                                      unsigned Depth) const {
6465   Known.resetAll();
6466 
6467   // Intrinsic CC result is returned in the two low bits.
6468   unsigned tmp0, tmp1; // not used
6469   if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, tmp0, tmp1)) {
6470     Known.Zero.setBitsFrom(2);
6471     return;
6472   }
6473   EVT VT = Op.getValueType();
6474   if (Op.getResNo() != 0 || VT == MVT::Untyped)
6475     return;
6476   assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
6477           "KnownBits does not match VT in bitwidth");
6478   assert ((!VT.isVector() ||
6479            (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
6480           "DemandedElts does not match VT number of elements");
6481   unsigned BitWidth = Known.getBitWidth();
6482   unsigned Opcode = Op.getOpcode();
6483   if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
6484     bool IsLogical = false;
6485     unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6486     switch (Id) {
6487     case Intrinsic::s390_vpksh:   // PACKS
6488     case Intrinsic::s390_vpksf:
6489     case Intrinsic::s390_vpksg:
6490     case Intrinsic::s390_vpkshs:  // PACKS_CC
6491     case Intrinsic::s390_vpksfs:
6492     case Intrinsic::s390_vpksgs:
6493     case Intrinsic::s390_vpklsh:  // PACKLS
6494     case Intrinsic::s390_vpklsf:
6495     case Intrinsic::s390_vpklsg:
6496     case Intrinsic::s390_vpklshs: // PACKLS_CC
6497     case Intrinsic::s390_vpklsfs:
6498     case Intrinsic::s390_vpklsgs:
6499     case Intrinsic::s390_vpdi:
6500     case Intrinsic::s390_vsldb:
6501     case Intrinsic::s390_vperm:
6502       computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
6503       break;
6504     case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
6505     case Intrinsic::s390_vuplhh:
6506     case Intrinsic::s390_vuplhf:
6507     case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
6508     case Intrinsic::s390_vupllh:
6509     case Intrinsic::s390_vupllf:
6510       IsLogical = true;
6511       LLVM_FALLTHROUGH;
6512     case Intrinsic::s390_vuphb:  // VECTOR UNPACK HIGH
6513     case Intrinsic::s390_vuphh:
6514     case Intrinsic::s390_vuphf:
6515     case Intrinsic::s390_vuplb:  // VECTOR UNPACK LOW
6516     case Intrinsic::s390_vuplhw:
6517     case Intrinsic::s390_vuplf: {
6518       SDValue SrcOp = Op.getOperand(1);
6519       APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
6520       Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
6521       if (IsLogical) {
6522         Known = Known.zext(BitWidth, true);
6523       } else
6524         Known = Known.sext(BitWidth);
6525       break;
6526     }
6527     default:
6528       break;
6529     }
6530   } else {
6531     switch (Opcode) {
6532     case SystemZISD::JOIN_DWORDS:
6533     case SystemZISD::SELECT_CCMASK:
6534       computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
6535       break;
6536     case SystemZISD::REPLICATE: {
6537       SDValue SrcOp = Op.getOperand(0);
6538       Known = DAG.computeKnownBits(SrcOp, Depth + 1);
6539       if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
6540         Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
6541       break;
6542     }
6543     default:
6544       break;
6545     }
6546   }
6547 
6548   // Known has the width of the source operand(s). Adjust if needed to match
6549   // the passed bitwidth.
6550   if (Known.getBitWidth() != BitWidth)
6551     Known = Known.zextOrTrunc(BitWidth, false);
6552 }
6553 
6554 static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
6555                                         const SelectionDAG &DAG, unsigned Depth,
6556                                         unsigned OpNo) {
6557   APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
6558   unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
6559   if (LHS == 1) return 1; // Early out.
6560   APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
6561   unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
6562   if (RHS == 1) return 1; // Early out.
6563   unsigned Common = std::min(LHS, RHS);
6564   unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
6565   EVT VT = Op.getValueType();
6566   unsigned VTBits = VT.getScalarSizeInBits();
6567   if (SrcBitWidth > VTBits) { // PACK
6568     unsigned SrcExtraBits = SrcBitWidth - VTBits;
6569     if (Common > SrcExtraBits)
6570       return (Common - SrcExtraBits);
6571     return 1;
6572   }
6573   assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
6574   return Common;
6575 }
6576 
6577 unsigned
6578 SystemZTargetLowering::ComputeNumSignBitsForTargetNode(
6579     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
6580     unsigned Depth) const {
6581   if (Op.getResNo() != 0)
6582     return 1;
6583   unsigned Opcode = Op.getOpcode();
6584   if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
6585     unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6586     switch (Id) {
6587     case Intrinsic::s390_vpksh:   // PACKS
6588     case Intrinsic::s390_vpksf:
6589     case Intrinsic::s390_vpksg:
6590     case Intrinsic::s390_vpkshs:  // PACKS_CC
6591     case Intrinsic::s390_vpksfs:
6592     case Intrinsic::s390_vpksgs:
6593     case Intrinsic::s390_vpklsh:  // PACKLS
6594     case Intrinsic::s390_vpklsf:
6595     case Intrinsic::s390_vpklsg:
6596     case Intrinsic::s390_vpklshs: // PACKLS_CC
6597     case Intrinsic::s390_vpklsfs:
6598     case Intrinsic::s390_vpklsgs:
6599     case Intrinsic::s390_vpdi:
6600     case Intrinsic::s390_vsldb:
6601     case Intrinsic::s390_vperm:
6602       return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
6603     case Intrinsic::s390_vuphb:  // VECTOR UNPACK HIGH
6604     case Intrinsic::s390_vuphh:
6605     case Intrinsic::s390_vuphf:
6606     case Intrinsic::s390_vuplb:  // VECTOR UNPACK LOW
6607     case Intrinsic::s390_vuplhw:
6608     case Intrinsic::s390_vuplf: {
6609       SDValue PackedOp = Op.getOperand(1);
6610       APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
6611       unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
6612       EVT VT = Op.getValueType();
6613       unsigned VTBits = VT.getScalarSizeInBits();
6614       Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
6615       return Tmp;
6616     }
6617     default:
6618       break;
6619     }
6620   } else {
6621     switch (Opcode) {
6622     case SystemZISD::SELECT_CCMASK:
6623       return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
6624     default:
6625       break;
6626     }
6627   }
6628 
6629   return 1;
6630 }
6631 
6632 //===----------------------------------------------------------------------===//
6633 // Custom insertion
6634 //===----------------------------------------------------------------------===//
6635 
6636 // Create a new basic block after MBB.
6637 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
6638   MachineFunction &MF = *MBB->getParent();
6639   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
6640   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
6641   return NewMBB;
6642 }
6643 
6644 // Split MBB after MI and return the new block (the one that contains
6645 // instructions after MI).
6646 static MachineBasicBlock *splitBlockAfter(MachineBasicBlock::iterator MI,
6647                                           MachineBasicBlock *MBB) {
6648   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
6649   NewMBB->splice(NewMBB->begin(), MBB,
6650                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6651   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
6652   return NewMBB;
6653 }
6654 
6655 // Split MBB before MI and return the new block (the one that contains MI).
6656 static MachineBasicBlock *splitBlockBefore(MachineBasicBlock::iterator MI,
6657                                            MachineBasicBlock *MBB) {
6658   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
6659   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
6660   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
6661   return NewMBB;
6662 }
6663 
6664 // Force base value Base into a register before MI.  Return the register.
6665 static Register forceReg(MachineInstr &MI, MachineOperand &Base,
6666                          const SystemZInstrInfo *TII) {
6667   if (Base.isReg())
6668     return Base.getReg();
6669 
6670   MachineBasicBlock *MBB = MI.getParent();
6671   MachineFunction &MF = *MBB->getParent();
6672   MachineRegisterInfo &MRI = MF.getRegInfo();
6673 
6674   Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
6675   BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
6676       .add(Base)
6677       .addImm(0)
6678       .addReg(0);
6679   return Reg;
6680 }
6681 
6682 // The CC operand of MI might be missing a kill marker because there
6683 // were multiple uses of CC, and ISel didn't know which to mark.
6684 // Figure out whether MI should have had a kill marker.
6685 static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB) {
6686   // Scan forward through BB for a use/def of CC.
6687   MachineBasicBlock::iterator miI(std::next(MachineBasicBlock::iterator(MI)));
6688   for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
6689     const MachineInstr& mi = *miI;
6690     if (mi.readsRegister(SystemZ::CC))
6691       return false;
6692     if (mi.definesRegister(SystemZ::CC))
6693       break; // Should have kill-flag - update below.
6694   }
6695 
6696   // If we hit the end of the block, check whether CC is live into a
6697   // successor.
6698   if (miI == MBB->end()) {
6699     for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)
6700       if ((*SI)->isLiveIn(SystemZ::CC))
6701         return false;
6702   }
6703 
6704   return true;
6705 }
6706 
6707 // Return true if it is OK for this Select pseudo-opcode to be cascaded
6708 // together with other Select pseudo-opcodes into a single basic-block with
6709 // a conditional jump around it.
6710 static bool isSelectPseudo(MachineInstr &MI) {
6711   switch (MI.getOpcode()) {
6712   case SystemZ::Select32:
6713   case SystemZ::Select64:
6714   case SystemZ::SelectF32:
6715   case SystemZ::SelectF64:
6716   case SystemZ::SelectF128:
6717   case SystemZ::SelectVR32:
6718   case SystemZ::SelectVR64:
6719   case SystemZ::SelectVR128:
6720     return true;
6721 
6722   default:
6723     return false;
6724   }
6725 }
6726 
6727 // Helper function, which inserts PHI functions into SinkMBB:
6728 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
6729 // where %FalseValue(i) and %TrueValue(i) are taken from Selects.
6730 static void createPHIsForSelects(SmallVector<MachineInstr*, 8> &Selects,
6731                                  MachineBasicBlock *TrueMBB,
6732                                  MachineBasicBlock *FalseMBB,
6733                                  MachineBasicBlock *SinkMBB) {
6734   MachineFunction *MF = TrueMBB->getParent();
6735   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
6736 
6737   MachineInstr *FirstMI = Selects.front();
6738   unsigned CCValid = FirstMI->getOperand(3).getImm();
6739   unsigned CCMask = FirstMI->getOperand(4).getImm();
6740 
6741   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
6742 
6743   // As we are creating the PHIs, we have to be careful if there is more than
6744   // one.  Later Selects may reference the results of earlier Selects, but later
6745   // PHIs have to reference the individual true/false inputs from earlier PHIs.
6746   // That also means that PHI construction must work forward from earlier to
6747   // later, and that the code must maintain a mapping from earlier PHI's
6748   // destination registers, and the registers that went into the PHI.
6749   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
6750 
6751   for (auto MI : Selects) {
6752     Register DestReg = MI->getOperand(0).getReg();
6753     Register TrueReg = MI->getOperand(1).getReg();
6754     Register FalseReg = MI->getOperand(2).getReg();
6755 
6756     // If this Select we are generating is the opposite condition from
6757     // the jump we generated, then we have to swap the operands for the
6758     // PHI that is going to be generated.
6759     if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
6760       std::swap(TrueReg, FalseReg);
6761 
6762     if (RegRewriteTable.find(TrueReg) != RegRewriteTable.end())
6763       TrueReg = RegRewriteTable[TrueReg].first;
6764 
6765     if (RegRewriteTable.find(FalseReg) != RegRewriteTable.end())
6766       FalseReg = RegRewriteTable[FalseReg].second;
6767 
6768     DebugLoc DL = MI->getDebugLoc();
6769     BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
6770       .addReg(TrueReg).addMBB(TrueMBB)
6771       .addReg(FalseReg).addMBB(FalseMBB);
6772 
6773     // Add this PHI to the rewrite table.
6774     RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
6775   }
6776 
6777   MF->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
6778 }
6779 
6780 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
6781 MachineBasicBlock *
6782 SystemZTargetLowering::emitSelect(MachineInstr &MI,
6783                                   MachineBasicBlock *MBB) const {
6784   assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
6785   const SystemZInstrInfo *TII =
6786       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
6787 
6788   unsigned CCValid = MI.getOperand(3).getImm();
6789   unsigned CCMask = MI.getOperand(4).getImm();
6790 
6791   // If we have a sequence of Select* pseudo instructions using the
6792   // same condition code value, we want to expand all of them into
6793   // a single pair of basic blocks using the same condition.
6794   SmallVector<MachineInstr*, 8> Selects;
6795   SmallVector<MachineInstr*, 8> DbgValues;
6796   Selects.push_back(&MI);
6797   unsigned Count = 0;
6798   for (MachineBasicBlock::iterator NextMIIt =
6799          std::next(MachineBasicBlock::iterator(MI));
6800        NextMIIt != MBB->end(); ++NextMIIt) {
6801     if (NextMIIt->definesRegister(SystemZ::CC))
6802       break;
6803     if (isSelectPseudo(*NextMIIt)) {
6804       assert(NextMIIt->getOperand(3).getImm() == CCValid &&
6805              "Bad CCValid operands since CC was not redefined.");
6806       if (NextMIIt->getOperand(4).getImm() == CCMask ||
6807           NextMIIt->getOperand(4).getImm() == (CCValid ^ CCMask)) {
6808         Selects.push_back(&*NextMIIt);
6809         continue;
6810       }
6811       break;
6812     }
6813     bool User = false;
6814     for (auto SelMI : Selects)
6815       if (NextMIIt->readsVirtualRegister(SelMI->getOperand(0).getReg())) {
6816         User = true;
6817         break;
6818       }
6819     if (NextMIIt->isDebugInstr()) {
6820       if (User) {
6821         assert(NextMIIt->isDebugValue() && "Unhandled debug opcode.");
6822         DbgValues.push_back(&*NextMIIt);
6823       }
6824     }
6825     else if (User || ++Count > 20)
6826       break;
6827   }
6828 
6829   MachineInstr *LastMI = Selects.back();
6830   bool CCKilled =
6831       (LastMI->killsRegister(SystemZ::CC) || checkCCKill(*LastMI, MBB));
6832   MachineBasicBlock *StartMBB = MBB;
6833   MachineBasicBlock *JoinMBB  = splitBlockAfter(LastMI, MBB);
6834   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
6835 
6836   // Unless CC was killed in the last Select instruction, mark it as
6837   // live-in to both FalseMBB and JoinMBB.
6838   if (!CCKilled) {
6839     FalseMBB->addLiveIn(SystemZ::CC);
6840     JoinMBB->addLiveIn(SystemZ::CC);
6841   }
6842 
6843   //  StartMBB:
6844   //   BRC CCMask, JoinMBB
6845   //   # fallthrough to FalseMBB
6846   MBB = StartMBB;
6847   BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
6848     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
6849   MBB->addSuccessor(JoinMBB);
6850   MBB->addSuccessor(FalseMBB);
6851 
6852   //  FalseMBB:
6853   //   # fallthrough to JoinMBB
6854   MBB = FalseMBB;
6855   MBB->addSuccessor(JoinMBB);
6856 
6857   //  JoinMBB:
6858   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
6859   //  ...
6860   MBB = JoinMBB;
6861   createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
6862   for (auto SelMI : Selects)
6863     SelMI->eraseFromParent();
6864 
6865   MachineBasicBlock::iterator InsertPos = MBB->getFirstNonPHI();
6866   for (auto DbgMI : DbgValues)
6867     MBB->splice(InsertPos, StartMBB, DbgMI);
6868 
6869   return JoinMBB;
6870 }
6871 
6872 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
6873 // StoreOpcode is the store to use and Invert says whether the store should
6874 // happen when the condition is false rather than true.  If a STORE ON
6875 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
6876 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
6877                                                         MachineBasicBlock *MBB,
6878                                                         unsigned StoreOpcode,
6879                                                         unsigned STOCOpcode,
6880                                                         bool Invert) const {
6881   const SystemZInstrInfo *TII =
6882       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
6883 
6884   Register SrcReg = MI.getOperand(0).getReg();
6885   MachineOperand Base = MI.getOperand(1);
6886   int64_t Disp = MI.getOperand(2).getImm();
6887   Register IndexReg = MI.getOperand(3).getReg();
6888   unsigned CCValid = MI.getOperand(4).getImm();
6889   unsigned CCMask = MI.getOperand(5).getImm();
6890   DebugLoc DL = MI.getDebugLoc();
6891 
6892   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
6893 
6894   // Use STOCOpcode if possible.  We could use different store patterns in
6895   // order to avoid matching the index register, but the performance trade-offs
6896   // might be more complicated in that case.
6897   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
6898     if (Invert)
6899       CCMask ^= CCValid;
6900 
6901     // ISel pattern matching also adds a load memory operand of the same
6902     // address, so take special care to find the storing memory operand.
6903     MachineMemOperand *MMO = nullptr;
6904     for (auto *I : MI.memoperands())
6905       if (I->isStore()) {
6906           MMO = I;
6907           break;
6908         }
6909 
6910     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
6911       .addReg(SrcReg)
6912       .add(Base)
6913       .addImm(Disp)
6914       .addImm(CCValid)
6915       .addImm(CCMask)
6916       .addMemOperand(MMO);
6917 
6918     MI.eraseFromParent();
6919     return MBB;
6920   }
6921 
6922   // Get the condition needed to branch around the store.
6923   if (!Invert)
6924     CCMask ^= CCValid;
6925 
6926   MachineBasicBlock *StartMBB = MBB;
6927   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
6928   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
6929 
6930   // Unless CC was killed in the CondStore instruction, mark it as
6931   // live-in to both FalseMBB and JoinMBB.
6932   if (!MI.killsRegister(SystemZ::CC) && !checkCCKill(MI, JoinMBB)) {
6933     FalseMBB->addLiveIn(SystemZ::CC);
6934     JoinMBB->addLiveIn(SystemZ::CC);
6935   }
6936 
6937   //  StartMBB:
6938   //   BRC CCMask, JoinMBB
6939   //   # fallthrough to FalseMBB
6940   MBB = StartMBB;
6941   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
6942     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
6943   MBB->addSuccessor(JoinMBB);
6944   MBB->addSuccessor(FalseMBB);
6945 
6946   //  FalseMBB:
6947   //   store %SrcReg, %Disp(%Index,%Base)
6948   //   # fallthrough to JoinMBB
6949   MBB = FalseMBB;
6950   BuildMI(MBB, DL, TII->get(StoreOpcode))
6951       .addReg(SrcReg)
6952       .add(Base)
6953       .addImm(Disp)
6954       .addReg(IndexReg);
6955   MBB->addSuccessor(JoinMBB);
6956 
6957   MI.eraseFromParent();
6958   return JoinMBB;
6959 }
6960 
6961 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
6962 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
6963 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
6964 // BitSize is the width of the field in bits, or 0 if this is a partword
6965 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
6966 // is one of the operands.  Invert says whether the field should be
6967 // inverted after performing BinOpcode (e.g. for NAND).
6968 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
6969     MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
6970     unsigned BitSize, bool Invert) const {
6971   MachineFunction &MF = *MBB->getParent();
6972   const SystemZInstrInfo *TII =
6973       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
6974   MachineRegisterInfo &MRI = MF.getRegInfo();
6975   bool IsSubWord = (BitSize < 32);
6976 
6977   // Extract the operands.  Base can be a register or a frame index.
6978   // Src2 can be a register or immediate.
6979   Register Dest = MI.getOperand(0).getReg();
6980   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
6981   int64_t Disp = MI.getOperand(2).getImm();
6982   MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
6983   Register BitShift = IsSubWord ? MI.getOperand(4).getReg() : Register();
6984   Register NegBitShift = IsSubWord ? MI.getOperand(5).getReg() : Register();
6985   DebugLoc DL = MI.getDebugLoc();
6986   if (IsSubWord)
6987     BitSize = MI.getOperand(6).getImm();
6988 
6989   // Subword operations use 32-bit registers.
6990   const TargetRegisterClass *RC = (BitSize <= 32 ?
6991                                    &SystemZ::GR32BitRegClass :
6992                                    &SystemZ::GR64BitRegClass);
6993   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
6994   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
6995 
6996   // Get the right opcodes for the displacement.
6997   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
6998   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
6999   assert(LOpcode && CSOpcode && "Displacement out of range");
7000 
7001   // Create virtual registers for temporary results.
7002   Register OrigVal       = MRI.createVirtualRegister(RC);
7003   Register OldVal        = MRI.createVirtualRegister(RC);
7004   Register NewVal        = (BinOpcode || IsSubWord ?
7005                             MRI.createVirtualRegister(RC) : Src2.getReg());
7006   Register RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
7007   Register RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
7008 
7009   // Insert a basic block for the main loop.
7010   MachineBasicBlock *StartMBB = MBB;
7011   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
7012   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
7013 
7014   //  StartMBB:
7015   //   ...
7016   //   %OrigVal = L Disp(%Base)
7017   //   # fall through to LoopMMB
7018   MBB = StartMBB;
7019   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
7020   MBB->addSuccessor(LoopMBB);
7021 
7022   //  LoopMBB:
7023   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
7024   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
7025   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
7026   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
7027   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
7028   //   JNE LoopMBB
7029   //   # fall through to DoneMMB
7030   MBB = LoopMBB;
7031   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
7032     .addReg(OrigVal).addMBB(StartMBB)
7033     .addReg(Dest).addMBB(LoopMBB);
7034   if (IsSubWord)
7035     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
7036       .addReg(OldVal).addReg(BitShift).addImm(0);
7037   if (Invert) {
7038     // Perform the operation normally and then invert every bit of the field.
7039     Register Tmp = MRI.createVirtualRegister(RC);
7040     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2);
7041     if (BitSize <= 32)
7042       // XILF with the upper BitSize bits set.
7043       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
7044         .addReg(Tmp).addImm(-1U << (32 - BitSize));
7045     else {
7046       // Use LCGR and add -1 to the result, which is more compact than
7047       // an XILF, XILH pair.
7048       Register Tmp2 = MRI.createVirtualRegister(RC);
7049       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
7050       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
7051         .addReg(Tmp2).addImm(-1);
7052     }
7053   } else if (BinOpcode)
7054     // A simply binary operation.
7055     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
7056         .addReg(RotatedOldVal)
7057         .add(Src2);
7058   else if (IsSubWord)
7059     // Use RISBG to rotate Src2 into position and use it to replace the
7060     // field in RotatedOldVal.
7061     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
7062       .addReg(RotatedOldVal).addReg(Src2.getReg())
7063       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
7064   if (IsSubWord)
7065     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
7066       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
7067   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
7068       .addReg(OldVal)
7069       .addReg(NewVal)
7070       .add(Base)
7071       .addImm(Disp);
7072   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7073     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
7074   MBB->addSuccessor(LoopMBB);
7075   MBB->addSuccessor(DoneMBB);
7076 
7077   MI.eraseFromParent();
7078   return DoneMBB;
7079 }
7080 
7081 // Implement EmitInstrWithCustomInserter for pseudo
7082 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
7083 // instruction that should be used to compare the current field with the
7084 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
7085 // for when the current field should be kept.  BitSize is the width of
7086 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
7087 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
7088     MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
7089     unsigned KeepOldMask, unsigned BitSize) const {
7090   MachineFunction &MF = *MBB->getParent();
7091   const SystemZInstrInfo *TII =
7092       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7093   MachineRegisterInfo &MRI = MF.getRegInfo();
7094   bool IsSubWord = (BitSize < 32);
7095 
7096   // Extract the operands.  Base can be a register or a frame index.
7097   Register Dest = MI.getOperand(0).getReg();
7098   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
7099   int64_t Disp = MI.getOperand(2).getImm();
7100   Register Src2 = MI.getOperand(3).getReg();
7101   Register BitShift = (IsSubWord ? MI.getOperand(4).getReg() : Register());
7102   Register NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : Register());
7103   DebugLoc DL = MI.getDebugLoc();
7104   if (IsSubWord)
7105     BitSize = MI.getOperand(6).getImm();
7106 
7107   // Subword operations use 32-bit registers.
7108   const TargetRegisterClass *RC = (BitSize <= 32 ?
7109                                    &SystemZ::GR32BitRegClass :
7110                                    &SystemZ::GR64BitRegClass);
7111   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
7112   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
7113 
7114   // Get the right opcodes for the displacement.
7115   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
7116   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
7117   assert(LOpcode && CSOpcode && "Displacement out of range");
7118 
7119   // Create virtual registers for temporary results.
7120   Register OrigVal       = MRI.createVirtualRegister(RC);
7121   Register OldVal        = MRI.createVirtualRegister(RC);
7122   Register NewVal        = MRI.createVirtualRegister(RC);
7123   Register RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
7124   Register RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
7125   Register RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
7126 
7127   // Insert 3 basic blocks for the loop.
7128   MachineBasicBlock *StartMBB  = MBB;
7129   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
7130   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
7131   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
7132   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
7133 
7134   //  StartMBB:
7135   //   ...
7136   //   %OrigVal     = L Disp(%Base)
7137   //   # fall through to LoopMMB
7138   MBB = StartMBB;
7139   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
7140   MBB->addSuccessor(LoopMBB);
7141 
7142   //  LoopMBB:
7143   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
7144   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
7145   //   CompareOpcode %RotatedOldVal, %Src2
7146   //   BRC KeepOldMask, UpdateMBB
7147   MBB = LoopMBB;
7148   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
7149     .addReg(OrigVal).addMBB(StartMBB)
7150     .addReg(Dest).addMBB(UpdateMBB);
7151   if (IsSubWord)
7152     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
7153       .addReg(OldVal).addReg(BitShift).addImm(0);
7154   BuildMI(MBB, DL, TII->get(CompareOpcode))
7155     .addReg(RotatedOldVal).addReg(Src2);
7156   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7157     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
7158   MBB->addSuccessor(UpdateMBB);
7159   MBB->addSuccessor(UseAltMBB);
7160 
7161   //  UseAltMBB:
7162   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
7163   //   # fall through to UpdateMMB
7164   MBB = UseAltMBB;
7165   if (IsSubWord)
7166     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
7167       .addReg(RotatedOldVal).addReg(Src2)
7168       .addImm(32).addImm(31 + BitSize).addImm(0);
7169   MBB->addSuccessor(UpdateMBB);
7170 
7171   //  UpdateMBB:
7172   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
7173   //                        [ %RotatedAltVal, UseAltMBB ]
7174   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
7175   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
7176   //   JNE LoopMBB
7177   //   # fall through to DoneMMB
7178   MBB = UpdateMBB;
7179   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
7180     .addReg(RotatedOldVal).addMBB(LoopMBB)
7181     .addReg(RotatedAltVal).addMBB(UseAltMBB);
7182   if (IsSubWord)
7183     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
7184       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
7185   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
7186       .addReg(OldVal)
7187       .addReg(NewVal)
7188       .add(Base)
7189       .addImm(Disp);
7190   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7191     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
7192   MBB->addSuccessor(LoopMBB);
7193   MBB->addSuccessor(DoneMBB);
7194 
7195   MI.eraseFromParent();
7196   return DoneMBB;
7197 }
7198 
7199 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
7200 // instruction MI.
7201 MachineBasicBlock *
7202 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
7203                                           MachineBasicBlock *MBB) const {
7204 
7205   MachineFunction &MF = *MBB->getParent();
7206   const SystemZInstrInfo *TII =
7207       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7208   MachineRegisterInfo &MRI = MF.getRegInfo();
7209 
7210   // Extract the operands.  Base can be a register or a frame index.
7211   Register Dest = MI.getOperand(0).getReg();
7212   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
7213   int64_t Disp = MI.getOperand(2).getImm();
7214   Register OrigCmpVal = MI.getOperand(3).getReg();
7215   Register OrigSwapVal = MI.getOperand(4).getReg();
7216   Register BitShift = MI.getOperand(5).getReg();
7217   Register NegBitShift = MI.getOperand(6).getReg();
7218   int64_t BitSize = MI.getOperand(7).getImm();
7219   DebugLoc DL = MI.getDebugLoc();
7220 
7221   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
7222 
7223   // Get the right opcodes for the displacement.
7224   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
7225   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
7226   assert(LOpcode && CSOpcode && "Displacement out of range");
7227 
7228   // Create virtual registers for temporary results.
7229   Register OrigOldVal = MRI.createVirtualRegister(RC);
7230   Register OldVal = MRI.createVirtualRegister(RC);
7231   Register CmpVal = MRI.createVirtualRegister(RC);
7232   Register SwapVal = MRI.createVirtualRegister(RC);
7233   Register StoreVal = MRI.createVirtualRegister(RC);
7234   Register RetryOldVal = MRI.createVirtualRegister(RC);
7235   Register RetryCmpVal = MRI.createVirtualRegister(RC);
7236   Register RetrySwapVal = MRI.createVirtualRegister(RC);
7237 
7238   // Insert 2 basic blocks for the loop.
7239   MachineBasicBlock *StartMBB = MBB;
7240   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
7241   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
7242   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
7243 
7244   //  StartMBB:
7245   //   ...
7246   //   %OrigOldVal     = L Disp(%Base)
7247   //   # fall through to LoopMMB
7248   MBB = StartMBB;
7249   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
7250       .add(Base)
7251       .addImm(Disp)
7252       .addReg(0);
7253   MBB->addSuccessor(LoopMBB);
7254 
7255   //  LoopMBB:
7256   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
7257   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
7258   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
7259   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
7260   //                      ^^ The low BitSize bits contain the field
7261   //                         of interest.
7262   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
7263   //                      ^^ Replace the upper 32-BitSize bits of the
7264   //                         comparison value with those that we loaded,
7265   //                         so that we can use a full word comparison.
7266   //   CR %Dest, %RetryCmpVal
7267   //   JNE DoneMBB
7268   //   # Fall through to SetMBB
7269   MBB = LoopMBB;
7270   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
7271     .addReg(OrigOldVal).addMBB(StartMBB)
7272     .addReg(RetryOldVal).addMBB(SetMBB);
7273   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
7274     .addReg(OrigCmpVal).addMBB(StartMBB)
7275     .addReg(RetryCmpVal).addMBB(SetMBB);
7276   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
7277     .addReg(OrigSwapVal).addMBB(StartMBB)
7278     .addReg(RetrySwapVal).addMBB(SetMBB);
7279   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
7280     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
7281   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
7282     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
7283   BuildMI(MBB, DL, TII->get(SystemZ::CR))
7284     .addReg(Dest).addReg(RetryCmpVal);
7285   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7286     .addImm(SystemZ::CCMASK_ICMP)
7287     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
7288   MBB->addSuccessor(DoneMBB);
7289   MBB->addSuccessor(SetMBB);
7290 
7291   //  SetMBB:
7292   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
7293   //                      ^^ Replace the upper 32-BitSize bits of the new
7294   //                         value with those that we loaded.
7295   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
7296   //                      ^^ Rotate the new field to its proper position.
7297   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
7298   //   JNE LoopMBB
7299   //   # fall through to ExitMMB
7300   MBB = SetMBB;
7301   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
7302     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
7303   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
7304     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
7305   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
7306       .addReg(OldVal)
7307       .addReg(StoreVal)
7308       .add(Base)
7309       .addImm(Disp);
7310   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7311     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
7312   MBB->addSuccessor(LoopMBB);
7313   MBB->addSuccessor(DoneMBB);
7314 
7315   // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
7316   // to the block after the loop.  At this point, CC may have been defined
7317   // either by the CR in LoopMBB or by the CS in SetMBB.
7318   if (!MI.registerDefIsDead(SystemZ::CC))
7319     DoneMBB->addLiveIn(SystemZ::CC);
7320 
7321   MI.eraseFromParent();
7322   return DoneMBB;
7323 }
7324 
7325 // Emit a move from two GR64s to a GR128.
7326 MachineBasicBlock *
7327 SystemZTargetLowering::emitPair128(MachineInstr &MI,
7328                                    MachineBasicBlock *MBB) const {
7329   MachineFunction &MF = *MBB->getParent();
7330   const SystemZInstrInfo *TII =
7331       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7332   MachineRegisterInfo &MRI = MF.getRegInfo();
7333   DebugLoc DL = MI.getDebugLoc();
7334 
7335   Register Dest = MI.getOperand(0).getReg();
7336   Register Hi = MI.getOperand(1).getReg();
7337   Register Lo = MI.getOperand(2).getReg();
7338   Register Tmp1 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7339   Register Tmp2 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7340 
7341   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Tmp1);
7342   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Tmp2)
7343     .addReg(Tmp1).addReg(Hi).addImm(SystemZ::subreg_h64);
7344   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
7345     .addReg(Tmp2).addReg(Lo).addImm(SystemZ::subreg_l64);
7346 
7347   MI.eraseFromParent();
7348   return MBB;
7349 }
7350 
7351 // Emit an extension from a GR64 to a GR128.  ClearEven is true
7352 // if the high register of the GR128 value must be cleared or false if
7353 // it's "don't care".
7354 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
7355                                                      MachineBasicBlock *MBB,
7356                                                      bool ClearEven) const {
7357   MachineFunction &MF = *MBB->getParent();
7358   const SystemZInstrInfo *TII =
7359       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7360   MachineRegisterInfo &MRI = MF.getRegInfo();
7361   DebugLoc DL = MI.getDebugLoc();
7362 
7363   Register Dest = MI.getOperand(0).getReg();
7364   Register Src = MI.getOperand(1).getReg();
7365   Register In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7366 
7367   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
7368   if (ClearEven) {
7369     Register NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7370     Register Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
7371 
7372     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
7373       .addImm(0);
7374     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
7375       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
7376     In128 = NewIn128;
7377   }
7378   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
7379     .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64);
7380 
7381   MI.eraseFromParent();
7382   return MBB;
7383 }
7384 
7385 MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper(
7386     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
7387   MachineFunction &MF = *MBB->getParent();
7388   const SystemZInstrInfo *TII =
7389       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7390   MachineRegisterInfo &MRI = MF.getRegInfo();
7391   DebugLoc DL = MI.getDebugLoc();
7392 
7393   MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
7394   uint64_t DestDisp = MI.getOperand(1).getImm();
7395   MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2));
7396   uint64_t SrcDisp = MI.getOperand(3).getImm();
7397   uint64_t Length = MI.getOperand(4).getImm();
7398 
7399   // When generating more than one CLC, all but the last will need to
7400   // branch to the end when a difference is found.
7401   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
7402                                splitBlockAfter(MI, MBB) : nullptr);
7403 
7404   // Check for the loop form, in which operand 5 is the trip count.
7405   if (MI.getNumExplicitOperands() > 5) {
7406     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
7407 
7408     Register StartCountReg = MI.getOperand(5).getReg();
7409     Register StartSrcReg   = forceReg(MI, SrcBase, TII);
7410     Register StartDestReg  = (HaveSingleBase ? StartSrcReg :
7411                               forceReg(MI, DestBase, TII));
7412 
7413     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
7414     Register ThisSrcReg  = MRI.createVirtualRegister(RC);
7415     Register ThisDestReg = (HaveSingleBase ? ThisSrcReg :
7416                             MRI.createVirtualRegister(RC));
7417     Register NextSrcReg  = MRI.createVirtualRegister(RC);
7418     Register NextDestReg = (HaveSingleBase ? NextSrcReg :
7419                             MRI.createVirtualRegister(RC));
7420 
7421     RC = &SystemZ::GR64BitRegClass;
7422     Register ThisCountReg = MRI.createVirtualRegister(RC);
7423     Register NextCountReg = MRI.createVirtualRegister(RC);
7424 
7425     MachineBasicBlock *StartMBB = MBB;
7426     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
7427     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
7428     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
7429 
7430     //  StartMBB:
7431     //   # fall through to LoopMMB
7432     MBB->addSuccessor(LoopMBB);
7433 
7434     //  LoopMBB:
7435     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
7436     //                      [ %NextDestReg, NextMBB ]
7437     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
7438     //                     [ %NextSrcReg, NextMBB ]
7439     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
7440     //                       [ %NextCountReg, NextMBB ]
7441     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
7442     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
7443     //   ( JLH EndMBB )
7444     //
7445     // The prefetch is used only for MVC.  The JLH is used only for CLC.
7446     MBB = LoopMBB;
7447 
7448     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
7449       .addReg(StartDestReg).addMBB(StartMBB)
7450       .addReg(NextDestReg).addMBB(NextMBB);
7451     if (!HaveSingleBase)
7452       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
7453         .addReg(StartSrcReg).addMBB(StartMBB)
7454         .addReg(NextSrcReg).addMBB(NextMBB);
7455     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
7456       .addReg(StartCountReg).addMBB(StartMBB)
7457       .addReg(NextCountReg).addMBB(NextMBB);
7458     if (Opcode == SystemZ::MVC)
7459       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
7460         .addImm(SystemZ::PFD_WRITE)
7461         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
7462     BuildMI(MBB, DL, TII->get(Opcode))
7463       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
7464       .addReg(ThisSrcReg).addImm(SrcDisp);
7465     if (EndMBB) {
7466       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7467         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
7468         .addMBB(EndMBB);
7469       MBB->addSuccessor(EndMBB);
7470       MBB->addSuccessor(NextMBB);
7471     }
7472 
7473     // NextMBB:
7474     //   %NextDestReg = LA 256(%ThisDestReg)
7475     //   %NextSrcReg = LA 256(%ThisSrcReg)
7476     //   %NextCountReg = AGHI %ThisCountReg, -1
7477     //   CGHI %NextCountReg, 0
7478     //   JLH LoopMBB
7479     //   # fall through to DoneMMB
7480     //
7481     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
7482     MBB = NextMBB;
7483 
7484     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
7485       .addReg(ThisDestReg).addImm(256).addReg(0);
7486     if (!HaveSingleBase)
7487       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
7488         .addReg(ThisSrcReg).addImm(256).addReg(0);
7489     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
7490       .addReg(ThisCountReg).addImm(-1);
7491     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
7492       .addReg(NextCountReg).addImm(0);
7493     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7494       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
7495       .addMBB(LoopMBB);
7496     MBB->addSuccessor(LoopMBB);
7497     MBB->addSuccessor(DoneMBB);
7498 
7499     DestBase = MachineOperand::CreateReg(NextDestReg, false);
7500     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
7501     Length &= 255;
7502     if (EndMBB && !Length)
7503       // If the loop handled the whole CLC range, DoneMBB will be empty with
7504       // CC live-through into EndMBB, so add it as live-in.
7505       DoneMBB->addLiveIn(SystemZ::CC);
7506     MBB = DoneMBB;
7507   }
7508   // Handle any remaining bytes with straight-line code.
7509   while (Length > 0) {
7510     uint64_t ThisLength = std::min(Length, uint64_t(256));
7511     // The previous iteration might have created out-of-range displacements.
7512     // Apply them using LAY if so.
7513     if (!isUInt<12>(DestDisp)) {
7514       Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
7515       BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
7516           .add(DestBase)
7517           .addImm(DestDisp)
7518           .addReg(0);
7519       DestBase = MachineOperand::CreateReg(Reg, false);
7520       DestDisp = 0;
7521     }
7522     if (!isUInt<12>(SrcDisp)) {
7523       Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
7524       BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
7525           .add(SrcBase)
7526           .addImm(SrcDisp)
7527           .addReg(0);
7528       SrcBase = MachineOperand::CreateReg(Reg, false);
7529       SrcDisp = 0;
7530     }
7531     BuildMI(*MBB, MI, DL, TII->get(Opcode))
7532         .add(DestBase)
7533         .addImm(DestDisp)
7534         .addImm(ThisLength)
7535         .add(SrcBase)
7536         .addImm(SrcDisp)
7537         .setMemRefs(MI.memoperands());
7538     DestDisp += ThisLength;
7539     SrcDisp += ThisLength;
7540     Length -= ThisLength;
7541     // If there's another CLC to go, branch to the end if a difference
7542     // was found.
7543     if (EndMBB && Length > 0) {
7544       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
7545       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7546         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
7547         .addMBB(EndMBB);
7548       MBB->addSuccessor(EndMBB);
7549       MBB->addSuccessor(NextMBB);
7550       MBB = NextMBB;
7551     }
7552   }
7553   if (EndMBB) {
7554     MBB->addSuccessor(EndMBB);
7555     MBB = EndMBB;
7556     MBB->addLiveIn(SystemZ::CC);
7557   }
7558 
7559   MI.eraseFromParent();
7560   return MBB;
7561 }
7562 
7563 // Decompose string pseudo-instruction MI into a loop that continually performs
7564 // Opcode until CC != 3.
7565 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
7566     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
7567   MachineFunction &MF = *MBB->getParent();
7568   const SystemZInstrInfo *TII =
7569       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7570   MachineRegisterInfo &MRI = MF.getRegInfo();
7571   DebugLoc DL = MI.getDebugLoc();
7572 
7573   uint64_t End1Reg = MI.getOperand(0).getReg();
7574   uint64_t Start1Reg = MI.getOperand(1).getReg();
7575   uint64_t Start2Reg = MI.getOperand(2).getReg();
7576   uint64_t CharReg = MI.getOperand(3).getReg();
7577 
7578   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
7579   uint64_t This1Reg = MRI.createVirtualRegister(RC);
7580   uint64_t This2Reg = MRI.createVirtualRegister(RC);
7581   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
7582 
7583   MachineBasicBlock *StartMBB = MBB;
7584   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
7585   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
7586 
7587   //  StartMBB:
7588   //   # fall through to LoopMMB
7589   MBB->addSuccessor(LoopMBB);
7590 
7591   //  LoopMBB:
7592   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
7593   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
7594   //   R0L = %CharReg
7595   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
7596   //   JO LoopMBB
7597   //   # fall through to DoneMMB
7598   //
7599   // The load of R0L can be hoisted by post-RA LICM.
7600   MBB = LoopMBB;
7601 
7602   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
7603     .addReg(Start1Reg).addMBB(StartMBB)
7604     .addReg(End1Reg).addMBB(LoopMBB);
7605   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
7606     .addReg(Start2Reg).addMBB(StartMBB)
7607     .addReg(End2Reg).addMBB(LoopMBB);
7608   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
7609   BuildMI(MBB, DL, TII->get(Opcode))
7610     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
7611     .addReg(This1Reg).addReg(This2Reg);
7612   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7613     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
7614   MBB->addSuccessor(LoopMBB);
7615   MBB->addSuccessor(DoneMBB);
7616 
7617   DoneMBB->addLiveIn(SystemZ::CC);
7618 
7619   MI.eraseFromParent();
7620   return DoneMBB;
7621 }
7622 
7623 // Update TBEGIN instruction with final opcode and register clobbers.
7624 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
7625     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
7626     bool NoFloat) const {
7627   MachineFunction &MF = *MBB->getParent();
7628   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
7629   const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
7630 
7631   // Update opcode.
7632   MI.setDesc(TII->get(Opcode));
7633 
7634   // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
7635   // Make sure to add the corresponding GRSM bits if they are missing.
7636   uint64_t Control = MI.getOperand(2).getImm();
7637   static const unsigned GPRControlBit[16] = {
7638     0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
7639     0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
7640   };
7641   Control |= GPRControlBit[15];
7642   if (TFI->hasFP(MF))
7643     Control |= GPRControlBit[11];
7644   MI.getOperand(2).setImm(Control);
7645 
7646   // Add GPR clobbers.
7647   for (int I = 0; I < 16; I++) {
7648     if ((Control & GPRControlBit[I]) == 0) {
7649       unsigned Reg = SystemZMC::GR64Regs[I];
7650       MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
7651     }
7652   }
7653 
7654   // Add FPR/VR clobbers.
7655   if (!NoFloat && (Control & 4) != 0) {
7656     if (Subtarget.hasVector()) {
7657       for (int I = 0; I < 32; I++) {
7658         unsigned Reg = SystemZMC::VR128Regs[I];
7659         MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
7660       }
7661     } else {
7662       for (int I = 0; I < 16; I++) {
7663         unsigned Reg = SystemZMC::FP64Regs[I];
7664         MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
7665       }
7666     }
7667   }
7668 
7669   return MBB;
7670 }
7671 
7672 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
7673     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
7674   MachineFunction &MF = *MBB->getParent();
7675   MachineRegisterInfo *MRI = &MF.getRegInfo();
7676   const SystemZInstrInfo *TII =
7677       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7678   DebugLoc DL = MI.getDebugLoc();
7679 
7680   Register SrcReg = MI.getOperand(0).getReg();
7681 
7682   // Create new virtual register of the same class as source.
7683   const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
7684   Register DstReg = MRI->createVirtualRegister(RC);
7685 
7686   // Replace pseudo with a normal load-and-test that models the def as
7687   // well.
7688   BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
7689     .addReg(SrcReg)
7690     .setMIFlags(MI.getFlags());
7691   MI.eraseFromParent();
7692 
7693   return MBB;
7694 }
7695 
7696 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter(
7697     MachineInstr &MI, MachineBasicBlock *MBB) const {
7698   switch (MI.getOpcode()) {
7699   case SystemZ::Select32:
7700   case SystemZ::Select64:
7701   case SystemZ::SelectF32:
7702   case SystemZ::SelectF64:
7703   case SystemZ::SelectF128:
7704   case SystemZ::SelectVR32:
7705   case SystemZ::SelectVR64:
7706   case SystemZ::SelectVR128:
7707     return emitSelect(MI, MBB);
7708 
7709   case SystemZ::CondStore8Mux:
7710     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
7711   case SystemZ::CondStore8MuxInv:
7712     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
7713   case SystemZ::CondStore16Mux:
7714     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
7715   case SystemZ::CondStore16MuxInv:
7716     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
7717   case SystemZ::CondStore32Mux:
7718     return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
7719   case SystemZ::CondStore32MuxInv:
7720     return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
7721   case SystemZ::CondStore8:
7722     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
7723   case SystemZ::CondStore8Inv:
7724     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
7725   case SystemZ::CondStore16:
7726     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
7727   case SystemZ::CondStore16Inv:
7728     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
7729   case SystemZ::CondStore32:
7730     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
7731   case SystemZ::CondStore32Inv:
7732     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
7733   case SystemZ::CondStore64:
7734     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
7735   case SystemZ::CondStore64Inv:
7736     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
7737   case SystemZ::CondStoreF32:
7738     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
7739   case SystemZ::CondStoreF32Inv:
7740     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
7741   case SystemZ::CondStoreF64:
7742     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
7743   case SystemZ::CondStoreF64Inv:
7744     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
7745 
7746   case SystemZ::PAIR128:
7747     return emitPair128(MI, MBB);
7748   case SystemZ::AEXT128:
7749     return emitExt128(MI, MBB, false);
7750   case SystemZ::ZEXT128:
7751     return emitExt128(MI, MBB, true);
7752 
7753   case SystemZ::ATOMIC_SWAPW:
7754     return emitAtomicLoadBinary(MI, MBB, 0, 0);
7755   case SystemZ::ATOMIC_SWAP_32:
7756     return emitAtomicLoadBinary(MI, MBB, 0, 32);
7757   case SystemZ::ATOMIC_SWAP_64:
7758     return emitAtomicLoadBinary(MI, MBB, 0, 64);
7759 
7760   case SystemZ::ATOMIC_LOADW_AR:
7761     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
7762   case SystemZ::ATOMIC_LOADW_AFI:
7763     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
7764   case SystemZ::ATOMIC_LOAD_AR:
7765     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
7766   case SystemZ::ATOMIC_LOAD_AHI:
7767     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
7768   case SystemZ::ATOMIC_LOAD_AFI:
7769     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
7770   case SystemZ::ATOMIC_LOAD_AGR:
7771     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
7772   case SystemZ::ATOMIC_LOAD_AGHI:
7773     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
7774   case SystemZ::ATOMIC_LOAD_AGFI:
7775     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
7776 
7777   case SystemZ::ATOMIC_LOADW_SR:
7778     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
7779   case SystemZ::ATOMIC_LOAD_SR:
7780     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
7781   case SystemZ::ATOMIC_LOAD_SGR:
7782     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
7783 
7784   case SystemZ::ATOMIC_LOADW_NR:
7785     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
7786   case SystemZ::ATOMIC_LOADW_NILH:
7787     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
7788   case SystemZ::ATOMIC_LOAD_NR:
7789     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
7790   case SystemZ::ATOMIC_LOAD_NILL:
7791     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
7792   case SystemZ::ATOMIC_LOAD_NILH:
7793     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
7794   case SystemZ::ATOMIC_LOAD_NILF:
7795     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
7796   case SystemZ::ATOMIC_LOAD_NGR:
7797     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
7798   case SystemZ::ATOMIC_LOAD_NILL64:
7799     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
7800   case SystemZ::ATOMIC_LOAD_NILH64:
7801     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
7802   case SystemZ::ATOMIC_LOAD_NIHL64:
7803     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
7804   case SystemZ::ATOMIC_LOAD_NIHH64:
7805     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
7806   case SystemZ::ATOMIC_LOAD_NILF64:
7807     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
7808   case SystemZ::ATOMIC_LOAD_NIHF64:
7809     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
7810 
7811   case SystemZ::ATOMIC_LOADW_OR:
7812     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
7813   case SystemZ::ATOMIC_LOADW_OILH:
7814     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
7815   case SystemZ::ATOMIC_LOAD_OR:
7816     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
7817   case SystemZ::ATOMIC_LOAD_OILL:
7818     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
7819   case SystemZ::ATOMIC_LOAD_OILH:
7820     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
7821   case SystemZ::ATOMIC_LOAD_OILF:
7822     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
7823   case SystemZ::ATOMIC_LOAD_OGR:
7824     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
7825   case SystemZ::ATOMIC_LOAD_OILL64:
7826     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
7827   case SystemZ::ATOMIC_LOAD_OILH64:
7828     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
7829   case SystemZ::ATOMIC_LOAD_OIHL64:
7830     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
7831   case SystemZ::ATOMIC_LOAD_OIHH64:
7832     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
7833   case SystemZ::ATOMIC_LOAD_OILF64:
7834     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
7835   case SystemZ::ATOMIC_LOAD_OIHF64:
7836     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
7837 
7838   case SystemZ::ATOMIC_LOADW_XR:
7839     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
7840   case SystemZ::ATOMIC_LOADW_XILF:
7841     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
7842   case SystemZ::ATOMIC_LOAD_XR:
7843     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
7844   case SystemZ::ATOMIC_LOAD_XILF:
7845     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
7846   case SystemZ::ATOMIC_LOAD_XGR:
7847     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
7848   case SystemZ::ATOMIC_LOAD_XILF64:
7849     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
7850   case SystemZ::ATOMIC_LOAD_XIHF64:
7851     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
7852 
7853   case SystemZ::ATOMIC_LOADW_NRi:
7854     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
7855   case SystemZ::ATOMIC_LOADW_NILHi:
7856     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
7857   case SystemZ::ATOMIC_LOAD_NRi:
7858     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
7859   case SystemZ::ATOMIC_LOAD_NILLi:
7860     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
7861   case SystemZ::ATOMIC_LOAD_NILHi:
7862     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
7863   case SystemZ::ATOMIC_LOAD_NILFi:
7864     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
7865   case SystemZ::ATOMIC_LOAD_NGRi:
7866     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
7867   case SystemZ::ATOMIC_LOAD_NILL64i:
7868     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
7869   case SystemZ::ATOMIC_LOAD_NILH64i:
7870     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
7871   case SystemZ::ATOMIC_LOAD_NIHL64i:
7872     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
7873   case SystemZ::ATOMIC_LOAD_NIHH64i:
7874     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
7875   case SystemZ::ATOMIC_LOAD_NILF64i:
7876     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
7877   case SystemZ::ATOMIC_LOAD_NIHF64i:
7878     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
7879 
7880   case SystemZ::ATOMIC_LOADW_MIN:
7881     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
7882                                 SystemZ::CCMASK_CMP_LE, 0);
7883   case SystemZ::ATOMIC_LOAD_MIN_32:
7884     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
7885                                 SystemZ::CCMASK_CMP_LE, 32);
7886   case SystemZ::ATOMIC_LOAD_MIN_64:
7887     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
7888                                 SystemZ::CCMASK_CMP_LE, 64);
7889 
7890   case SystemZ::ATOMIC_LOADW_MAX:
7891     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
7892                                 SystemZ::CCMASK_CMP_GE, 0);
7893   case SystemZ::ATOMIC_LOAD_MAX_32:
7894     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
7895                                 SystemZ::CCMASK_CMP_GE, 32);
7896   case SystemZ::ATOMIC_LOAD_MAX_64:
7897     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
7898                                 SystemZ::CCMASK_CMP_GE, 64);
7899 
7900   case SystemZ::ATOMIC_LOADW_UMIN:
7901     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
7902                                 SystemZ::CCMASK_CMP_LE, 0);
7903   case SystemZ::ATOMIC_LOAD_UMIN_32:
7904     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
7905                                 SystemZ::CCMASK_CMP_LE, 32);
7906   case SystemZ::ATOMIC_LOAD_UMIN_64:
7907     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
7908                                 SystemZ::CCMASK_CMP_LE, 64);
7909 
7910   case SystemZ::ATOMIC_LOADW_UMAX:
7911     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
7912                                 SystemZ::CCMASK_CMP_GE, 0);
7913   case SystemZ::ATOMIC_LOAD_UMAX_32:
7914     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
7915                                 SystemZ::CCMASK_CMP_GE, 32);
7916   case SystemZ::ATOMIC_LOAD_UMAX_64:
7917     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
7918                                 SystemZ::CCMASK_CMP_GE, 64);
7919 
7920   case SystemZ::ATOMIC_CMP_SWAPW:
7921     return emitAtomicCmpSwapW(MI, MBB);
7922   case SystemZ::MVCSequence:
7923   case SystemZ::MVCLoop:
7924     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
7925   case SystemZ::NCSequence:
7926   case SystemZ::NCLoop:
7927     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
7928   case SystemZ::OCSequence:
7929   case SystemZ::OCLoop:
7930     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
7931   case SystemZ::XCSequence:
7932   case SystemZ::XCLoop:
7933     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
7934   case SystemZ::CLCSequence:
7935   case SystemZ::CLCLoop:
7936     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
7937   case SystemZ::CLSTLoop:
7938     return emitStringWrapper(MI, MBB, SystemZ::CLST);
7939   case SystemZ::MVSTLoop:
7940     return emitStringWrapper(MI, MBB, SystemZ::MVST);
7941   case SystemZ::SRSTLoop:
7942     return emitStringWrapper(MI, MBB, SystemZ::SRST);
7943   case SystemZ::TBEGIN:
7944     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
7945   case SystemZ::TBEGIN_nofloat:
7946     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
7947   case SystemZ::TBEGINC:
7948     return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
7949   case SystemZ::LTEBRCompare_VecPseudo:
7950     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
7951   case SystemZ::LTDBRCompare_VecPseudo:
7952     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
7953   case SystemZ::LTXBRCompare_VecPseudo:
7954     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
7955 
7956   case TargetOpcode::STACKMAP:
7957   case TargetOpcode::PATCHPOINT:
7958     return emitPatchPoint(MI, MBB);
7959 
7960   default:
7961     llvm_unreachable("Unexpected instr type to insert");
7962   }
7963 }
7964 
7965 // This is only used by the isel schedulers, and is needed only to prevent
7966 // compiler from crashing when list-ilp is used.
7967 const TargetRegisterClass *
7968 SystemZTargetLowering::getRepRegClassFor(MVT VT) const {
7969   if (VT == MVT::Untyped)
7970     return &SystemZ::ADDR128BitRegClass;
7971   return TargetLowering::getRepRegClassFor(VT);
7972 }
7973