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