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