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