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