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