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