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