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