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