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