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