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