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