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