Home | History | Annotate | Line # | Download | only in SystemZ
      1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This file implements the SystemZTargetLowering class.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #include "SystemZISelLowering.h"
     14 #include "SystemZCallingConv.h"
     15 #include "SystemZConstantPoolValue.h"
     16 #include "SystemZMachineFunctionInfo.h"
     17 #include "SystemZTargetMachine.h"
     18 #include "llvm/CodeGen/CallingConvLower.h"
     19 #include "llvm/CodeGen/MachineInstrBuilder.h"
     20 #include "llvm/CodeGen/MachineRegisterInfo.h"
     21 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
     22 #include "llvm/IR/IntrinsicInst.h"
     23 #include "llvm/IR/Intrinsics.h"
     24 #include "llvm/IR/IntrinsicsS390.h"
     25 #include "llvm/Support/CommandLine.h"
     26 #include "llvm/Support/KnownBits.h"
     27 #include <cctype>
     28 
     29 using namespace llvm;
     30 
     31 #define DEBUG_TYPE "systemz-lower"
     32 
     33 namespace {
     34 // Represents information about a comparison.
     35 struct Comparison {
     36   Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
     37     : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
     38       Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
     39 
     40   // The operands to the comparison.
     41   SDValue Op0, Op1;
     42 
     43   // Chain if this is a strict floating-point comparison.
     44   SDValue Chain;
     45 
     46   // The opcode that should be used to compare Op0 and Op1.
     47   unsigned Opcode;
     48 
     49   // A SystemZICMP value.  Only used for integer comparisons.
     50   unsigned ICmpType;
     51 
     52   // The mask of CC values that Opcode can produce.
     53   unsigned CCValid;
     54 
     55   // The mask of CC values for which the original condition is true.
     56   unsigned CCMask;
     57 };
     58 } // end anonymous namespace
     59 
     60 // Classify VT as either 32 or 64 bit.
     61 static bool is32Bit(EVT VT) {
     62   switch (VT.getSimpleVT().SimpleTy) {
     63   case MVT::i32:
     64     return true;
     65   case MVT::i64:
     66     return false;
     67   default:
     68     llvm_unreachable("Unsupported type");
     69   }
     70 }
     71 
     72 // Return a version of MachineOperand that can be safely used before the
     73 // final use.
     74 static MachineOperand earlyUseOperand(MachineOperand Op) {
     75   if (Op.isReg())
     76     Op.setIsKill(false);
     77   return Op;
     78 }
     79 
     80 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
     81                                              const SystemZSubtarget &STI)
     82     : TargetLowering(TM), Subtarget(STI) {
     83   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize(0));
     84 
     85   // Set up the register classes.
     86   if (Subtarget.hasHighWord())
     87     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
     88   else
     89     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
     90   addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
     91   if (!useSoftFloat()) {
     92     if (Subtarget.hasVector()) {
     93       addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
     94       addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
     95     } else {
     96       addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
     97       addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
     98     }
     99     if (Subtarget.hasVectorEnhancements1())
    100       addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
    101     else
    102       addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
    103 
    104     if (Subtarget.hasVector()) {
    105       addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
    106       addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
    107       addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
    108       addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
    109       addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
    110       addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
    111     }
    112   }
    113 
    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(Align(2));
    131   // For performance reasons we prefer 16-byte alignment.
    132   setPrefFunctionAlignment(Align(16));
    133 
    134   // Handle operations that are handled in a similar way for all types.
    135   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
    136        I <= MVT::LAST_FP_VALUETYPE;
    137        ++I) {
    138     MVT VT = MVT::SimpleValueType(I);
    139     if (isTypeLegal(VT)) {
    140       // Lower SET_CC into an IPM-based sequence.
    141       setOperationAction(ISD::SETCC, VT, Custom);
    142       setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
    143       setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
    144 
    145       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
    146       setOperationAction(ISD::SELECT, VT, Expand);
    147 
    148       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
    149       setOperationAction(ISD::SELECT_CC, VT, Custom);
    150       setOperationAction(ISD::BR_CC,     VT, Custom);
    151     }
    152   }
    153 
    154   // Expand jump table branches as address arithmetic followed by an
    155   // indirect jump.
    156   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
    157 
    158   // Expand BRCOND into a BR_CC (see above).
    159   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
    160 
    161   // Handle integer types.
    162   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
    163        I <= MVT::LAST_INTEGER_VALUETYPE;
    164        ++I) {
    165     MVT VT = MVT::SimpleValueType(I);
    166     if (isTypeLegal(VT)) {
    167       setOperationAction(ISD::ABS, VT, Legal);
    168 
    169       // Expand individual DIV and REMs into DIVREMs.
    170       setOperationAction(ISD::SDIV, VT, Expand);
    171       setOperationAction(ISD::UDIV, VT, Expand);
    172       setOperationAction(ISD::SREM, VT, Expand);
    173       setOperationAction(ISD::UREM, VT, Expand);
    174       setOperationAction(ISD::SDIVREM, VT, Custom);
    175       setOperationAction(ISD::UDIVREM, VT, Custom);
    176 
    177       // Support addition/subtraction with overflow.
    178       setOperationAction(ISD::SADDO, VT, Custom);
    179       setOperationAction(ISD::SSUBO, VT, Custom);
    180 
    181       // Support addition/subtraction with carry.
    182       setOperationAction(ISD::UADDO, VT, Custom);
    183       setOperationAction(ISD::USUBO, VT, Custom);
    184 
    185       // Support carry in as value rather than glue.
    186       setOperationAction(ISD::ADDCARRY, VT, Custom);
    187       setOperationAction(ISD::SUBCARRY, VT, Custom);
    188 
    189       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
    190       // stores, putting a serialization instruction after the stores.
    191       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
    192       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
    193 
    194       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
    195       // available, or if the operand is constant.
    196       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
    197 
    198       // Use POPCNT on z196 and above.
    199       if (Subtarget.hasPopulationCount())
    200         setOperationAction(ISD::CTPOP, VT, Custom);
    201       else
    202         setOperationAction(ISD::CTPOP, VT, Expand);
    203 
    204       // No special instructions for these.
    205       setOperationAction(ISD::CTTZ,            VT, Expand);
    206       setOperationAction(ISD::ROTR,            VT, Expand);
    207 
    208       // Use *MUL_LOHI where possible instead of MULH*.
    209       setOperationAction(ISD::MULHS, VT, Expand);
    210       setOperationAction(ISD::MULHU, VT, Expand);
    211       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
    212       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
    213 
    214       // Only z196 and above have native support for conversions to unsigned.
    215       // On z10, promoting to i64 doesn't generate an inexact condition for
    216       // values that are outside the i32 range but in the i64 range, so use
    217       // the default expansion.
    218       if (!Subtarget.hasFPExtension())
    219         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
    220 
    221       // Mirror those settings for STRICT_FP_TO_[SU]INT.  Note that these all
    222       // default to Expand, so need to be modified to Legal where appropriate.
    223       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Legal);
    224       if (Subtarget.hasFPExtension())
    225         setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Legal);
    226 
    227       // And similarly for STRICT_[SU]INT_TO_FP.
    228       setOperationAction(ISD::STRICT_SINT_TO_FP, VT, Legal);
    229       if (Subtarget.hasFPExtension())
    230         setOperationAction(ISD::STRICT_UINT_TO_FP, VT, Legal);
    231     }
    232   }
    233 
    234   // Type legalization will convert 8- and 16-bit atomic operations into
    235   // forms that operate on i32s (but still keeping the original memory VT).
    236   // Lower them into full i32 operations.
    237   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
    238   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
    239   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
    240   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
    241   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
    242   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
    243   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
    244   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
    245   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
    246   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
    247   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
    248 
    249   // Even though i128 is not a legal type, we still need to custom lower
    250   // the atomic operations in order to exploit SystemZ instructions.
    251   setOperationAction(ISD::ATOMIC_LOAD,     MVT::i128, Custom);
    252   setOperationAction(ISD::ATOMIC_STORE,    MVT::i128, Custom);
    253 
    254   // We can use the CC result of compare-and-swap to implement
    255   // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
    256   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Custom);
    257   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Custom);
    258   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
    259 
    260   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
    261 
    262   // Traps are legal, as we will convert them to "j .+2".
    263   setOperationAction(ISD::TRAP, MVT::Other, Legal);
    264 
    265   // z10 has instructions for signed but not unsigned FP conversion.
    266   // Handle unsigned 32-bit types as signed 64-bit types.
    267   if (!Subtarget.hasFPExtension()) {
    268     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
    269     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
    270     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Promote);
    271     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
    272   }
    273 
    274   // We have native support for a 64-bit CTLZ, via FLOGR.
    275   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
    276   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Promote);
    277   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
    278 
    279   // On z15 we have native support for a 64-bit CTPOP.
    280   if (Subtarget.hasMiscellaneousExtensions3()) {
    281     setOperationAction(ISD::CTPOP, MVT::i32, Promote);
    282     setOperationAction(ISD::CTPOP, MVT::i64, Legal);
    283   }
    284 
    285   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
    286   setOperationAction(ISD::OR, MVT::i64, Custom);
    287 
    288   // Expand 128 bit shifts without using a libcall.
    289   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
    290   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
    291   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
    292   setLibcallName(RTLIB::SRL_I128, nullptr);
    293   setLibcallName(RTLIB::SHL_I128, nullptr);
    294   setLibcallName(RTLIB::SRA_I128, nullptr);
    295 
    296   // We have native instructions for i8, i16 and i32 extensions, but not i1.
    297   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
    298   for (MVT VT : MVT::integer_valuetypes()) {
    299     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
    300     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
    301     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
    302   }
    303 
    304   // Handle the various types of symbolic address.
    305   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
    306   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
    307   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
    308   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
    309   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
    310 
    311   // We need to handle dynamic allocations specially because of the
    312   // 160-byte area at the bottom of the stack.
    313   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
    314   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
    315 
    316   // Use custom expanders so that we can force the function to use
    317   // a frame pointer.
    318   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
    319   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
    320 
    321   // Handle prefetches with PFD or PFDRL.
    322   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
    323 
    324   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
    325     // Assume by default that all vector operations need to be expanded.
    326     for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
    327       if (getOperationAction(Opcode, VT) == Legal)
    328         setOperationAction(Opcode, VT, Expand);
    329 
    330     // Likewise all truncating stores and extending loads.
    331     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
    332       setTruncStoreAction(VT, InnerVT, Expand);
    333       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
    334       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
    335       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
    336     }
    337 
    338     if (isTypeLegal(VT)) {
    339       // These operations are legal for anything that can be stored in a
    340       // vector register, even if there is no native support for the format
    341       // as such.  In particular, we can do these for v4f32 even though there
    342       // are no specific instructions for that format.
    343       setOperationAction(ISD::LOAD, VT, Legal);
    344       setOperationAction(ISD::STORE, VT, Legal);
    345       setOperationAction(ISD::VSELECT, VT, Legal);
    346       setOperationAction(ISD::BITCAST, VT, Legal);
    347       setOperationAction(ISD::UNDEF, VT, Legal);
    348 
    349       // Likewise, except that we need to replace the nodes with something
    350       // more specific.
    351       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
    352       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
    353     }
    354   }
    355 
    356   // Handle integer vector types.
    357   for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
    358     if (isTypeLegal(VT)) {
    359       // These operations have direct equivalents.
    360       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
    361       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
    362       setOperationAction(ISD::ADD, VT, Legal);
    363       setOperationAction(ISD::SUB, VT, Legal);
    364       if (VT != MVT::v2i64)
    365         setOperationAction(ISD::MUL, VT, Legal);
    366       setOperationAction(ISD::ABS, VT, Legal);
    367       setOperationAction(ISD::AND, VT, Legal);
    368       setOperationAction(ISD::OR, VT, Legal);
    369       setOperationAction(ISD::XOR, VT, Legal);
    370       if (Subtarget.hasVectorEnhancements1())
    371         setOperationAction(ISD::CTPOP, VT, Legal);
    372       else
    373         setOperationAction(ISD::CTPOP, VT, Custom);
    374       setOperationAction(ISD::CTTZ, VT, Legal);
    375       setOperationAction(ISD::CTLZ, VT, Legal);
    376 
    377       // Convert a GPR scalar to a vector by inserting it into element 0.
    378       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
    379 
    380       // Use a series of unpacks for extensions.
    381       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
    382       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
    383 
    384       // Detect shifts by a scalar amount and convert them into
    385       // V*_BY_SCALAR.
    386       setOperationAction(ISD::SHL, VT, Custom);
    387       setOperationAction(ISD::SRA, VT, Custom);
    388       setOperationAction(ISD::SRL, VT, Custom);
    389 
    390       // At present ROTL isn't matched by DAGCombiner.  ROTR should be
    391       // converted into ROTL.
    392       setOperationAction(ISD::ROTL, VT, Expand);
    393       setOperationAction(ISD::ROTR, VT, Expand);
    394 
    395       // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
    396       // and inverting the result as necessary.
    397       setOperationAction(ISD::SETCC, VT, Custom);
    398       setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
    399       if (Subtarget.hasVectorEnhancements1())
    400         setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
    401     }
    402   }
    403 
    404   if (Subtarget.hasVector()) {
    405     // There should be no need to check for float types other than v2f64
    406     // since <2 x f32> isn't a legal type.
    407     setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
    408     setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal);
    409     setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
    410     setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal);
    411     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
    412     setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal);
    413     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
    414     setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal);
    415 
    416     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
    417     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f64, Legal);
    418     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
    419     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f64, Legal);
    420     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
    421     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f64, Legal);
    422     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
    423     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f64, Legal);
    424   }
    425 
    426   if (Subtarget.hasVectorEnhancements2()) {
    427     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
    428     setOperationAction(ISD::FP_TO_SINT, MVT::v4f32, Legal);
    429     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
    430     setOperationAction(ISD::FP_TO_UINT, MVT::v4f32, Legal);
    431     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
    432     setOperationAction(ISD::SINT_TO_FP, MVT::v4f32, Legal);
    433     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
    434     setOperationAction(ISD::UINT_TO_FP, MVT::v4f32, Legal);
    435 
    436     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
    437     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f32, Legal);
    438     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
    439     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f32, Legal);
    440     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
    441     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f32, Legal);
    442     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
    443     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f32, Legal);
    444   }
    445 
    446   // Handle floating-point types.
    447   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
    448        I <= MVT::LAST_FP_VALUETYPE;
    449        ++I) {
    450     MVT VT = MVT::SimpleValueType(I);
    451     if (isTypeLegal(VT)) {
    452       // We can use FI for FRINT.
    453       setOperationAction(ISD::FRINT, VT, Legal);
    454 
    455       // We can use the extended form of FI for other rounding operations.
    456       if (Subtarget.hasFPExtension()) {
    457         setOperationAction(ISD::FNEARBYINT, VT, Legal);
    458         setOperationAction(ISD::FFLOOR, VT, Legal);
    459         setOperationAction(ISD::FCEIL, VT, Legal);
    460         setOperationAction(ISD::FTRUNC, VT, Legal);
    461         setOperationAction(ISD::FROUND, VT, Legal);
    462       }
    463 
    464       // No special instructions for these.
    465       setOperationAction(ISD::FSIN, VT, Expand);
    466       setOperationAction(ISD::FCOS, VT, Expand);
    467       setOperationAction(ISD::FSINCOS, VT, Expand);
    468       setOperationAction(ISD::FREM, VT, Expand);
    469       setOperationAction(ISD::FPOW, VT, Expand);
    470 
    471       // Handle constrained floating-point operations.
    472       setOperationAction(ISD::STRICT_FADD, VT, Legal);
    473       setOperationAction(ISD::STRICT_FSUB, VT, Legal);
    474       setOperationAction(ISD::STRICT_FMUL, VT, Legal);
    475       setOperationAction(ISD::STRICT_FDIV, VT, Legal);
    476       setOperationAction(ISD::STRICT_FMA, VT, Legal);
    477       setOperationAction(ISD::STRICT_FSQRT, VT, Legal);
    478       setOperationAction(ISD::STRICT_FRINT, VT, Legal);
    479       setOperationAction(ISD::STRICT_FP_ROUND, VT, Legal);
    480       setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal);
    481       if (Subtarget.hasFPExtension()) {
    482         setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
    483         setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
    484         setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
    485         setOperationAction(ISD::STRICT_FROUND, VT, Legal);
    486         setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
    487       }
    488     }
    489   }
    490 
    491   // Handle floating-point vector types.
    492   if (Subtarget.hasVector()) {
    493     // Scalar-to-vector conversion is just a subreg.
    494     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
    495     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
    496 
    497     // Some insertions and extractions can be done directly but others
    498     // need to go via integers.
    499     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
    500     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
    501     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
    502     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
    503 
    504     // These operations have direct equivalents.
    505     setOperationAction(ISD::FADD, MVT::v2f64, Legal);
    506     setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
    507     setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
    508     setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
    509     setOperationAction(ISD::FMA, MVT::v2f64, Legal);
    510     setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
    511     setOperationAction(ISD::FABS, MVT::v2f64, Legal);
    512     setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
    513     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
    514     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
    515     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
    516     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
    517     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
    518     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
    519 
    520     // Handle constrained floating-point operations.
    521     setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
    522     setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
    523     setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
    524     setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
    525     setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
    526     setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
    527     setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
    528     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
    529     setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
    530     setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
    531     setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
    532     setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
    533   }
    534 
    535   // The vector enhancements facility 1 has instructions for these.
    536   if (Subtarget.hasVectorEnhancements1()) {
    537     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
    538     setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
    539     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
    540     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
    541     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
    542     setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
    543     setOperationAction(ISD::FABS, MVT::v4f32, Legal);
    544     setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
    545     setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
    546     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
    547     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
    548     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
    549     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
    550     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
    551 
    552     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
    553     setOperationAction(ISD::FMAXIMUM, MVT::f64, Legal);
    554     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
    555     setOperationAction(ISD::FMINIMUM, MVT::f64, Legal);
    556 
    557     setOperationAction(ISD::FMAXNUM, MVT::v2f64, Legal);
    558     setOperationAction(ISD::FMAXIMUM, MVT::v2f64, Legal);
    559     setOperationAction(ISD::FMINNUM, MVT::v2f64, Legal);
    560     setOperationAction(ISD::FMINIMUM, MVT::v2f64, Legal);
    561 
    562     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
    563     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
    564     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
    565     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
    566 
    567     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
    568     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
    569     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
    570     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
    571 
    572     setOperationAction(ISD::FMAXNUM, MVT::f128, Legal);
    573     setOperationAction(ISD::FMAXIMUM, MVT::f128, Legal);
    574     setOperationAction(ISD::FMINNUM, MVT::f128, Legal);
    575     setOperationAction(ISD::FMINIMUM, MVT::f128, Legal);
    576 
    577     // Handle constrained floating-point operations.
    578     setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
    579     setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
    580     setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
    581     setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
    582     setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
    583     setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
    584     setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
    585     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
    586     setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
    587     setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
    588     setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
    589     setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
    590     for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
    591                      MVT::v4f32, MVT::v2f64 }) {
    592       setOperationAction(ISD::STRICT_FMAXNUM, VT, Legal);
    593       setOperationAction(ISD::STRICT_FMINNUM, VT, Legal);
    594       setOperationAction(ISD::STRICT_FMAXIMUM, VT, Legal);
    595       setOperationAction(ISD::STRICT_FMINIMUM, VT, Legal);
    596     }
    597   }
    598 
    599   // We only have fused f128 multiply-addition on vector registers.
    600   if (!Subtarget.hasVectorEnhancements1()) {
    601     setOperationAction(ISD::FMA, MVT::f128, Expand);
    602     setOperationAction(ISD::STRICT_FMA, MVT::f128, Expand);
    603   }
    604 
    605   // We don't have a copysign instruction on vector registers.
    606   if (Subtarget.hasVectorEnhancements1())
    607     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
    608 
    609   // Needed so that we don't try to implement f128 constant loads using
    610   // a load-and-extend of a f80 constant (in cases where the constant
    611   // would fit in an f80).
    612   for (MVT VT : MVT::fp_valuetypes())
    613     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
    614 
    615   // We don't have extending load instruction on vector registers.
    616   if (Subtarget.hasVectorEnhancements1()) {
    617     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
    618     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
    619   }
    620 
    621   // Floating-point truncation and stores need to be done separately.
    622   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
    623   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
    624   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
    625 
    626   // We have 64-bit FPR<->GPR moves, but need special handling for
    627   // 32-bit forms.
    628   if (!Subtarget.hasVector()) {
    629     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
    630     setOperationAction(ISD::BITCAST, MVT::f32, Custom);
    631   }
    632 
    633   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
    634   // structure, but VAEND is a no-op.
    635   setOperationAction(ISD::VASTART, MVT::Other, Custom);
    636   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
    637   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
    638 
    639   // Codes for which we want to perform some z-specific combinations.
    640   setTargetDAGCombine(ISD::ZERO_EXTEND);
    641   setTargetDAGCombine(ISD::SIGN_EXTEND);
    642   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
    643   setTargetDAGCombine(ISD::LOAD);
    644   setTargetDAGCombine(ISD::STORE);
    645   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
    646   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
    647   setTargetDAGCombine(ISD::FP_ROUND);
    648   setTargetDAGCombine(ISD::STRICT_FP_ROUND);
    649   setTargetDAGCombine(ISD::FP_EXTEND);
    650   setTargetDAGCombine(ISD::SINT_TO_FP);
    651   setTargetDAGCombine(ISD::UINT_TO_FP);
    652   setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
    653   setTargetDAGCombine(ISD::BSWAP);
    654   setTargetDAGCombine(ISD::SDIV);
    655   setTargetDAGCombine(ISD::UDIV);
    656   setTargetDAGCombine(ISD::SREM);
    657   setTargetDAGCombine(ISD::UREM);
    658   setTargetDAGCombine(ISD::INTRINSIC_VOID);
    659   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
    660 
    661   // Handle intrinsics.
    662   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
    663   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
    664 
    665   // We want to use MVC in preference to even a single load/store pair.
    666   MaxStoresPerMemcpy = 0;
    667   MaxStoresPerMemcpyOptSize = 0;
    668 
    669   // The main memset sequence is a byte store followed by an MVC.
    670   // Two STC or MV..I stores win over that, but the kind of fused stores
    671   // generated by target-independent code don't when the byte value is
    672   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
    673   // than "STC;MVC".  Handle the choice in target-specific code instead.
    674   MaxStoresPerMemset = 0;
    675   MaxStoresPerMemsetOptSize = 0;
    676 
    677   // Default to having -disable-strictnode-mutation on
    678   IsStrictFPEnabled = true;
    679 }
    680 
    681 bool SystemZTargetLowering::useSoftFloat() const {
    682   return Subtarget.hasSoftFloat();
    683 }
    684 
    685 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
    686                                               LLVMContext &, EVT VT) const {
    687   if (!VT.isVector())
    688     return MVT::i32;
    689   return VT.changeVectorElementTypeToInteger();
    690 }
    691 
    692 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(
    693     const MachineFunction &MF, EVT VT) const {
    694   VT = VT.getScalarType();
    695 
    696   if (!VT.isSimple())
    697     return false;
    698 
    699   switch (VT.getSimpleVT().SimpleTy) {
    700   case MVT::f32:
    701   case MVT::f64:
    702     return true;
    703   case MVT::f128:
    704     return Subtarget.hasVectorEnhancements1();
    705   default:
    706     break;
    707   }
    708 
    709   return false;
    710 }
    711 
    712 // Return true if the constant can be generated with a vector instruction,
    713 // such as VGM, VGMB or VREPI.
    714 bool SystemZVectorConstantInfo::isVectorConstantLegal(
    715     const SystemZSubtarget &Subtarget) {
    716   const SystemZInstrInfo *TII =
    717       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
    718   if (!Subtarget.hasVector() ||
    719       (isFP128 && !Subtarget.hasVectorEnhancements1()))
    720     return false;
    721 
    722   // Try using VECTOR GENERATE BYTE MASK.  This is the architecturally-
    723   // preferred way of creating all-zero and all-one vectors so give it
    724   // priority over other methods below.
    725   unsigned Mask = 0;
    726   unsigned I = 0;
    727   for (; I < SystemZ::VectorBytes; ++I) {
    728     uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
    729     if (Byte == 0xff)
    730       Mask |= 1ULL << I;
    731     else if (Byte != 0)
    732       break;
    733   }
    734   if (I == SystemZ::VectorBytes) {
    735     Opcode = SystemZISD::BYTE_MASK;
    736     OpVals.push_back(Mask);
    737     VecVT = MVT::getVectorVT(MVT::getIntegerVT(8), 16);
    738     return true;
    739   }
    740 
    741   if (SplatBitSize > 64)
    742     return false;
    743 
    744   auto tryValue = [&](uint64_t Value) -> bool {
    745     // Try VECTOR REPLICATE IMMEDIATE
    746     int64_t SignedValue = SignExtend64(Value, SplatBitSize);
    747     if (isInt<16>(SignedValue)) {
    748       OpVals.push_back(((unsigned) SignedValue));
    749       Opcode = SystemZISD::REPLICATE;
    750       VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
    751                                SystemZ::VectorBits / SplatBitSize);
    752       return true;
    753     }
    754     // Try VECTOR GENERATE MASK
    755     unsigned Start, End;
    756     if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
    757       // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
    758       // denoting 1 << 63 and 63 denoting 1.  Convert them to bit numbers for
    759       // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
    760       OpVals.push_back(Start - (64 - SplatBitSize));
    761       OpVals.push_back(End - (64 - SplatBitSize));
    762       Opcode = SystemZISD::ROTATE_MASK;
    763       VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
    764                                SystemZ::VectorBits / SplatBitSize);
    765       return true;
    766     }
    767     return false;
    768   };
    769 
    770   // First try assuming that any undefined bits above the highest set bit
    771   // and below the lowest set bit are 1s.  This increases the likelihood of
    772   // being able to use a sign-extended element value in VECTOR REPLICATE
    773   // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
    774   uint64_t SplatBitsZ = SplatBits.getZExtValue();
    775   uint64_t SplatUndefZ = SplatUndef.getZExtValue();
    776   uint64_t Lower =
    777       (SplatUndefZ & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
    778   uint64_t Upper =
    779       (SplatUndefZ & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
    780   if (tryValue(SplatBitsZ | Upper | Lower))
    781     return true;
    782 
    783   // Now try assuming that any undefined bits between the first and
    784   // last defined set bits are set.  This increases the chances of
    785   // using a non-wraparound mask.
    786   uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
    787   return tryValue(SplatBitsZ | Middle);
    788 }
    789 
    790 SystemZVectorConstantInfo::SystemZVectorConstantInfo(APFloat FPImm) {
    791   IntBits = FPImm.bitcastToAPInt().zextOrSelf(128);
    792   isFP128 = (&FPImm.getSemantics() == &APFloat::IEEEquad());
    793   SplatBits = FPImm.bitcastToAPInt();
    794   unsigned Width = SplatBits.getBitWidth();
    795   IntBits <<= (SystemZ::VectorBits - Width);
    796 
    797   // Find the smallest splat.
    798   while (Width > 8) {
    799     unsigned HalfSize = Width / 2;
    800     APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
    801     APInt LowValue = SplatBits.trunc(HalfSize);
    802 
    803     // If the two halves do not match, stop here.
    804     if (HighValue != LowValue || 8 > HalfSize)
    805       break;
    806 
    807     SplatBits = HighValue;
    808     Width = HalfSize;
    809   }
    810   SplatUndef = 0;
    811   SplatBitSize = Width;
    812 }
    813 
    814 SystemZVectorConstantInfo::SystemZVectorConstantInfo(BuildVectorSDNode *BVN) {
    815   assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
    816   bool HasAnyUndefs;
    817 
    818   // Get IntBits by finding the 128 bit splat.
    819   BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
    820                        true);
    821 
    822   // Get SplatBits by finding the 8 bit or greater splat.
    823   BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
    824                        true);
    825 }
    826 
    827 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
    828                                          bool ForCodeSize) const {
    829   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
    830   if (Imm.isZero() || Imm.isNegZero())
    831     return true;
    832 
    833   return SystemZVectorConstantInfo(Imm).isVectorConstantLegal(Subtarget);
    834 }
    835 
    836 /// Returns true if stack probing through inline assembly is requested.
    837 bool SystemZTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
    838   // If the function specifically requests inline stack probes, emit them.
    839   if (MF.getFunction().hasFnAttribute("probe-stack"))
    840     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
    841            "inline-asm";
    842   return false;
    843 }
    844 
    845 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
    846   // We can use CGFI or CLGFI.
    847   return isInt<32>(Imm) || isUInt<32>(Imm);
    848 }
    849 
    850 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
    851   // We can use ALGFI or SLGFI.
    852   return isUInt<32>(Imm) || isUInt<32>(-Imm);
    853 }
    854 
    855 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(
    856     EVT VT, unsigned, Align, MachineMemOperand::Flags, bool *Fast) const {
    857   // Unaligned accesses should never be slower than the expanded version.
    858   // We check specifically for aligned accesses in the few cases where
    859   // they are required.
    860   if (Fast)
    861     *Fast = true;
    862   return true;
    863 }
    864 
    865 // Information about the addressing mode for a memory access.
    866 struct AddressingMode {
    867   // True if a long displacement is supported.
    868   bool LongDisplacement;
    869 
    870   // True if use of index register is supported.
    871   bool IndexReg;
    872 
    873   AddressingMode(bool LongDispl, bool IdxReg) :
    874     LongDisplacement(LongDispl), IndexReg(IdxReg) {}
    875 };
    876 
    877 // Return the desired addressing mode for a Load which has only one use (in
    878 // the same block) which is a Store.
    879 static AddressingMode getLoadStoreAddrMode(bool HasVector,
    880                                           Type *Ty) {
    881   // With vector support a Load->Store combination may be combined to either
    882   // an MVC or vector operations and it seems to work best to allow the
    883   // vector addressing mode.
    884   if (HasVector)
    885     return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
    886 
    887   // Otherwise only the MVC case is special.
    888   bool MVC = Ty->isIntegerTy(8);
    889   return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
    890 }
    891 
    892 // Return the addressing mode which seems most desirable given an LLVM
    893 // Instruction pointer.
    894 static AddressingMode
    895 supportedAddressingMode(Instruction *I, bool HasVector) {
    896   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
    897     switch (II->getIntrinsicID()) {
    898     default: break;
    899     case Intrinsic::memset:
    900     case Intrinsic::memmove:
    901     case Intrinsic::memcpy:
    902       return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
    903     }
    904   }
    905 
    906   if (isa<LoadInst>(I) && I->hasOneUse()) {
    907     auto *SingleUser = cast<Instruction>(*I->user_begin());
    908     if (SingleUser->getParent() == I->getParent()) {
    909       if (isa<ICmpInst>(SingleUser)) {
    910         if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
    911           if (C->getBitWidth() <= 64 &&
    912               (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
    913             // Comparison of memory with 16 bit signed / unsigned immediate
    914             return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
    915       } else if (isa<StoreInst>(SingleUser))
    916         // Load->Store
    917         return getLoadStoreAddrMode(HasVector, I->getType());
    918     }
    919   } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
    920     if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
    921       if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
    922         // Load->Store
    923         return getLoadStoreAddrMode(HasVector, LoadI->getType());
    924   }
    925 
    926   if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
    927 
    928     // * Use LDE instead of LE/LEY for z13 to avoid partial register
    929     //   dependencies (LDE only supports small offsets).
    930     // * Utilize the vector registers to hold floating point
    931     //   values (vector load / store instructions only support small
    932     //   offsets).
    933 
    934     Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
    935                          I->getOperand(0)->getType());
    936     bool IsFPAccess = MemAccessTy->isFloatingPointTy();
    937     bool IsVectorAccess = MemAccessTy->isVectorTy();
    938 
    939     // A store of an extracted vector element will be combined into a VSTE type
    940     // instruction.
    941     if (!IsVectorAccess && isa<StoreInst>(I)) {
    942       Value *DataOp = I->getOperand(0);
    943       if (isa<ExtractElementInst>(DataOp))
    944         IsVectorAccess = true;
    945     }
    946 
    947     // A load which gets inserted into a vector element will be combined into a
    948     // VLE type instruction.
    949     if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
    950       User *LoadUser = *I->user_begin();
    951       if (isa<InsertElementInst>(LoadUser))
    952         IsVectorAccess = true;
    953     }
    954 
    955     if (IsFPAccess || IsVectorAccess)
    956       return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
    957   }
    958 
    959   return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
    960 }
    961 
    962 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
    963        const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
    964   // Punt on globals for now, although they can be used in limited
    965   // RELATIVE LONG cases.
    966   if (AM.BaseGV)
    967     return false;
    968 
    969   // Require a 20-bit signed offset.
    970   if (!isInt<20>(AM.BaseOffs))
    971     return false;
    972 
    973   AddressingMode SupportedAM(true, true);
    974   if (I != nullptr)
    975     SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
    976 
    977   if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
    978     return false;
    979 
    980   if (!SupportedAM.IndexReg)
    981     // No indexing allowed.
    982     return AM.Scale == 0;
    983   else
    984     // Indexing is OK but no scale factor can be applied.
    985     return AM.Scale == 0 || AM.Scale == 1;
    986 }
    987 
    988 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
    989   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
    990     return false;
    991   unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedSize();
    992   unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedSize();
    993   return FromBits > ToBits;
    994 }
    995 
    996 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
    997   if (!FromVT.isInteger() || !ToVT.isInteger())
    998     return false;
    999   unsigned FromBits = FromVT.getFixedSizeInBits();
   1000   unsigned ToBits = ToVT.getFixedSizeInBits();
   1001   return FromBits > ToBits;
   1002 }
   1003 
   1004 //===----------------------------------------------------------------------===//
   1005 // Inline asm support
   1006 //===----------------------------------------------------------------------===//
   1007 
   1008 TargetLowering::ConstraintType
   1009 SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
   1010   if (Constraint.size() == 1) {
   1011     switch (Constraint[0]) {
   1012     case 'a': // Address register
   1013     case 'd': // Data register (equivalent to 'r')
   1014     case 'f': // Floating-point register
   1015     case 'h': // High-part register
   1016     case 'r': // General-purpose register
   1017     case 'v': // Vector register
   1018       return C_RegisterClass;
   1019 
   1020     case 'Q': // Memory with base and unsigned 12-bit displacement
   1021     case 'R': // Likewise, plus an index
   1022     case 'S': // Memory with base and signed 20-bit displacement
   1023     case 'T': // Likewise, plus an index
   1024     case 'm': // Equivalent to 'T'.
   1025       return C_Memory;
   1026 
   1027     case 'I': // Unsigned 8-bit constant
   1028     case 'J': // Unsigned 12-bit constant
   1029     case 'K': // Signed 16-bit constant
   1030     case 'L': // Signed 20-bit displacement (on all targets we support)
   1031     case 'M': // 0x7fffffff
   1032       return C_Immediate;
   1033 
   1034     default:
   1035       break;
   1036     }
   1037   }
   1038   return TargetLowering::getConstraintType(Constraint);
   1039 }
   1040 
   1041 TargetLowering::ConstraintWeight SystemZTargetLowering::
   1042 getSingleConstraintMatchWeight(AsmOperandInfo &info,
   1043                                const char *constraint) const {
   1044   ConstraintWeight weight = CW_Invalid;
   1045   Value *CallOperandVal = info.CallOperandVal;
   1046   // If we don't have a value, we can't do a match,
   1047   // but allow it at the lowest weight.
   1048   if (!CallOperandVal)
   1049     return CW_Default;
   1050   Type *type = CallOperandVal->getType();
   1051   // Look at the constraint type.
   1052   switch (*constraint) {
   1053   default:
   1054     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
   1055     break;
   1056 
   1057   case 'a': // Address register
   1058   case 'd': // Data register (equivalent to 'r')
   1059   case 'h': // High-part register
   1060   case 'r': // General-purpose register
   1061     if (CallOperandVal->getType()->isIntegerTy())
   1062       weight = CW_Register;
   1063     break;
   1064 
   1065   case 'f': // Floating-point register
   1066     if (type->isFloatingPointTy())
   1067       weight = CW_Register;
   1068     break;
   1069 
   1070   case 'v': // Vector register
   1071     if ((type->isVectorTy() || type->isFloatingPointTy()) &&
   1072         Subtarget.hasVector())
   1073       weight = CW_Register;
   1074     break;
   1075 
   1076   case 'I': // Unsigned 8-bit constant
   1077     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
   1078       if (isUInt<8>(C->getZExtValue()))
   1079         weight = CW_Constant;
   1080     break;
   1081 
   1082   case 'J': // Unsigned 12-bit constant
   1083     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
   1084       if (isUInt<12>(C->getZExtValue()))
   1085         weight = CW_Constant;
   1086     break;
   1087 
   1088   case 'K': // Signed 16-bit constant
   1089     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
   1090       if (isInt<16>(C->getSExtValue()))
   1091         weight = CW_Constant;
   1092     break;
   1093 
   1094   case 'L': // Signed 20-bit displacement (on all targets we support)
   1095     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
   1096       if (isInt<20>(C->getSExtValue()))
   1097         weight = CW_Constant;
   1098     break;
   1099 
   1100   case 'M': // 0x7fffffff
   1101     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
   1102       if (C->getZExtValue() == 0x7fffffff)
   1103         weight = CW_Constant;
   1104     break;
   1105   }
   1106   return weight;
   1107 }
   1108 
   1109 // Parse a "{tNNN}" register constraint for which the register type "t"
   1110 // has already been verified.  MC is the class associated with "t" and
   1111 // Map maps 0-based register numbers to LLVM register numbers.
   1112 static std::pair<unsigned, const TargetRegisterClass *>
   1113 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
   1114                     const unsigned *Map, unsigned Size) {
   1115   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
   1116   if (isdigit(Constraint[2])) {
   1117     unsigned Index;
   1118     bool Failed =
   1119         Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
   1120     if (!Failed && Index < Size && Map[Index])
   1121       return std::make_pair(Map[Index], RC);
   1122   }
   1123   return std::make_pair(0U, nullptr);
   1124 }
   1125 
   1126 std::pair<unsigned, const TargetRegisterClass *>
   1127 SystemZTargetLowering::getRegForInlineAsmConstraint(
   1128     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
   1129   if (Constraint.size() == 1) {
   1130     // GCC Constraint Letters
   1131     switch (Constraint[0]) {
   1132     default: break;
   1133     case 'd': // Data register (equivalent to 'r')
   1134     case 'r': // General-purpose register
   1135       if (VT == MVT::i64)
   1136         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
   1137       else if (VT == MVT::i128)
   1138         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
   1139       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
   1140 
   1141     case 'a': // Address register
   1142       if (VT == MVT::i64)
   1143         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
   1144       else if (VT == MVT::i128)
   1145         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
   1146       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
   1147 
   1148     case 'h': // High-part register (an LLVM extension)
   1149       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
   1150 
   1151     case 'f': // Floating-point register
   1152       if (!useSoftFloat()) {
   1153         if (VT == MVT::f64)
   1154           return std::make_pair(0U, &SystemZ::FP64BitRegClass);
   1155         else if (VT == MVT::f128)
   1156           return std::make_pair(0U, &SystemZ::FP128BitRegClass);
   1157         return std::make_pair(0U, &SystemZ::FP32BitRegClass);
   1158       }
   1159       break;
   1160     case 'v': // Vector register
   1161       if (Subtarget.hasVector()) {
   1162         if (VT == MVT::f32)
   1163           return std::make_pair(0U, &SystemZ::VR32BitRegClass);
   1164         if (VT == MVT::f64)
   1165           return std::make_pair(0U, &SystemZ::VR64BitRegClass);
   1166         return std::make_pair(0U, &SystemZ::VR128BitRegClass);
   1167       }
   1168       break;
   1169     }
   1170   }
   1171   if (Constraint.size() > 0 && Constraint[0] == '{') {
   1172     // We need to override the default register parsing for GPRs and FPRs
   1173     // because the interpretation depends on VT.  The internal names of
   1174     // the registers are also different from the external names
   1175     // (F0D and F0S instead of F0, etc.).
   1176     if (Constraint[1] == 'r') {
   1177       if (VT == MVT::i32)
   1178         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
   1179                                    SystemZMC::GR32Regs, 16);
   1180       if (VT == MVT::i128)
   1181         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
   1182                                    SystemZMC::GR128Regs, 16);
   1183       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
   1184                                  SystemZMC::GR64Regs, 16);
   1185     }
   1186     if (Constraint[1] == 'f') {
   1187       if (useSoftFloat())
   1188         return std::make_pair(
   1189             0u, static_cast<const TargetRegisterClass *>(nullptr));
   1190       if (VT == MVT::f32)
   1191         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
   1192                                    SystemZMC::FP32Regs, 16);
   1193       if (VT == MVT::f128)
   1194         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
   1195                                    SystemZMC::FP128Regs, 16);
   1196       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
   1197                                  SystemZMC::FP64Regs, 16);
   1198     }
   1199     if (Constraint[1] == 'v') {
   1200       if (!Subtarget.hasVector())
   1201         return std::make_pair(
   1202             0u, static_cast<const TargetRegisterClass *>(nullptr));
   1203       if (VT == MVT::f32)
   1204         return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
   1205                                    SystemZMC::VR32Regs, 32);
   1206       if (VT == MVT::f64)
   1207         return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
   1208                                    SystemZMC::VR64Regs, 32);
   1209       return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
   1210                                  SystemZMC::VR128Regs, 32);
   1211     }
   1212   }
   1213   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
   1214 }
   1215 
   1216 // FIXME? Maybe this could be a TableGen attribute on some registers and
   1217 // this table could be generated automatically from RegInfo.
   1218 Register SystemZTargetLowering::getRegisterByName(const char *RegName, LLT VT,
   1219                                                   const MachineFunction &MF) const {
   1220 
   1221   Register Reg = StringSwitch<Register>(RegName)
   1222                    .Case("r15", SystemZ::R15D)
   1223                    .Default(0);
   1224   if (Reg)
   1225     return Reg;
   1226   report_fatal_error("Invalid register name global variable");
   1227 }
   1228 
   1229 void SystemZTargetLowering::
   1230 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
   1231                              std::vector<SDValue> &Ops,
   1232                              SelectionDAG &DAG) const {
   1233   // Only support length 1 constraints for now.
   1234   if (Constraint.length() == 1) {
   1235     switch (Constraint[0]) {
   1236     case 'I': // Unsigned 8-bit constant
   1237       if (auto *C = dyn_cast<ConstantSDNode>(Op))
   1238         if (isUInt<8>(C->getZExtValue()))
   1239           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
   1240                                               Op.getValueType()));
   1241       return;
   1242 
   1243     case 'J': // Unsigned 12-bit constant
   1244       if (auto *C = dyn_cast<ConstantSDNode>(Op))
   1245         if (isUInt<12>(C->getZExtValue()))
   1246           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
   1247                                               Op.getValueType()));
   1248       return;
   1249 
   1250     case 'K': // Signed 16-bit constant
   1251       if (auto *C = dyn_cast<ConstantSDNode>(Op))
   1252         if (isInt<16>(C->getSExtValue()))
   1253           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
   1254                                               Op.getValueType()));
   1255       return;
   1256 
   1257     case 'L': // Signed 20-bit displacement (on all targets we support)
   1258       if (auto *C = dyn_cast<ConstantSDNode>(Op))
   1259         if (isInt<20>(C->getSExtValue()))
   1260           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
   1261                                               Op.getValueType()));
   1262       return;
   1263 
   1264     case 'M': // 0x7fffffff
   1265       if (auto *C = dyn_cast<ConstantSDNode>(Op))
   1266         if (C->getZExtValue() == 0x7fffffff)
   1267           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
   1268                                               Op.getValueType()));
   1269       return;
   1270     }
   1271   }
   1272   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
   1273 }
   1274 
   1275 //===----------------------------------------------------------------------===//
   1276 // Calling conventions
   1277 //===----------------------------------------------------------------------===//
   1278 
   1279 #include "SystemZGenCallingConv.inc"
   1280 
   1281 const MCPhysReg *SystemZTargetLowering::getScratchRegisters(
   1282   CallingConv::ID) const {
   1283   static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
   1284                                            SystemZ::R14D, 0 };
   1285   return ScratchRegs;
   1286 }
   1287 
   1288 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
   1289                                                      Type *ToType) const {
   1290   return isTruncateFree(FromType, ToType);
   1291 }
   1292 
   1293 bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
   1294   return CI->isTailCall();
   1295 }
   1296 
   1297 // We do not yet support 128-bit single-element vector types.  If the user
   1298 // attempts to use such types as function argument or return type, prefer
   1299 // to error out instead of emitting code violating the ABI.
   1300 static void VerifyVectorType(MVT VT, EVT ArgVT) {
   1301   if (ArgVT.isVector() && !VT.isVector())
   1302     report_fatal_error("Unsupported vector argument or return type");
   1303 }
   1304 
   1305 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
   1306   for (unsigned i = 0; i < Ins.size(); ++i)
   1307     VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
   1308 }
   1309 
   1310 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
   1311   for (unsigned i = 0; i < Outs.size(); ++i)
   1312     VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
   1313 }
   1314 
   1315 // Value is a value that has been passed to us in the location described by VA
   1316 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
   1317 // any loads onto Chain.
   1318 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
   1319                                    CCValAssign &VA, SDValue Chain,
   1320                                    SDValue Value) {
   1321   // If the argument has been promoted from a smaller type, insert an
   1322   // assertion to capture this.
   1323   if (VA.getLocInfo() == CCValAssign::SExt)
   1324     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
   1325                         DAG.getValueType(VA.getValVT()));
   1326   else if (VA.getLocInfo() == CCValAssign::ZExt)
   1327     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
   1328                         DAG.getValueType(VA.getValVT()));
   1329 
   1330   if (VA.isExtInLoc())
   1331     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
   1332   else if (VA.getLocInfo() == CCValAssign::BCvt) {
   1333     // If this is a short vector argument loaded from the stack,
   1334     // extend from i64 to full vector size and then bitcast.
   1335     assert(VA.getLocVT() == MVT::i64);
   1336     assert(VA.getValVT().isVector());
   1337     Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
   1338     Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
   1339   } else
   1340     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
   1341   return Value;
   1342 }
   1343 
   1344 // Value is a value of type VA.getValVT() that we need to copy into
   1345 // the location described by VA.  Return a copy of Value converted to
   1346 // VA.getValVT().  The caller is responsible for handling indirect values.
   1347 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
   1348                                    CCValAssign &VA, SDValue Value) {
   1349   switch (VA.getLocInfo()) {
   1350   case CCValAssign::SExt:
   1351     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
   1352   case CCValAssign::ZExt:
   1353     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
   1354   case CCValAssign::AExt:
   1355     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
   1356   case CCValAssign::BCvt:
   1357     // If this is a short vector argument to be stored to the stack,
   1358     // bitcast to v2i64 and then extract first element.
   1359     assert(VA.getLocVT() == MVT::i64);
   1360     assert(VA.getValVT().isVector());
   1361     Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
   1362     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
   1363                        DAG.getConstant(0, DL, MVT::i32));
   1364   case CCValAssign::Full:
   1365     return Value;
   1366   default:
   1367     llvm_unreachable("Unhandled getLocInfo()");
   1368   }
   1369 }
   1370 
   1371 SDValue SystemZTargetLowering::LowerFormalArguments(
   1372     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
   1373     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
   1374     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
   1375   MachineFunction &MF = DAG.getMachineFunction();
   1376   MachineFrameInfo &MFI = MF.getFrameInfo();
   1377   MachineRegisterInfo &MRI = MF.getRegInfo();
   1378   SystemZMachineFunctionInfo *FuncInfo =
   1379       MF.getInfo<SystemZMachineFunctionInfo>();
   1380   auto *TFL =
   1381       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
   1382   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   1383 
   1384   // Detect unsupported vector argument types.
   1385   if (Subtarget.hasVector())
   1386     VerifyVectorTypes(Ins);
   1387 
   1388   // Assign locations to all of the incoming arguments.
   1389   SmallVector<CCValAssign, 16> ArgLocs;
   1390   SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
   1391   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
   1392 
   1393   unsigned NumFixedGPRs = 0;
   1394   unsigned NumFixedFPRs = 0;
   1395   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
   1396     SDValue ArgValue;
   1397     CCValAssign &VA = ArgLocs[I];
   1398     EVT LocVT = VA.getLocVT();
   1399     if (VA.isRegLoc()) {
   1400       // Arguments passed in registers
   1401       const TargetRegisterClass *RC;
   1402       switch (LocVT.getSimpleVT().SimpleTy) {
   1403       default:
   1404         // Integers smaller than i64 should be promoted to i64.
   1405         llvm_unreachable("Unexpected argument type");
   1406       case MVT::i32:
   1407         NumFixedGPRs += 1;
   1408         RC = &SystemZ::GR32BitRegClass;
   1409         break;
   1410       case MVT::i64:
   1411         NumFixedGPRs += 1;
   1412         RC = &SystemZ::GR64BitRegClass;
   1413         break;
   1414       case MVT::f32:
   1415         NumFixedFPRs += 1;
   1416         RC = &SystemZ::FP32BitRegClass;
   1417         break;
   1418       case MVT::f64:
   1419         NumFixedFPRs += 1;
   1420         RC = &SystemZ::FP64BitRegClass;
   1421         break;
   1422       case MVT::v16i8:
   1423       case MVT::v8i16:
   1424       case MVT::v4i32:
   1425       case MVT::v2i64:
   1426       case MVT::v4f32:
   1427       case MVT::v2f64:
   1428         RC = &SystemZ::VR128BitRegClass;
   1429         break;
   1430       }
   1431 
   1432       Register VReg = MRI.createVirtualRegister(RC);
   1433       MRI.addLiveIn(VA.getLocReg(), VReg);
   1434       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
   1435     } else {
   1436       assert(VA.isMemLoc() && "Argument not register or memory");
   1437 
   1438       // Create the frame index object for this incoming parameter.
   1439       int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
   1440                                      VA.getLocMemOffset(), true);
   1441 
   1442       // Create the SelectionDAG nodes corresponding to a load
   1443       // from this parameter.  Unpromoted ints and floats are
   1444       // passed as right-justified 8-byte values.
   1445       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
   1446       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
   1447         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
   1448                           DAG.getIntPtrConstant(4, DL));
   1449       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
   1450                              MachinePointerInfo::getFixedStack(MF, FI));
   1451     }
   1452 
   1453     // Convert the value of the argument register into the value that's
   1454     // being passed.
   1455     if (VA.getLocInfo() == CCValAssign::Indirect) {
   1456       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
   1457                                    MachinePointerInfo()));
   1458       // If the original argument was split (e.g. i128), we need
   1459       // to load all parts of it here (using the same address).
   1460       unsigned ArgIndex = Ins[I].OrigArgIndex;
   1461       assert (Ins[I].PartOffset == 0);
   1462       while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
   1463         CCValAssign &PartVA = ArgLocs[I + 1];
   1464         unsigned PartOffset = Ins[I + 1].PartOffset;
   1465         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
   1466                                       DAG.getIntPtrConstant(PartOffset, DL));
   1467         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
   1468                                      MachinePointerInfo()));
   1469         ++I;
   1470       }
   1471     } else
   1472       InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
   1473   }
   1474 
   1475   if (IsVarArg) {
   1476     // Save the number of non-varargs registers for later use by va_start, etc.
   1477     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
   1478     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
   1479 
   1480     // Likewise the address (in the form of a frame index) of where the
   1481     // first stack vararg would be.  The 1-byte size here is arbitrary.
   1482     int64_t StackSize = CCInfo.getNextStackOffset();
   1483     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
   1484 
   1485     // ...and a similar frame index for the caller-allocated save area
   1486     // that will be used to store the incoming registers.
   1487     int64_t RegSaveOffset =
   1488       -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
   1489     unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
   1490     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
   1491 
   1492     // Store the FPR varargs in the reserved frame slots.  (We store the
   1493     // GPRs as part of the prologue.)
   1494     if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
   1495       SDValue MemOps[SystemZ::ELFNumArgFPRs];
   1496       for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
   1497         unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
   1498         int FI =
   1499           MFI.CreateFixedObject(8, -SystemZMC::ELFCallFrameSize + Offset, true);
   1500         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
   1501         unsigned VReg = MF.addLiveIn(SystemZ::ELFArgFPRs[I],
   1502                                      &SystemZ::FP64BitRegClass);
   1503         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
   1504         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
   1505                                  MachinePointerInfo::getFixedStack(MF, FI));
   1506       }
   1507       // Join the stores, which are independent of one another.
   1508       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
   1509                           makeArrayRef(&MemOps[NumFixedFPRs],
   1510                                        SystemZ::ELFNumArgFPRs-NumFixedFPRs));
   1511     }
   1512   }
   1513 
   1514   return Chain;
   1515 }
   1516 
   1517 static bool canUseSiblingCall(const CCState &ArgCCInfo,
   1518                               SmallVectorImpl<CCValAssign> &ArgLocs,
   1519                               SmallVectorImpl<ISD::OutputArg> &Outs) {
   1520   // Punt if there are any indirect or stack arguments, or if the call
   1521   // needs the callee-saved argument register R6, or if the call uses
   1522   // the callee-saved register arguments SwiftSelf and SwiftError.
   1523   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
   1524     CCValAssign &VA = ArgLocs[I];
   1525     if (VA.getLocInfo() == CCValAssign::Indirect)
   1526       return false;
   1527     if (!VA.isRegLoc())
   1528       return false;
   1529     Register Reg = VA.getLocReg();
   1530     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
   1531       return false;
   1532     if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
   1533       return false;
   1534   }
   1535   return true;
   1536 }
   1537 
   1538 SDValue
   1539 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
   1540                                  SmallVectorImpl<SDValue> &InVals) const {
   1541   SelectionDAG &DAG = CLI.DAG;
   1542   SDLoc &DL = CLI.DL;
   1543   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
   1544   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
   1545   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
   1546   SDValue Chain = CLI.Chain;
   1547   SDValue Callee = CLI.Callee;
   1548   bool &IsTailCall = CLI.IsTailCall;
   1549   CallingConv::ID CallConv = CLI.CallConv;
   1550   bool IsVarArg = CLI.IsVarArg;
   1551   MachineFunction &MF = DAG.getMachineFunction();
   1552   EVT PtrVT = getPointerTy(MF.getDataLayout());
   1553   LLVMContext &Ctx = *DAG.getContext();
   1554 
   1555   // Detect unsupported vector argument and return types.
   1556   if (Subtarget.hasVector()) {
   1557     VerifyVectorTypes(Outs);
   1558     VerifyVectorTypes(Ins);
   1559   }
   1560 
   1561   // Analyze the operands of the call, assigning locations to each operand.
   1562   SmallVector<CCValAssign, 16> ArgLocs;
   1563   SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
   1564   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
   1565 
   1566   // We don't support GuaranteedTailCallOpt, only automatically-detected
   1567   // sibling calls.
   1568   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
   1569     IsTailCall = false;
   1570 
   1571   // Get a count of how many bytes are to be pushed on the stack.
   1572   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
   1573 
   1574   // Mark the start of the call.
   1575   if (!IsTailCall)
   1576     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
   1577 
   1578   // Copy argument values to their designated locations.
   1579   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
   1580   SmallVector<SDValue, 8> MemOpChains;
   1581   SDValue StackPtr;
   1582   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
   1583     CCValAssign &VA = ArgLocs[I];
   1584     SDValue ArgValue = OutVals[I];
   1585 
   1586     if (VA.getLocInfo() == CCValAssign::Indirect) {
   1587       // Store the argument in a stack slot and pass its address.
   1588       unsigned ArgIndex = Outs[I].OrigArgIndex;
   1589       EVT SlotVT;
   1590       if (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
   1591         // Allocate the full stack space for a promoted (and split) argument.
   1592         Type *OrigArgType = CLI.Args[Outs[I].OrigArgIndex].Ty;
   1593         EVT OrigArgVT = getValueType(MF.getDataLayout(), OrigArgType);
   1594         MVT PartVT = getRegisterTypeForCallingConv(Ctx, CLI.CallConv, OrigArgVT);
   1595         unsigned N = getNumRegistersForCallingConv(Ctx, CLI.CallConv, OrigArgVT);
   1596         SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * N);
   1597       } else {
   1598         SlotVT = Outs[I].ArgVT;
   1599       }
   1600       SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
   1601       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
   1602       MemOpChains.push_back(
   1603           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
   1604                        MachinePointerInfo::getFixedStack(MF, FI)));
   1605       // If the original argument was split (e.g. i128), we need
   1606       // to store all parts of it here (and pass just one address).
   1607       assert (Outs[I].PartOffset == 0);
   1608       while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
   1609         SDValue PartValue = OutVals[I + 1];
   1610         unsigned PartOffset = Outs[I + 1].PartOffset;
   1611         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
   1612                                       DAG.getIntPtrConstant(PartOffset, DL));
   1613         MemOpChains.push_back(
   1614             DAG.getStore(Chain, DL, PartValue, Address,
   1615                          MachinePointerInfo::getFixedStack(MF, FI)));
   1616         assert((PartOffset + PartValue.getValueType().getStoreSize() <=
   1617                 SlotVT.getStoreSize()) && "Not enough space for argument part!");
   1618         ++I;
   1619       }
   1620       ArgValue = SpillSlot;
   1621     } else
   1622       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
   1623 
   1624     if (VA.isRegLoc())
   1625       // Queue up the argument copies and emit them at the end.
   1626       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
   1627     else {
   1628       assert(VA.isMemLoc() && "Argument not register or memory");
   1629 
   1630       // Work out the address of the stack slot.  Unpromoted ints and
   1631       // floats are passed as right-justified 8-byte values.
   1632       if (!StackPtr.getNode())
   1633         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
   1634       unsigned Offset = SystemZMC::ELFCallFrameSize + VA.getLocMemOffset();
   1635       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
   1636         Offset += 4;
   1637       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
   1638                                     DAG.getIntPtrConstant(Offset, DL));
   1639 
   1640       // Emit the store.
   1641       MemOpChains.push_back(
   1642           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
   1643     }
   1644   }
   1645 
   1646   // Join the stores, which are independent of one another.
   1647   if (!MemOpChains.empty())
   1648     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
   1649 
   1650   // Accept direct calls by converting symbolic call addresses to the
   1651   // associated Target* opcodes.  Force %r1 to be used for indirect
   1652   // tail calls.
   1653   SDValue Glue;
   1654   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
   1655     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
   1656     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
   1657   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
   1658     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
   1659     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
   1660   } else if (IsTailCall) {
   1661     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
   1662     Glue = Chain.getValue(1);
   1663     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
   1664   }
   1665 
   1666   // Build a sequence of copy-to-reg nodes, chained and glued together.
   1667   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
   1668     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
   1669                              RegsToPass[I].second, Glue);
   1670     Glue = Chain.getValue(1);
   1671   }
   1672 
   1673   // The first call operand is the chain and the second is the target address.
   1674   SmallVector<SDValue, 8> Ops;
   1675   Ops.push_back(Chain);
   1676   Ops.push_back(Callee);
   1677 
   1678   // Add argument registers to the end of the list so that they are
   1679   // known live into the call.
   1680   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
   1681     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
   1682                                   RegsToPass[I].second.getValueType()));
   1683 
   1684   // Add a register mask operand representing the call-preserved registers.
   1685   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
   1686   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
   1687   assert(Mask && "Missing call preserved mask for calling convention");
   1688   Ops.push_back(DAG.getRegisterMask(Mask));
   1689 
   1690   // Glue the call to the argument copies, if any.
   1691   if (Glue.getNode())
   1692     Ops.push_back(Glue);
   1693 
   1694   // Emit the call.
   1695   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   1696   if (IsTailCall)
   1697     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
   1698   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
   1699   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
   1700   Glue = Chain.getValue(1);
   1701 
   1702   // Mark the end of the call, which is glued to the call itself.
   1703   Chain = DAG.getCALLSEQ_END(Chain,
   1704                              DAG.getConstant(NumBytes, DL, PtrVT, true),
   1705                              DAG.getConstant(0, DL, PtrVT, true),
   1706                              Glue, DL);
   1707   Glue = Chain.getValue(1);
   1708 
   1709   // Assign locations to each value returned by this call.
   1710   SmallVector<CCValAssign, 16> RetLocs;
   1711   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
   1712   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
   1713 
   1714   // Copy all of the result registers out of their specified physreg.
   1715   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
   1716     CCValAssign &VA = RetLocs[I];
   1717 
   1718     // Copy the value out, gluing the copy to the end of the call sequence.
   1719     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
   1720                                           VA.getLocVT(), Glue);
   1721     Chain = RetValue.getValue(1);
   1722     Glue = RetValue.getValue(2);
   1723 
   1724     // Convert the value of the return register into the value that's
   1725     // being returned.
   1726     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
   1727   }
   1728 
   1729   return Chain;
   1730 }
   1731 
   1732 bool SystemZTargetLowering::
   1733 CanLowerReturn(CallingConv::ID CallConv,
   1734                MachineFunction &MF, bool isVarArg,
   1735                const SmallVectorImpl<ISD::OutputArg> &Outs,
   1736                LLVMContext &Context) const {
   1737   // Detect unsupported vector return types.
   1738   if (Subtarget.hasVector())
   1739     VerifyVectorTypes(Outs);
   1740 
   1741   // Special case that we cannot easily detect in RetCC_SystemZ since
   1742   // i128 is not a legal type.
   1743   for (auto &Out : Outs)
   1744     if (Out.ArgVT == MVT::i128)
   1745       return false;
   1746 
   1747   SmallVector<CCValAssign, 16> RetLocs;
   1748   CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
   1749   return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
   1750 }
   1751 
   1752 SDValue
   1753 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
   1754                                    bool IsVarArg,
   1755                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
   1756                                    const SmallVectorImpl<SDValue> &OutVals,
   1757                                    const SDLoc &DL, SelectionDAG &DAG) const {
   1758   MachineFunction &MF = DAG.getMachineFunction();
   1759 
   1760   // Detect unsupported vector return types.
   1761   if (Subtarget.hasVector())
   1762     VerifyVectorTypes(Outs);
   1763 
   1764   // Assign locations to each returned value.
   1765   SmallVector<CCValAssign, 16> RetLocs;
   1766   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
   1767   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
   1768 
   1769   // Quick exit for void returns
   1770   if (RetLocs.empty())
   1771     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
   1772 
   1773   if (CallConv == CallingConv::GHC)
   1774     report_fatal_error("GHC functions return void only");
   1775 
   1776   // Copy the result values into the output registers.
   1777   SDValue Glue;
   1778   SmallVector<SDValue, 4> RetOps;
   1779   RetOps.push_back(Chain);
   1780   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
   1781     CCValAssign &VA = RetLocs[I];
   1782     SDValue RetValue = OutVals[I];
   1783 
   1784     // Make the return register live on exit.
   1785     assert(VA.isRegLoc() && "Can only return in registers!");
   1786 
   1787     // Promote the value as required.
   1788     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
   1789 
   1790     // Chain and glue the copies together.
   1791     Register Reg = VA.getLocReg();
   1792     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
   1793     Glue = Chain.getValue(1);
   1794     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
   1795   }
   1796 
   1797   // Update chain and glue.
   1798   RetOps[0] = Chain;
   1799   if (Glue.getNode())
   1800     RetOps.push_back(Glue);
   1801 
   1802   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
   1803 }
   1804 
   1805 // Return true if Op is an intrinsic node with chain that returns the CC value
   1806 // as its only (other) argument.  Provide the associated SystemZISD opcode and
   1807 // the mask of valid CC values if so.
   1808 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
   1809                                       unsigned &CCValid) {
   1810   unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   1811   switch (Id) {
   1812   case Intrinsic::s390_tbegin:
   1813     Opcode = SystemZISD::TBEGIN;
   1814     CCValid = SystemZ::CCMASK_TBEGIN;
   1815     return true;
   1816 
   1817   case Intrinsic::s390_tbegin_nofloat:
   1818     Opcode = SystemZISD::TBEGIN_NOFLOAT;
   1819     CCValid = SystemZ::CCMASK_TBEGIN;
   1820     return true;
   1821 
   1822   case Intrinsic::s390_tend:
   1823     Opcode = SystemZISD::TEND;
   1824     CCValid = SystemZ::CCMASK_TEND;
   1825     return true;
   1826 
   1827   default:
   1828     return false;
   1829   }
   1830 }
   1831 
   1832 // Return true if Op is an intrinsic node without chain that returns the
   1833 // CC value as its final argument.  Provide the associated SystemZISD
   1834 // opcode and the mask of valid CC values if so.
   1835 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
   1836   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   1837   switch (Id) {
   1838   case Intrinsic::s390_vpkshs:
   1839   case Intrinsic::s390_vpksfs:
   1840   case Intrinsic::s390_vpksgs:
   1841     Opcode = SystemZISD::PACKS_CC;
   1842     CCValid = SystemZ::CCMASK_VCMP;
   1843     return true;
   1844 
   1845   case Intrinsic::s390_vpklshs:
   1846   case Intrinsic::s390_vpklsfs:
   1847   case Intrinsic::s390_vpklsgs:
   1848     Opcode = SystemZISD::PACKLS_CC;
   1849     CCValid = SystemZ::CCMASK_VCMP;
   1850     return true;
   1851 
   1852   case Intrinsic::s390_vceqbs:
   1853   case Intrinsic::s390_vceqhs:
   1854   case Intrinsic::s390_vceqfs:
   1855   case Intrinsic::s390_vceqgs:
   1856     Opcode = SystemZISD::VICMPES;
   1857     CCValid = SystemZ::CCMASK_VCMP;
   1858     return true;
   1859 
   1860   case Intrinsic::s390_vchbs:
   1861   case Intrinsic::s390_vchhs:
   1862   case Intrinsic::s390_vchfs:
   1863   case Intrinsic::s390_vchgs:
   1864     Opcode = SystemZISD::VICMPHS;
   1865     CCValid = SystemZ::CCMASK_VCMP;
   1866     return true;
   1867 
   1868   case Intrinsic::s390_vchlbs:
   1869   case Intrinsic::s390_vchlhs:
   1870   case Intrinsic::s390_vchlfs:
   1871   case Intrinsic::s390_vchlgs:
   1872     Opcode = SystemZISD::VICMPHLS;
   1873     CCValid = SystemZ::CCMASK_VCMP;
   1874     return true;
   1875 
   1876   case Intrinsic::s390_vtm:
   1877     Opcode = SystemZISD::VTM;
   1878     CCValid = SystemZ::CCMASK_VCMP;
   1879     return true;
   1880 
   1881   case Intrinsic::s390_vfaebs:
   1882   case Intrinsic::s390_vfaehs:
   1883   case Intrinsic::s390_vfaefs:
   1884     Opcode = SystemZISD::VFAE_CC;
   1885     CCValid = SystemZ::CCMASK_ANY;
   1886     return true;
   1887 
   1888   case Intrinsic::s390_vfaezbs:
   1889   case Intrinsic::s390_vfaezhs:
   1890   case Intrinsic::s390_vfaezfs:
   1891     Opcode = SystemZISD::VFAEZ_CC;
   1892     CCValid = SystemZ::CCMASK_ANY;
   1893     return true;
   1894 
   1895   case Intrinsic::s390_vfeebs:
   1896   case Intrinsic::s390_vfeehs:
   1897   case Intrinsic::s390_vfeefs:
   1898     Opcode = SystemZISD::VFEE_CC;
   1899     CCValid = SystemZ::CCMASK_ANY;
   1900     return true;
   1901 
   1902   case Intrinsic::s390_vfeezbs:
   1903   case Intrinsic::s390_vfeezhs:
   1904   case Intrinsic::s390_vfeezfs:
   1905     Opcode = SystemZISD::VFEEZ_CC;
   1906     CCValid = SystemZ::CCMASK_ANY;
   1907     return true;
   1908 
   1909   case Intrinsic::s390_vfenebs:
   1910   case Intrinsic::s390_vfenehs:
   1911   case Intrinsic::s390_vfenefs:
   1912     Opcode = SystemZISD::VFENE_CC;
   1913     CCValid = SystemZ::CCMASK_ANY;
   1914     return true;
   1915 
   1916   case Intrinsic::s390_vfenezbs:
   1917   case Intrinsic::s390_vfenezhs:
   1918   case Intrinsic::s390_vfenezfs:
   1919     Opcode = SystemZISD::VFENEZ_CC;
   1920     CCValid = SystemZ::CCMASK_ANY;
   1921     return true;
   1922 
   1923   case Intrinsic::s390_vistrbs:
   1924   case Intrinsic::s390_vistrhs:
   1925   case Intrinsic::s390_vistrfs:
   1926     Opcode = SystemZISD::VISTR_CC;
   1927     CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
   1928     return true;
   1929 
   1930   case Intrinsic::s390_vstrcbs:
   1931   case Intrinsic::s390_vstrchs:
   1932   case Intrinsic::s390_vstrcfs:
   1933     Opcode = SystemZISD::VSTRC_CC;
   1934     CCValid = SystemZ::CCMASK_ANY;
   1935     return true;
   1936 
   1937   case Intrinsic::s390_vstrczbs:
   1938   case Intrinsic::s390_vstrczhs:
   1939   case Intrinsic::s390_vstrczfs:
   1940     Opcode = SystemZISD::VSTRCZ_CC;
   1941     CCValid = SystemZ::CCMASK_ANY;
   1942     return true;
   1943 
   1944   case Intrinsic::s390_vstrsb:
   1945   case Intrinsic::s390_vstrsh:
   1946   case Intrinsic::s390_vstrsf:
   1947     Opcode = SystemZISD::VSTRS_CC;
   1948     CCValid = SystemZ::CCMASK_ANY;
   1949     return true;
   1950 
   1951   case Intrinsic::s390_vstrszb:
   1952   case Intrinsic::s390_vstrszh:
   1953   case Intrinsic::s390_vstrszf:
   1954     Opcode = SystemZISD::VSTRSZ_CC;
   1955     CCValid = SystemZ::CCMASK_ANY;
   1956     return true;
   1957 
   1958   case Intrinsic::s390_vfcedbs:
   1959   case Intrinsic::s390_vfcesbs:
   1960     Opcode = SystemZISD::VFCMPES;
   1961     CCValid = SystemZ::CCMASK_VCMP;
   1962     return true;
   1963 
   1964   case Intrinsic::s390_vfchdbs:
   1965   case Intrinsic::s390_vfchsbs:
   1966     Opcode = SystemZISD::VFCMPHS;
   1967     CCValid = SystemZ::CCMASK_VCMP;
   1968     return true;
   1969 
   1970   case Intrinsic::s390_vfchedbs:
   1971   case Intrinsic::s390_vfchesbs:
   1972     Opcode = SystemZISD::VFCMPHES;
   1973     CCValid = SystemZ::CCMASK_VCMP;
   1974     return true;
   1975 
   1976   case Intrinsic::s390_vftcidb:
   1977   case Intrinsic::s390_vftcisb:
   1978     Opcode = SystemZISD::VFTCI;
   1979     CCValid = SystemZ::CCMASK_VCMP;
   1980     return true;
   1981 
   1982   case Intrinsic::s390_tdc:
   1983     Opcode = SystemZISD::TDC;
   1984     CCValid = SystemZ::CCMASK_TDC;
   1985     return true;
   1986 
   1987   default:
   1988     return false;
   1989   }
   1990 }
   1991 
   1992 // Emit an intrinsic with chain and an explicit CC register result.
   1993 static SDNode *emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op,
   1994                                            unsigned Opcode) {
   1995   // Copy all operands except the intrinsic ID.
   1996   unsigned NumOps = Op.getNumOperands();
   1997   SmallVector<SDValue, 6> Ops;
   1998   Ops.reserve(NumOps - 1);
   1999   Ops.push_back(Op.getOperand(0));
   2000   for (unsigned I = 2; I < NumOps; ++I)
   2001     Ops.push_back(Op.getOperand(I));
   2002 
   2003   assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
   2004   SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
   2005   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
   2006   SDValue OldChain = SDValue(Op.getNode(), 1);
   2007   SDValue NewChain = SDValue(Intr.getNode(), 1);
   2008   DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
   2009   return Intr.getNode();
   2010 }
   2011 
   2012 // Emit an intrinsic with an explicit CC register result.
   2013 static SDNode *emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op,
   2014                                    unsigned Opcode) {
   2015   // Copy all operands except the intrinsic ID.
   2016   unsigned NumOps = Op.getNumOperands();
   2017   SmallVector<SDValue, 6> Ops;
   2018   Ops.reserve(NumOps - 1);
   2019   for (unsigned I = 1; I < NumOps; ++I)
   2020     Ops.push_back(Op.getOperand(I));
   2021 
   2022   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops);
   2023   return Intr.getNode();
   2024 }
   2025 
   2026 // CC is a comparison that will be implemented using an integer or
   2027 // floating-point comparison.  Return the condition code mask for
   2028 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
   2029 // unsigned comparisons and clear for signed ones.  In the floating-point
   2030 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
   2031 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
   2032 #define CONV(X) \
   2033   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
   2034   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
   2035   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
   2036 
   2037   switch (CC) {
   2038   default:
   2039     llvm_unreachable("Invalid integer condition!");
   2040 
   2041   CONV(EQ);
   2042   CONV(NE);
   2043   CONV(GT);
   2044   CONV(GE);
   2045   CONV(LT);
   2046   CONV(LE);
   2047 
   2048   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
   2049   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
   2050   }
   2051 #undef CONV
   2052 }
   2053 
   2054 // If C can be converted to a comparison against zero, adjust the operands
   2055 // as necessary.
   2056 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
   2057   if (C.ICmpType == SystemZICMP::UnsignedOnly)
   2058     return;
   2059 
   2060   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
   2061   if (!ConstOp1)
   2062     return;
   2063 
   2064   int64_t Value = ConstOp1->getSExtValue();
   2065   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
   2066       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
   2067       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
   2068       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
   2069     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
   2070     C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
   2071   }
   2072 }
   2073 
   2074 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
   2075 // adjust the operands as necessary.
   2076 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
   2077                              Comparison &C) {
   2078   // For us to make any changes, it must a comparison between a single-use
   2079   // load and a constant.
   2080   if (!C.Op0.hasOneUse() ||
   2081       C.Op0.getOpcode() != ISD::LOAD ||
   2082       C.Op1.getOpcode() != ISD::Constant)
   2083     return;
   2084 
   2085   // We must have an 8- or 16-bit load.
   2086   auto *Load = cast<LoadSDNode>(C.Op0);
   2087   unsigned NumBits = Load->getMemoryVT().getSizeInBits();
   2088   if ((NumBits != 8 && NumBits != 16) ||
   2089       NumBits != Load->getMemoryVT().getStoreSizeInBits())
   2090     return;
   2091 
   2092   // The load must be an extending one and the constant must be within the
   2093   // range of the unextended value.
   2094   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
   2095   uint64_t Value = ConstOp1->getZExtValue();
   2096   uint64_t Mask = (1 << NumBits) - 1;
   2097   if (Load->getExtensionType() == ISD::SEXTLOAD) {
   2098     // Make sure that ConstOp1 is in range of C.Op0.
   2099     int64_t SignedValue = ConstOp1->getSExtValue();
   2100     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
   2101       return;
   2102     if (C.ICmpType != SystemZICMP::SignedOnly) {
   2103       // Unsigned comparison between two sign-extended values is equivalent
   2104       // to unsigned comparison between two zero-extended values.
   2105       Value &= Mask;
   2106     } else if (NumBits == 8) {
   2107       // Try to treat the comparison as unsigned, so that we can use CLI.
   2108       // Adjust CCMask and Value as necessary.
   2109       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
   2110         // Test whether the high bit of the byte is set.
   2111         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
   2112       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
   2113         // Test whether the high bit of the byte is clear.
   2114         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
   2115       else
   2116         // No instruction exists for this combination.
   2117         return;
   2118       C.ICmpType = SystemZICMP::UnsignedOnly;
   2119     }
   2120   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
   2121     if (Value > Mask)
   2122       return;
   2123     // If the constant is in range, we can use any comparison.
   2124     C.ICmpType = SystemZICMP::Any;
   2125   } else
   2126     return;
   2127 
   2128   // Make sure that the first operand is an i32 of the right extension type.
   2129   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
   2130                               ISD::SEXTLOAD :
   2131                               ISD::ZEXTLOAD);
   2132   if (C.Op0.getValueType() != MVT::i32 ||
   2133       Load->getExtensionType() != ExtType) {
   2134     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
   2135                            Load->getBasePtr(), Load->getPointerInfo(),
   2136                            Load->getMemoryVT(), Load->getAlignment(),
   2137                            Load->getMemOperand()->getFlags());
   2138     // Update the chain uses.
   2139     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
   2140   }
   2141 
   2142   // Make sure that the second operand is an i32 with the right value.
   2143   if (C.Op1.getValueType() != MVT::i32 ||
   2144       Value != ConstOp1->getZExtValue())
   2145     C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
   2146 }
   2147 
   2148 // Return true if Op is either an unextended load, or a load suitable
   2149 // for integer register-memory comparisons of type ICmpType.
   2150 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
   2151   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
   2152   if (Load) {
   2153     // There are no instructions to compare a register with a memory byte.
   2154     if (Load->getMemoryVT() == MVT::i8)
   2155       return false;
   2156     // Otherwise decide on extension type.
   2157     switch (Load->getExtensionType()) {
   2158     case ISD::NON_EXTLOAD:
   2159       return true;
   2160     case ISD::SEXTLOAD:
   2161       return ICmpType != SystemZICMP::UnsignedOnly;
   2162     case ISD::ZEXTLOAD:
   2163       return ICmpType != SystemZICMP::SignedOnly;
   2164     default:
   2165       break;
   2166     }
   2167   }
   2168   return false;
   2169 }
   2170 
   2171 // Return true if it is better to swap the operands of C.
   2172 static bool shouldSwapCmpOperands(const Comparison &C) {
   2173   // Leave f128 comparisons alone, since they have no memory forms.
   2174   if (C.Op0.getValueType() == MVT::f128)
   2175     return false;
   2176 
   2177   // Always keep a floating-point constant second, since comparisons with
   2178   // zero can use LOAD TEST and comparisons with other constants make a
   2179   // natural memory operand.
   2180   if (isa<ConstantFPSDNode>(C.Op1))
   2181     return false;
   2182 
   2183   // Never swap comparisons with zero since there are many ways to optimize
   2184   // those later.
   2185   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
   2186   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
   2187     return false;
   2188 
   2189   // Also keep natural memory operands second if the loaded value is
   2190   // only used here.  Several comparisons have memory forms.
   2191   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
   2192     return false;
   2193 
   2194   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
   2195   // In that case we generally prefer the memory to be second.
   2196   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
   2197     // The only exceptions are when the second operand is a constant and
   2198     // we can use things like CHHSI.
   2199     if (!ConstOp1)
   2200       return true;
   2201     // The unsigned memory-immediate instructions can handle 16-bit
   2202     // unsigned integers.
   2203     if (C.ICmpType != SystemZICMP::SignedOnly &&
   2204         isUInt<16>(ConstOp1->getZExtValue()))
   2205       return false;
   2206     // The signed memory-immediate instructions can handle 16-bit
   2207     // signed integers.
   2208     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
   2209         isInt<16>(ConstOp1->getSExtValue()))
   2210       return false;
   2211     return true;
   2212   }
   2213 
   2214   // Try to promote the use of CGFR and CLGFR.
   2215   unsigned Opcode0 = C.Op0.getOpcode();
   2216   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
   2217     return true;
   2218   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
   2219     return true;
   2220   if (C.ICmpType != SystemZICMP::SignedOnly &&
   2221       Opcode0 == ISD::AND &&
   2222       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
   2223       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
   2224     return true;
   2225 
   2226   return false;
   2227 }
   2228 
   2229 // Check whether C tests for equality between X and Y and whether X - Y
   2230 // or Y - X is also computed.  In that case it's better to compare the
   2231 // result of the subtraction against zero.
   2232 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
   2233                                  Comparison &C) {
   2234   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
   2235       C.CCMask == SystemZ::CCMASK_CMP_NE) {
   2236     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
   2237       SDNode *N = *I;
   2238       if (N->getOpcode() == ISD::SUB &&
   2239           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
   2240            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
   2241         C.Op0 = SDValue(N, 0);
   2242         C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
   2243         return;
   2244       }
   2245     }
   2246   }
   2247 }
   2248 
   2249 // Check whether C compares a floating-point value with zero and if that
   2250 // floating-point value is also negated.  In this case we can use the
   2251 // negation to set CC, so avoiding separate LOAD AND TEST and
   2252 // LOAD (NEGATIVE/COMPLEMENT) instructions.
   2253 static void adjustForFNeg(Comparison &C) {
   2254   // This optimization is invalid for strict comparisons, since FNEG
   2255   // does not raise any exceptions.
   2256   if (C.Chain)
   2257     return;
   2258   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
   2259   if (C1 && C1->isZero()) {
   2260     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
   2261       SDNode *N = *I;
   2262       if (N->getOpcode() == ISD::FNEG) {
   2263         C.Op0 = SDValue(N, 0);
   2264         C.CCMask = SystemZ::reverseCCMask(C.CCMask);
   2265         return;
   2266       }
   2267     }
   2268   }
   2269 }
   2270 
   2271 // Check whether C compares (shl X, 32) with 0 and whether X is
   2272 // also sign-extended.  In that case it is better to test the result
   2273 // of the sign extension using LTGFR.
   2274 //
   2275 // This case is important because InstCombine transforms a comparison
   2276 // with (sext (trunc X)) into a comparison with (shl X, 32).
   2277 static void adjustForLTGFR(Comparison &C) {
   2278   // Check for a comparison between (shl X, 32) and 0.
   2279   if (C.Op0.getOpcode() == ISD::SHL &&
   2280       C.Op0.getValueType() == MVT::i64 &&
   2281       C.Op1.getOpcode() == ISD::Constant &&
   2282       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
   2283     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
   2284     if (C1 && C1->getZExtValue() == 32) {
   2285       SDValue ShlOp0 = C.Op0.getOperand(0);
   2286       // See whether X has any SIGN_EXTEND_INREG uses.
   2287       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
   2288         SDNode *N = *I;
   2289         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
   2290             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
   2291           C.Op0 = SDValue(N, 0);
   2292           return;
   2293         }
   2294       }
   2295     }
   2296   }
   2297 }
   2298 
   2299 // If C compares the truncation of an extending load, try to compare
   2300 // the untruncated value instead.  This exposes more opportunities to
   2301 // reuse CC.
   2302 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
   2303                                Comparison &C) {
   2304   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
   2305       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
   2306       C.Op1.getOpcode() == ISD::Constant &&
   2307       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
   2308     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
   2309     if (L->getMemoryVT().getStoreSizeInBits().getFixedSize() <=
   2310         C.Op0.getValueSizeInBits().getFixedSize()) {
   2311       unsigned Type = L->getExtensionType();
   2312       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
   2313           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
   2314         C.Op0 = C.Op0.getOperand(0);
   2315         C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
   2316       }
   2317     }
   2318   }
   2319 }
   2320 
   2321 // Return true if shift operation N has an in-range constant shift value.
   2322 // Store it in ShiftVal if so.
   2323 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
   2324   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
   2325   if (!Shift)
   2326     return false;
   2327 
   2328   uint64_t Amount = Shift->getZExtValue();
   2329   if (Amount >= N.getValueSizeInBits())
   2330     return false;
   2331 
   2332   ShiftVal = Amount;
   2333   return true;
   2334 }
   2335 
   2336 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
   2337 // instruction and whether the CC value is descriptive enough to handle
   2338 // a comparison of type Opcode between the AND result and CmpVal.
   2339 // CCMask says which comparison result is being tested and BitSize is
   2340 // the number of bits in the operands.  If TEST UNDER MASK can be used,
   2341 // return the corresponding CC mask, otherwise return 0.
   2342 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
   2343                                      uint64_t Mask, uint64_t CmpVal,
   2344                                      unsigned ICmpType) {
   2345   assert(Mask != 0 && "ANDs with zero should have been removed by now");
   2346 
   2347   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
   2348   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
   2349       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
   2350     return 0;
   2351 
   2352   // Work out the masks for the lowest and highest bits.
   2353   unsigned HighShift = 63 - countLeadingZeros(Mask);
   2354   uint64_t High = uint64_t(1) << HighShift;
   2355   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
   2356 
   2357   // Signed ordered comparisons are effectively unsigned if the sign
   2358   // bit is dropped.
   2359   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
   2360 
   2361   // Check for equality comparisons with 0, or the equivalent.
   2362   if (CmpVal == 0) {
   2363     if (CCMask == SystemZ::CCMASK_CMP_EQ)
   2364       return SystemZ::CCMASK_TM_ALL_0;
   2365     if (CCMask == SystemZ::CCMASK_CMP_NE)
   2366       return SystemZ::CCMASK_TM_SOME_1;
   2367   }
   2368   if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
   2369     if (CCMask == SystemZ::CCMASK_CMP_LT)
   2370       return SystemZ::CCMASK_TM_ALL_0;
   2371     if (CCMask == SystemZ::CCMASK_CMP_GE)
   2372       return SystemZ::CCMASK_TM_SOME_1;
   2373   }
   2374   if (EffectivelyUnsigned && CmpVal < Low) {
   2375     if (CCMask == SystemZ::CCMASK_CMP_LE)
   2376       return SystemZ::CCMASK_TM_ALL_0;
   2377     if (CCMask == SystemZ::CCMASK_CMP_GT)
   2378       return SystemZ::CCMASK_TM_SOME_1;
   2379   }
   2380 
   2381   // Check for equality comparisons with the mask, or the equivalent.
   2382   if (CmpVal == Mask) {
   2383     if (CCMask == SystemZ::CCMASK_CMP_EQ)
   2384       return SystemZ::CCMASK_TM_ALL_1;
   2385     if (CCMask == SystemZ::CCMASK_CMP_NE)
   2386       return SystemZ::CCMASK_TM_SOME_0;
   2387   }
   2388   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
   2389     if (CCMask == SystemZ::CCMASK_CMP_GT)
   2390       return SystemZ::CCMASK_TM_ALL_1;
   2391     if (CCMask == SystemZ::CCMASK_CMP_LE)
   2392       return SystemZ::CCMASK_TM_SOME_0;
   2393   }
   2394   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
   2395     if (CCMask == SystemZ::CCMASK_CMP_GE)
   2396       return SystemZ::CCMASK_TM_ALL_1;
   2397     if (CCMask == SystemZ::CCMASK_CMP_LT)
   2398       return SystemZ::CCMASK_TM_SOME_0;
   2399   }
   2400 
   2401   // Check for ordered comparisons with the top bit.
   2402   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
   2403     if (CCMask == SystemZ::CCMASK_CMP_LE)
   2404       return SystemZ::CCMASK_TM_MSB_0;
   2405     if (CCMask == SystemZ::CCMASK_CMP_GT)
   2406       return SystemZ::CCMASK_TM_MSB_1;
   2407   }
   2408   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
   2409     if (CCMask == SystemZ::CCMASK_CMP_LT)
   2410       return SystemZ::CCMASK_TM_MSB_0;
   2411     if (CCMask == SystemZ::CCMASK_CMP_GE)
   2412       return SystemZ::CCMASK_TM_MSB_1;
   2413   }
   2414 
   2415   // If there are just two bits, we can do equality checks for Low and High
   2416   // as well.
   2417   if (Mask == Low + High) {
   2418     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
   2419       return SystemZ::CCMASK_TM_MIXED_MSB_0;
   2420     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
   2421       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
   2422     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
   2423       return SystemZ::CCMASK_TM_MIXED_MSB_1;
   2424     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
   2425       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
   2426   }
   2427 
   2428   // Looks like we've exhausted our options.
   2429   return 0;
   2430 }
   2431 
   2432 // See whether C can be implemented as a TEST UNDER MASK instruction.
   2433 // Update the arguments with the TM version if so.
   2434 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
   2435                                    Comparison &C) {
   2436   // Check that we have a comparison with a constant.
   2437   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
   2438   if (!ConstOp1)
   2439     return;
   2440   uint64_t CmpVal = ConstOp1->getZExtValue();
   2441 
   2442   // Check whether the nonconstant input is an AND with a constant mask.
   2443   Comparison NewC(C);
   2444   uint64_t MaskVal;
   2445   ConstantSDNode *Mask = nullptr;
   2446   if (C.Op0.getOpcode() == ISD::AND) {
   2447     NewC.Op0 = C.Op0.getOperand(0);
   2448     NewC.Op1 = C.Op0.getOperand(1);
   2449     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
   2450     if (!Mask)
   2451       return;
   2452     MaskVal = Mask->getZExtValue();
   2453   } else {
   2454     // There is no instruction to compare with a 64-bit immediate
   2455     // so use TMHH instead if possible.  We need an unsigned ordered
   2456     // comparison with an i64 immediate.
   2457     if (NewC.Op0.getValueType() != MVT::i64 ||
   2458         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
   2459         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
   2460         NewC.ICmpType == SystemZICMP::SignedOnly)
   2461       return;
   2462     // Convert LE and GT comparisons into LT and GE.
   2463     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
   2464         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
   2465       if (CmpVal == uint64_t(-1))
   2466         return;
   2467       CmpVal += 1;
   2468       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
   2469     }
   2470     // If the low N bits of Op1 are zero than the low N bits of Op0 can
   2471     // be masked off without changing the result.
   2472     MaskVal = -(CmpVal & -CmpVal);
   2473     NewC.ICmpType = SystemZICMP::UnsignedOnly;
   2474   }
   2475   if (!MaskVal)
   2476     return;
   2477 
   2478   // Check whether the combination of mask, comparison value and comparison
   2479   // type are suitable.
   2480   unsigned BitSize = NewC.Op0.getValueSizeInBits();
   2481   unsigned NewCCMask, ShiftVal;
   2482   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
   2483       NewC.Op0.getOpcode() == ISD::SHL &&
   2484       isSimpleShift(NewC.Op0, ShiftVal) &&
   2485       (MaskVal >> ShiftVal != 0) &&
   2486       ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
   2487       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
   2488                                         MaskVal >> ShiftVal,
   2489                                         CmpVal >> ShiftVal,
   2490                                         SystemZICMP::Any))) {
   2491     NewC.Op0 = NewC.Op0.getOperand(0);
   2492     MaskVal >>= ShiftVal;
   2493   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
   2494              NewC.Op0.getOpcode() == ISD::SRL &&
   2495              isSimpleShift(NewC.Op0, ShiftVal) &&
   2496              (MaskVal << ShiftVal != 0) &&
   2497              ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
   2498              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
   2499                                                MaskVal << ShiftVal,
   2500                                                CmpVal << ShiftVal,
   2501                                                SystemZICMP::UnsignedOnly))) {
   2502     NewC.Op0 = NewC.Op0.getOperand(0);
   2503     MaskVal <<= ShiftVal;
   2504   } else {
   2505     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
   2506                                      NewC.ICmpType);
   2507     if (!NewCCMask)
   2508       return;
   2509   }
   2510 
   2511   // Go ahead and make the change.
   2512   C.Opcode = SystemZISD::TM;
   2513   C.Op0 = NewC.Op0;
   2514   if (Mask && Mask->getZExtValue() == MaskVal)
   2515     C.Op1 = SDValue(Mask, 0);
   2516   else
   2517     C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
   2518   C.CCValid = SystemZ::CCMASK_TM;
   2519   C.CCMask = NewCCMask;
   2520 }
   2521 
   2522 // See whether the comparison argument contains a redundant AND
   2523 // and remove it if so.  This sometimes happens due to the generic
   2524 // BRCOND expansion.
   2525 static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL,
   2526                                   Comparison &C) {
   2527   if (C.Op0.getOpcode() != ISD::AND)
   2528     return;
   2529   auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
   2530   if (!Mask)
   2531     return;
   2532   KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
   2533   if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
   2534     return;
   2535 
   2536   C.Op0 = C.Op0.getOperand(0);
   2537 }
   2538 
   2539 // Return a Comparison that tests the condition-code result of intrinsic
   2540 // node Call against constant integer CC using comparison code Cond.
   2541 // Opcode is the opcode of the SystemZISD operation for the intrinsic
   2542 // and CCValid is the set of possible condition-code results.
   2543 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
   2544                                   SDValue Call, unsigned CCValid, uint64_t CC,
   2545                                   ISD::CondCode Cond) {
   2546   Comparison C(Call, SDValue(), SDValue());
   2547   C.Opcode = Opcode;
   2548   C.CCValid = CCValid;
   2549   if (Cond == ISD::SETEQ)
   2550     // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
   2551     C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
   2552   else if (Cond == ISD::SETNE)
   2553     // ...and the inverse of that.
   2554     C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
   2555   else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
   2556     // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
   2557     // always true for CC>3.
   2558     C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
   2559   else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
   2560     // ...and the inverse of that.
   2561     C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
   2562   else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
   2563     // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
   2564     // always true for CC>3.
   2565     C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
   2566   else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
   2567     // ...and the inverse of that.
   2568     C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
   2569   else
   2570     llvm_unreachable("Unexpected integer comparison type");
   2571   C.CCMask &= CCValid;
   2572   return C;
   2573 }
   2574 
   2575 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
   2576 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
   2577                          ISD::CondCode Cond, const SDLoc &DL,
   2578                          SDValue Chain = SDValue(),
   2579                          bool IsSignaling = false) {
   2580   if (CmpOp1.getOpcode() == ISD::Constant) {
   2581     assert(!Chain);
   2582     uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
   2583     unsigned Opcode, CCValid;
   2584     if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
   2585         CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
   2586         isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
   2587       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
   2588     if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
   2589         CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
   2590         isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
   2591       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
   2592   }
   2593   Comparison C(CmpOp0, CmpOp1, Chain);
   2594   C.CCMask = CCMaskForCondCode(Cond);
   2595   if (C.Op0.getValueType().isFloatingPoint()) {
   2596     C.CCValid = SystemZ::CCMASK_FCMP;
   2597     if (!C.Chain)
   2598       C.Opcode = SystemZISD::FCMP;
   2599     else if (!IsSignaling)
   2600       C.Opcode = SystemZISD::STRICT_FCMP;
   2601     else
   2602       C.Opcode = SystemZISD::STRICT_FCMPS;
   2603     adjustForFNeg(C);
   2604   } else {
   2605     assert(!C.Chain);
   2606     C.CCValid = SystemZ::CCMASK_ICMP;
   2607     C.Opcode = SystemZISD::ICMP;
   2608     // Choose the type of comparison.  Equality and inequality tests can
   2609     // use either signed or unsigned comparisons.  The choice also doesn't
   2610     // matter if both sign bits are known to be clear.  In those cases we
   2611     // want to give the main isel code the freedom to choose whichever
   2612     // form fits best.
   2613     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
   2614         C.CCMask == SystemZ::CCMASK_CMP_NE ||
   2615         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
   2616       C.ICmpType = SystemZICMP::Any;
   2617     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
   2618       C.ICmpType = SystemZICMP::UnsignedOnly;
   2619     else
   2620       C.ICmpType = SystemZICMP::SignedOnly;
   2621     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
   2622     adjustForRedundantAnd(DAG, DL, C);
   2623     adjustZeroCmp(DAG, DL, C);
   2624     adjustSubwordCmp(DAG, DL, C);
   2625     adjustForSubtraction(DAG, DL, C);
   2626     adjustForLTGFR(C);
   2627     adjustICmpTruncate(DAG, DL, C);
   2628   }
   2629 
   2630   if (shouldSwapCmpOperands(C)) {
   2631     std::swap(C.Op0, C.Op1);
   2632     C.CCMask = SystemZ::reverseCCMask(C.CCMask);
   2633   }
   2634 
   2635   adjustForTestUnderMask(DAG, DL, C);
   2636   return C;
   2637 }
   2638 
   2639 // Emit the comparison instruction described by C.
   2640 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
   2641   if (!C.Op1.getNode()) {
   2642     SDNode *Node;
   2643     switch (C.Op0.getOpcode()) {
   2644     case ISD::INTRINSIC_W_CHAIN:
   2645       Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
   2646       return SDValue(Node, 0);
   2647     case ISD::INTRINSIC_WO_CHAIN:
   2648       Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
   2649       return SDValue(Node, Node->getNumValues() - 1);
   2650     default:
   2651       llvm_unreachable("Invalid comparison operands");
   2652     }
   2653   }
   2654   if (C.Opcode == SystemZISD::ICMP)
   2655     return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
   2656                        DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
   2657   if (C.Opcode == SystemZISD::TM) {
   2658     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
   2659                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
   2660     return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
   2661                        DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
   2662   }
   2663   if (C.Chain) {
   2664     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
   2665     return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
   2666   }
   2667   return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
   2668 }
   2669 
   2670 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
   2671 // 64 bits.  Extend is the extension type to use.  Store the high part
   2672 // in Hi and the low part in Lo.
   2673 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
   2674                             SDValue Op0, SDValue Op1, SDValue &Hi,
   2675                             SDValue &Lo) {
   2676   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
   2677   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
   2678   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
   2679   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
   2680                    DAG.getConstant(32, DL, MVT::i64));
   2681   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
   2682   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
   2683 }
   2684 
   2685 // Lower a binary operation that produces two VT results, one in each
   2686 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
   2687 // and Opcode performs the GR128 operation.  Store the even register result
   2688 // in Even and the odd register result in Odd.
   2689 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
   2690                              unsigned Opcode, SDValue Op0, SDValue Op1,
   2691                              SDValue &Even, SDValue &Odd) {
   2692   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
   2693   bool Is32Bit = is32Bit(VT);
   2694   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
   2695   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
   2696 }
   2697 
   2698 // Return an i32 value that is 1 if the CC value produced by CCReg is
   2699 // in the mask CCMask and 0 otherwise.  CC is known to have a value
   2700 // in CCValid, so other values can be ignored.
   2701 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
   2702                          unsigned CCValid, unsigned CCMask) {
   2703   SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
   2704                    DAG.getConstant(0, DL, MVT::i32),
   2705                    DAG.getTargetConstant(CCValid, DL, MVT::i32),
   2706                    DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
   2707   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
   2708 }
   2709 
   2710 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
   2711 // be done directly.  Mode is CmpMode::Int for integer comparisons, CmpMode::FP
   2712 // for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
   2713 // floating-point comparisons, and CmpMode::SignalingFP for strict signaling
   2714 // floating-point comparisons.
   2715 enum class CmpMode { Int, FP, StrictFP, SignalingFP };
   2716 static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode) {
   2717   switch (CC) {
   2718   case ISD::SETOEQ:
   2719   case ISD::SETEQ:
   2720     switch (Mode) {
   2721     case CmpMode::Int:         return SystemZISD::VICMPE;
   2722     case CmpMode::FP:          return SystemZISD::VFCMPE;
   2723     case CmpMode::StrictFP:    return SystemZISD::STRICT_VFCMPE;
   2724     case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
   2725     }
   2726     llvm_unreachable("Bad mode");
   2727 
   2728   case ISD::SETOGE:
   2729   case ISD::SETGE:
   2730     switch (Mode) {
   2731     case CmpMode::Int:         return 0;
   2732     case CmpMode::FP:          return SystemZISD::VFCMPHE;
   2733     case CmpMode::StrictFP:    return SystemZISD::STRICT_VFCMPHE;
   2734     case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
   2735     }
   2736     llvm_unreachable("Bad mode");
   2737 
   2738   case ISD::SETOGT:
   2739   case ISD::SETGT:
   2740     switch (Mode) {
   2741     case CmpMode::Int:         return SystemZISD::VICMPH;
   2742     case CmpMode::FP:          return SystemZISD::VFCMPH;
   2743     case CmpMode::StrictFP:    return SystemZISD::STRICT_VFCMPH;
   2744     case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
   2745     }
   2746     llvm_unreachable("Bad mode");
   2747 
   2748   case ISD::SETUGT:
   2749     switch (Mode) {
   2750     case CmpMode::Int:         return SystemZISD::VICMPHL;
   2751     case CmpMode::FP:          return 0;
   2752     case CmpMode::StrictFP:    return 0;
   2753     case CmpMode::SignalingFP: return 0;
   2754     }
   2755     llvm_unreachable("Bad mode");
   2756 
   2757   default:
   2758     return 0;
   2759   }
   2760 }
   2761 
   2762 // Return the SystemZISD vector comparison operation for CC or its inverse,
   2763 // or 0 if neither can be done directly.  Indicate in Invert whether the
   2764 // result is for the inverse of CC.  Mode is as above.
   2765 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode,
   2766                                             bool &Invert) {
   2767   if (unsigned Opcode = getVectorComparison(CC, Mode)) {
   2768     Invert = false;
   2769     return Opcode;
   2770   }
   2771 
   2772   CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
   2773   if (unsigned Opcode = getVectorComparison(CC, Mode)) {
   2774     Invert = true;
   2775     return Opcode;
   2776   }
   2777 
   2778   return 0;
   2779 }
   2780 
   2781 // Return a v2f64 that contains the extended form of elements Start and Start+1
   2782 // of v4f32 value Op.  If Chain is nonnull, return the strict form.
   2783 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
   2784                                   SDValue Op, SDValue Chain) {
   2785   int Mask[] = { Start, -1, Start + 1, -1 };
   2786   Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
   2787   if (Chain) {
   2788     SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
   2789     return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
   2790   }
   2791   return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
   2792 }
   2793 
   2794 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
   2795 // producing a result of type VT.  If Chain is nonnull, return the strict form.
   2796 SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
   2797                                             const SDLoc &DL, EVT VT,
   2798                                             SDValue CmpOp0,
   2799                                             SDValue CmpOp1,
   2800                                             SDValue Chain) const {
   2801   // There is no hardware support for v4f32 (unless we have the vector
   2802   // enhancements facility 1), so extend the vector into two v2f64s
   2803   // and compare those.
   2804   if (CmpOp0.getValueType() == MVT::v4f32 &&
   2805       !Subtarget.hasVectorEnhancements1()) {
   2806     SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
   2807     SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
   2808     SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
   2809     SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
   2810     if (Chain) {
   2811       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
   2812       SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
   2813       SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
   2814       SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
   2815       SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
   2816                             H1.getValue(1), L1.getValue(1),
   2817                             HRes.getValue(1), LRes.getValue(1) };
   2818       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
   2819       SDValue Ops[2] = { Res, NewChain };
   2820       return DAG.getMergeValues(Ops, DL);
   2821     }
   2822     SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
   2823     SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
   2824     return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
   2825   }
   2826   if (Chain) {
   2827     SDVTList VTs = DAG.getVTList(VT, MVT::Other);
   2828     return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
   2829   }
   2830   return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
   2831 }
   2832 
   2833 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
   2834 // an integer mask of type VT.  If Chain is nonnull, we have a strict
   2835 // floating-point comparison.  If in addition IsSignaling is true, we have
   2836 // a strict signaling floating-point comparison.
   2837 SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
   2838                                                 const SDLoc &DL, EVT VT,
   2839                                                 ISD::CondCode CC,
   2840                                                 SDValue CmpOp0,
   2841                                                 SDValue CmpOp1,
   2842                                                 SDValue Chain,
   2843                                                 bool IsSignaling) const {
   2844   bool IsFP = CmpOp0.getValueType().isFloatingPoint();
   2845   assert (!Chain || IsFP);
   2846   assert (!IsSignaling || Chain);
   2847   CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
   2848                  Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
   2849   bool Invert = false;
   2850   SDValue Cmp;
   2851   switch (CC) {
   2852     // Handle tests for order using (or (ogt y x) (oge x y)).
   2853   case ISD::SETUO:
   2854     Invert = true;
   2855     LLVM_FALLTHROUGH;
   2856   case ISD::SETO: {
   2857     assert(IsFP && "Unexpected integer comparison");
   2858     SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
   2859                               DL, VT, CmpOp1, CmpOp0, Chain);
   2860     SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
   2861                               DL, VT, CmpOp0, CmpOp1, Chain);
   2862     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
   2863     if (Chain)
   2864       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
   2865                           LT.getValue(1), GE.getValue(1));
   2866     break;
   2867   }
   2868 
   2869     // Handle <> tests using (or (ogt y x) (ogt x y)).
   2870   case ISD::SETUEQ:
   2871     Invert = true;
   2872     LLVM_FALLTHROUGH;
   2873   case ISD::SETONE: {
   2874     assert(IsFP && "Unexpected integer comparison");
   2875     SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
   2876                               DL, VT, CmpOp1, CmpOp0, Chain);
   2877     SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
   2878                               DL, VT, CmpOp0, CmpOp1, Chain);
   2879     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
   2880     if (Chain)
   2881       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
   2882                           LT.getValue(1), GT.getValue(1));
   2883     break;
   2884   }
   2885 
   2886     // Otherwise a single comparison is enough.  It doesn't really
   2887     // matter whether we try the inversion or the swap first, since
   2888     // there are no cases where both work.
   2889   default:
   2890     if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
   2891       Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
   2892     else {
   2893       CC = ISD::getSetCCSwappedOperands(CC);
   2894       if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
   2895         Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
   2896       else
   2897         llvm_unreachable("Unhandled comparison");
   2898     }
   2899     if (Chain)
   2900       Chain = Cmp.getValue(1);
   2901     break;
   2902   }
   2903   if (Invert) {
   2904     SDValue Mask =
   2905       DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64));
   2906     Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
   2907   }
   2908   if (Chain && Chain.getNode() != Cmp.getNode()) {
   2909     SDValue Ops[2] = { Cmp, Chain };
   2910     Cmp = DAG.getMergeValues(Ops, DL);
   2911   }
   2912   return Cmp;
   2913 }
   2914 
   2915 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
   2916                                           SelectionDAG &DAG) const {
   2917   SDValue CmpOp0   = Op.getOperand(0);
   2918   SDValue CmpOp1   = Op.getOperand(1);
   2919   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
   2920   SDLoc DL(Op);
   2921   EVT VT = Op.getValueType();
   2922   if (VT.isVector())
   2923     return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
   2924 
   2925   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
   2926   SDValue CCReg = emitCmp(DAG, DL, C);
   2927   return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
   2928 }
   2929 
   2930 SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
   2931                                                   SelectionDAG &DAG,
   2932                                                   bool IsSignaling) const {
   2933   SDValue Chain    = Op.getOperand(0);
   2934   SDValue CmpOp0   = Op.getOperand(1);
   2935   SDValue CmpOp1   = Op.getOperand(2);
   2936   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
   2937   SDLoc DL(Op);
   2938   EVT VT = Op.getNode()->getValueType(0);
   2939   if (VT.isVector()) {
   2940     SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
   2941                                    Chain, IsSignaling);
   2942     return Res.getValue(Op.getResNo());
   2943   }
   2944 
   2945   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
   2946   SDValue CCReg = emitCmp(DAG, DL, C);
   2947   CCReg->setFlags(Op->getFlags());
   2948   SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
   2949   SDValue Ops[2] = { Result, CCReg.getValue(1) };
   2950   return DAG.getMergeValues(Ops, DL);
   2951 }
   2952 
   2953 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
   2954   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
   2955   SDValue CmpOp0   = Op.getOperand(2);
   2956   SDValue CmpOp1   = Op.getOperand(3);
   2957   SDValue Dest     = Op.getOperand(4);
   2958   SDLoc DL(Op);
   2959 
   2960   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
   2961   SDValue CCReg = emitCmp(DAG, DL, C);
   2962   return DAG.getNode(
   2963       SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
   2964       DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
   2965       DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
   2966 }
   2967 
   2968 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
   2969 // allowing Pos and Neg to be wider than CmpOp.
   2970 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
   2971   return (Neg.getOpcode() == ISD::SUB &&
   2972           Neg.getOperand(0).getOpcode() == ISD::Constant &&
   2973           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
   2974           Neg.getOperand(1) == Pos &&
   2975           (Pos == CmpOp ||
   2976            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
   2977             Pos.getOperand(0) == CmpOp)));
   2978 }
   2979 
   2980 // Return the absolute or negative absolute of Op; IsNegative decides which.
   2981 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
   2982                            bool IsNegative) {
   2983   Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
   2984   if (IsNegative)
   2985     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
   2986                      DAG.getConstant(0, DL, Op.getValueType()), Op);
   2987   return Op;
   2988 }
   2989 
   2990 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
   2991                                               SelectionDAG &DAG) const {
   2992   SDValue CmpOp0   = Op.getOperand(0);
   2993   SDValue CmpOp1   = Op.getOperand(1);
   2994   SDValue TrueOp   = Op.getOperand(2);
   2995   SDValue FalseOp  = Op.getOperand(3);
   2996   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
   2997   SDLoc DL(Op);
   2998 
   2999   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
   3000 
   3001   // Check for absolute and negative-absolute selections, including those
   3002   // where the comparison value is sign-extended (for LPGFR and LNGFR).
   3003   // This check supplements the one in DAGCombiner.
   3004   if (C.Opcode == SystemZISD::ICMP &&
   3005       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
   3006       C.CCMask != SystemZ::CCMASK_CMP_NE &&
   3007       C.Op1.getOpcode() == ISD::Constant &&
   3008       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
   3009     if (isAbsolute(C.Op0, TrueOp, FalseOp))
   3010       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
   3011     if (isAbsolute(C.Op0, FalseOp, TrueOp))
   3012       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
   3013   }
   3014 
   3015   SDValue CCReg = emitCmp(DAG, DL, C);
   3016   SDValue Ops[] = {TrueOp, FalseOp,
   3017                    DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
   3018                    DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
   3019 
   3020   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
   3021 }
   3022 
   3023 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
   3024                                                   SelectionDAG &DAG) const {
   3025   SDLoc DL(Node);
   3026   const GlobalValue *GV = Node->getGlobal();
   3027   int64_t Offset = Node->getOffset();
   3028   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3029   CodeModel::Model CM = DAG.getTarget().getCodeModel();
   3030 
   3031   SDValue Result;
   3032   if (Subtarget.isPC32DBLSymbol(GV, CM)) {
   3033     if (isInt<32>(Offset)) {
   3034       // Assign anchors at 1<<12 byte boundaries.
   3035       uint64_t Anchor = Offset & ~uint64_t(0xfff);
   3036       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
   3037       Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
   3038 
   3039       // The offset can be folded into the address if it is aligned to a
   3040       // halfword.
   3041       Offset -= Anchor;
   3042       if (Offset != 0 && (Offset & 1) == 0) {
   3043         SDValue Full =
   3044           DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
   3045         Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
   3046         Offset = 0;
   3047       }
   3048     } else {
   3049       // Conservatively load a constant offset greater than 32 bits into a
   3050       // register below.
   3051       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
   3052       Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
   3053     }
   3054   } else {
   3055     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
   3056     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
   3057     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
   3058                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
   3059   }
   3060 
   3061   // If there was a non-zero offset that we didn't fold, create an explicit
   3062   // addition for it.
   3063   if (Offset != 0)
   3064     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
   3065                          DAG.getConstant(Offset, DL, PtrVT));
   3066 
   3067   return Result;
   3068 }
   3069 
   3070 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
   3071                                                  SelectionDAG &DAG,
   3072                                                  unsigned Opcode,
   3073                                                  SDValue GOTOffset) const {
   3074   SDLoc DL(Node);
   3075   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3076   SDValue Chain = DAG.getEntryNode();
   3077   SDValue Glue;
   3078 
   3079   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
   3080       CallingConv::GHC)
   3081     report_fatal_error("In GHC calling convention TLS is not supported");
   3082 
   3083   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
   3084   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
   3085   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
   3086   Glue = Chain.getValue(1);
   3087   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
   3088   Glue = Chain.getValue(1);
   3089 
   3090   // The first call operand is the chain and the second is the TLS symbol.
   3091   SmallVector<SDValue, 8> Ops;
   3092   Ops.push_back(Chain);
   3093   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
   3094                                            Node->getValueType(0),
   3095                                            0, 0));
   3096 
   3097   // Add argument registers to the end of the list so that they are
   3098   // known live into the call.
   3099   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
   3100   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
   3101 
   3102   // Add a register mask operand representing the call-preserved registers.
   3103   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
   3104   const uint32_t *Mask =
   3105       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
   3106   assert(Mask && "Missing call preserved mask for calling convention");
   3107   Ops.push_back(DAG.getRegisterMask(Mask));
   3108 
   3109   // Glue the call to the argument copies.
   3110   Ops.push_back(Glue);
   3111 
   3112   // Emit the call.
   3113   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   3114   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
   3115   Glue = Chain.getValue(1);
   3116 
   3117   // Copy the return value from %r2.
   3118   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
   3119 }
   3120 
   3121 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
   3122                                                   SelectionDAG &DAG) const {
   3123   SDValue Chain = DAG.getEntryNode();
   3124   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3125 
   3126   // The high part of the thread pointer is in access register 0.
   3127   SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
   3128   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
   3129 
   3130   // The low part of the thread pointer is in access register 1.
   3131   SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
   3132   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
   3133 
   3134   // Merge them into a single 64-bit address.
   3135   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
   3136                                     DAG.getConstant(32, DL, PtrVT));
   3137   return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
   3138 }
   3139 
   3140 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
   3141                                                      SelectionDAG &DAG) const {
   3142   if (DAG.getTarget().useEmulatedTLS())
   3143     return LowerToTLSEmulatedModel(Node, DAG);
   3144   SDLoc DL(Node);
   3145   const GlobalValue *GV = Node->getGlobal();
   3146   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3147   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
   3148 
   3149   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
   3150       CallingConv::GHC)
   3151     report_fatal_error("In GHC calling convention TLS is not supported");
   3152 
   3153   SDValue TP = lowerThreadPointer(DL, DAG);
   3154 
   3155   // Get the offset of GA from the thread pointer, based on the TLS model.
   3156   SDValue Offset;
   3157   switch (model) {
   3158     case TLSModel::GeneralDynamic: {
   3159       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
   3160       SystemZConstantPoolValue *CPV =
   3161         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
   3162 
   3163       Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
   3164       Offset = DAG.getLoad(
   3165           PtrVT, DL, DAG.getEntryNode(), Offset,
   3166           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
   3167 
   3168       // Call __tls_get_offset to retrieve the offset.
   3169       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
   3170       break;
   3171     }
   3172 
   3173     case TLSModel::LocalDynamic: {
   3174       // Load the GOT offset of the module ID.
   3175       SystemZConstantPoolValue *CPV =
   3176         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
   3177 
   3178       Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
   3179       Offset = DAG.getLoad(
   3180           PtrVT, DL, DAG.getEntryNode(), Offset,
   3181           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
   3182 
   3183       // Call __tls_get_offset to retrieve the module base offset.
   3184       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
   3185 
   3186       // Note: The SystemZLDCleanupPass will remove redundant computations
   3187       // of the module base offset.  Count total number of local-dynamic
   3188       // accesses to trigger execution of that pass.
   3189       SystemZMachineFunctionInfo* MFI =
   3190         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
   3191       MFI->incNumLocalDynamicTLSAccesses();
   3192 
   3193       // Add the per-symbol offset.
   3194       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
   3195 
   3196       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
   3197       DTPOffset = DAG.getLoad(
   3198           PtrVT, DL, DAG.getEntryNode(), DTPOffset,
   3199           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
   3200 
   3201       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
   3202       break;
   3203     }
   3204 
   3205     case TLSModel::InitialExec: {
   3206       // Load the offset from the GOT.
   3207       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
   3208                                           SystemZII::MO_INDNTPOFF);
   3209       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
   3210       Offset =
   3211           DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
   3212                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
   3213       break;
   3214     }
   3215 
   3216     case TLSModel::LocalExec: {
   3217       // Force the offset into the constant pool and load it from there.
   3218       SystemZConstantPoolValue *CPV =
   3219         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
   3220 
   3221       Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
   3222       Offset = DAG.getLoad(
   3223           PtrVT, DL, DAG.getEntryNode(), Offset,
   3224           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
   3225       break;
   3226     }
   3227   }
   3228 
   3229   // Add the base and offset together.
   3230   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
   3231 }
   3232 
   3233 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
   3234                                                  SelectionDAG &DAG) const {
   3235   SDLoc DL(Node);
   3236   const BlockAddress *BA = Node->getBlockAddress();
   3237   int64_t Offset = Node->getOffset();
   3238   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3239 
   3240   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
   3241   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
   3242   return Result;
   3243 }
   3244 
   3245 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
   3246                                               SelectionDAG &DAG) const {
   3247   SDLoc DL(JT);
   3248   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3249   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
   3250 
   3251   // Use LARL to load the address of the table.
   3252   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
   3253 }
   3254 
   3255 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
   3256                                                  SelectionDAG &DAG) const {
   3257   SDLoc DL(CP);
   3258   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3259 
   3260   SDValue Result;
   3261   if (CP->isMachineConstantPoolEntry())
   3262     Result =
   3263         DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
   3264   else
   3265     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
   3266                                        CP->getOffset());
   3267 
   3268   // Use LARL to load the address of the constant pool entry.
   3269   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
   3270 }
   3271 
   3272 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
   3273                                               SelectionDAG &DAG) const {
   3274   auto *TFL =
   3275       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
   3276   MachineFunction &MF = DAG.getMachineFunction();
   3277   MachineFrameInfo &MFI = MF.getFrameInfo();
   3278   MFI.setFrameAddressIsTaken(true);
   3279 
   3280   SDLoc DL(Op);
   3281   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   3282   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3283 
   3284   // By definition, the frame address is the address of the back chain.  (In
   3285   // the case of packed stack without backchain, return the address where the
   3286   // backchain would have been stored. This will either be an unused space or
   3287   // contain a saved register).
   3288   int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
   3289   SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
   3290 
   3291   // FIXME The frontend should detect this case.
   3292   if (Depth > 0) {
   3293     report_fatal_error("Unsupported stack frame traversal count");
   3294   }
   3295 
   3296   return BackChain;
   3297 }
   3298 
   3299 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
   3300                                                SelectionDAG &DAG) const {
   3301   MachineFunction &MF = DAG.getMachineFunction();
   3302   MachineFrameInfo &MFI = MF.getFrameInfo();
   3303   MFI.setReturnAddressIsTaken(true);
   3304 
   3305   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
   3306     return SDValue();
   3307 
   3308   SDLoc DL(Op);
   3309   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   3310   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3311 
   3312   // FIXME The frontend should detect this case.
   3313   if (Depth > 0) {
   3314     report_fatal_error("Unsupported stack frame traversal count");
   3315   }
   3316 
   3317   // Return R14D, which has the return address. Mark it an implicit live-in.
   3318   unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
   3319   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
   3320 }
   3321 
   3322 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
   3323                                             SelectionDAG &DAG) const {
   3324   SDLoc DL(Op);
   3325   SDValue In = Op.getOperand(0);
   3326   EVT InVT = In.getValueType();
   3327   EVT ResVT = Op.getValueType();
   3328 
   3329   // Convert loads directly.  This is normally done by DAGCombiner,
   3330   // but we need this case for bitcasts that are created during lowering
   3331   // and which are then lowered themselves.
   3332   if (auto *LoadN = dyn_cast<LoadSDNode>(In))
   3333     if (ISD::isNormalLoad(LoadN)) {
   3334       SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
   3335                                     LoadN->getBasePtr(), LoadN->getMemOperand());
   3336       // Update the chain uses.
   3337       DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
   3338       return NewLoad;
   3339     }
   3340 
   3341   if (InVT == MVT::i32 && ResVT == MVT::f32) {
   3342     SDValue In64;
   3343     if (Subtarget.hasHighWord()) {
   3344       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
   3345                                        MVT::i64);
   3346       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
   3347                                        MVT::i64, SDValue(U64, 0), In);
   3348     } else {
   3349       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
   3350       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
   3351                          DAG.getConstant(32, DL, MVT::i64));
   3352     }
   3353     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
   3354     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
   3355                                       DL, MVT::f32, Out64);
   3356   }
   3357   if (InVT == MVT::f32 && ResVT == MVT::i32) {
   3358     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
   3359     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
   3360                                              MVT::f64, SDValue(U64, 0), In);
   3361     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
   3362     if (Subtarget.hasHighWord())
   3363       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
   3364                                         MVT::i32, Out64);
   3365     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
   3366                                 DAG.getConstant(32, DL, MVT::i64));
   3367     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
   3368   }
   3369   llvm_unreachable("Unexpected bitcast combination");
   3370 }
   3371 
   3372 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
   3373                                             SelectionDAG &DAG) const {
   3374   MachineFunction &MF = DAG.getMachineFunction();
   3375   SystemZMachineFunctionInfo *FuncInfo =
   3376     MF.getInfo<SystemZMachineFunctionInfo>();
   3377   EVT PtrVT = getPointerTy(DAG.getDataLayout());
   3378 
   3379   SDValue Chain   = Op.getOperand(0);
   3380   SDValue Addr    = Op.getOperand(1);
   3381   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
   3382   SDLoc DL(Op);
   3383 
   3384   // The initial values of each field.
   3385   const unsigned NumFields = 4;
   3386   SDValue Fields[NumFields] = {
   3387     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
   3388     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
   3389     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
   3390     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
   3391   };
   3392 
   3393   // Store each field into its respective slot.
   3394   SDValue MemOps[NumFields];
   3395   unsigned Offset = 0;
   3396   for (unsigned I = 0; I < NumFields; ++I) {
   3397     SDValue FieldAddr = Addr;
   3398     if (Offset != 0)
   3399       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
   3400                               DAG.getIntPtrConstant(Offset, DL));
   3401     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
   3402                              MachinePointerInfo(SV, Offset));
   3403     Offset += 8;
   3404   }
   3405   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
   3406 }
   3407 
   3408 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
   3409                                            SelectionDAG &DAG) const {
   3410   SDValue Chain      = Op.getOperand(0);
   3411   SDValue DstPtr     = Op.getOperand(1);
   3412   SDValue SrcPtr     = Op.getOperand(2);
   3413   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
   3414   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
   3415   SDLoc DL(Op);
   3416 
   3417   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
   3418                        Align(8), /*isVolatile*/ false, /*AlwaysInline*/ false,
   3419                        /*isTailCall*/ false, MachinePointerInfo(DstSV),
   3420                        MachinePointerInfo(SrcSV));
   3421 }
   3422 
   3423 SDValue SystemZTargetLowering::
   3424 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
   3425   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
   3426   MachineFunction &MF = DAG.getMachineFunction();
   3427   bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
   3428   bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
   3429 
   3430   SDValue Chain = Op.getOperand(0);
   3431   SDValue Size  = Op.getOperand(1);
   3432   SDValue Align = Op.getOperand(2);
   3433   SDLoc DL(Op);
   3434 
   3435   // If user has set the no alignment function attribute, ignore
   3436   // alloca alignments.
   3437   uint64_t AlignVal =
   3438       (RealignOpt ? cast<ConstantSDNode>(Align)->getZExtValue() : 0);
   3439 
   3440   uint64_t StackAlign = TFI->getStackAlignment();
   3441   uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
   3442   uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
   3443 
   3444   Register SPReg = getStackPointerRegisterToSaveRestore();
   3445   SDValue NeededSpace = Size;
   3446 
   3447   // Get a reference to the stack pointer.
   3448   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
   3449 
   3450   // If we need a backchain, save it now.
   3451   SDValue Backchain;
   3452   if (StoreBackchain)
   3453     Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
   3454                             MachinePointerInfo());
   3455 
   3456   // Add extra space for alignment if needed.
   3457   if (ExtraAlignSpace)
   3458     NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
   3459                               DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
   3460 
   3461   // Get the new stack pointer value.
   3462   SDValue NewSP;
   3463   if (hasInlineStackProbe(MF)) {
   3464     NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
   3465                 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
   3466     Chain = NewSP.getValue(1);
   3467   }
   3468   else {
   3469     NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
   3470     // Copy the new stack pointer back.
   3471     Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
   3472   }
   3473 
   3474   // The allocated data lives above the 160 bytes allocated for the standard
   3475   // frame, plus any outgoing stack arguments.  We don't know how much that
   3476   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
   3477   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
   3478   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
   3479 
   3480   // Dynamically realign if needed.
   3481   if (RequiredAlign > StackAlign) {
   3482     Result =
   3483       DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
   3484                   DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
   3485     Result =
   3486       DAG.getNode(ISD::AND, DL, MVT::i64, Result,
   3487                   DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
   3488   }
   3489 
   3490   if (StoreBackchain)
   3491     Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
   3492                          MachinePointerInfo());
   3493 
   3494   SDValue Ops[2] = { Result, Chain };
   3495   return DAG.getMergeValues(Ops, DL);
   3496 }
   3497 
   3498 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
   3499     SDValue Op, SelectionDAG &DAG) const {
   3500   SDLoc DL(Op);
   3501 
   3502   return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
   3503 }
   3504 
   3505 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
   3506                                               SelectionDAG &DAG) const {
   3507   EVT VT = Op.getValueType();
   3508   SDLoc DL(Op);
   3509   SDValue Ops[2];
   3510   if (is32Bit(VT))
   3511     // Just do a normal 64-bit multiplication and extract the results.
   3512     // We define this so that it can be used for constant division.
   3513     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
   3514                     Op.getOperand(1), Ops[1], Ops[0]);
   3515   else if (Subtarget.hasMiscellaneousExtensions2())
   3516     // SystemZISD::SMUL_LOHI returns the low result in the odd register and
   3517     // the high result in the even register.  ISD::SMUL_LOHI is defined to
   3518     // return the low half first, so the results are in reverse order.
   3519     lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
   3520                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
   3521   else {
   3522     // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
   3523     //
   3524     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
   3525     //
   3526     // but using the fact that the upper halves are either all zeros
   3527     // or all ones:
   3528     //
   3529     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
   3530     //
   3531     // and grouping the right terms together since they are quicker than the
   3532     // multiplication:
   3533     //
   3534     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
   3535     SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
   3536     SDValue LL = Op.getOperand(0);
   3537     SDValue RL = Op.getOperand(1);
   3538     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
   3539     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
   3540     // SystemZISD::UMUL_LOHI returns the low result in the odd register and
   3541     // the high result in the even register.  ISD::SMUL_LOHI is defined to
   3542     // return the low half first, so the results are in reverse order.
   3543     lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
   3544                      LL, RL, Ops[1], Ops[0]);
   3545     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
   3546     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
   3547     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
   3548     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
   3549   }
   3550   return DAG.getMergeValues(Ops, DL);
   3551 }
   3552 
   3553 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
   3554                                               SelectionDAG &DAG) const {
   3555   EVT VT = Op.getValueType();
   3556   SDLoc DL(Op);
   3557   SDValue Ops[2];
   3558   if (is32Bit(VT))
   3559     // Just do a normal 64-bit multiplication and extract the results.
   3560     // We define this so that it can be used for constant division.
   3561     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
   3562                     Op.getOperand(1), Ops[1], Ops[0]);
   3563   else
   3564     // SystemZISD::UMUL_LOHI returns the low result in the odd register and
   3565     // the high result in the even register.  ISD::UMUL_LOHI is defined to
   3566     // return the low half first, so the results are in reverse order.
   3567     lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
   3568                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
   3569   return DAG.getMergeValues(Ops, DL);
   3570 }
   3571 
   3572 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
   3573                                             SelectionDAG &DAG) const {
   3574   SDValue Op0 = Op.getOperand(0);
   3575   SDValue Op1 = Op.getOperand(1);
   3576   EVT VT = Op.getValueType();
   3577   SDLoc DL(Op);
   3578 
   3579   // We use DSGF for 32-bit division.  This means the first operand must
   3580   // always be 64-bit, and the second operand should be 32-bit whenever
   3581   // that is possible, to improve performance.
   3582   if (is32Bit(VT))
   3583     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
   3584   else if (DAG.ComputeNumSignBits(Op1) > 32)
   3585     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
   3586 
   3587   // DSG(F) returns the remainder in the even register and the
   3588   // quotient in the odd register.
   3589   SDValue Ops[2];
   3590   lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
   3591   return DAG.getMergeValues(Ops, DL);
   3592 }
   3593 
   3594 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
   3595                                             SelectionDAG &DAG) const {
   3596   EVT VT = Op.getValueType();
   3597   SDLoc DL(Op);
   3598 
   3599   // DL(G) returns the remainder in the even register and the
   3600   // quotient in the odd register.
   3601   SDValue Ops[2];
   3602   lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
   3603                    Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
   3604   return DAG.getMergeValues(Ops, DL);
   3605 }
   3606 
   3607 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
   3608   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
   3609 
   3610   // Get the known-zero masks for each operand.
   3611   SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
   3612   KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
   3613                         DAG.computeKnownBits(Ops[1])};
   3614 
   3615   // See if the upper 32 bits of one operand and the lower 32 bits of the
   3616   // other are known zero.  They are the low and high operands respectively.
   3617   uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
   3618                        Known[1].Zero.getZExtValue() };
   3619   unsigned High, Low;
   3620   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
   3621     High = 1, Low = 0;
   3622   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
   3623     High = 0, Low = 1;
   3624   else
   3625     return Op;
   3626 
   3627   SDValue LowOp = Ops[Low];
   3628   SDValue HighOp = Ops[High];
   3629 
   3630   // If the high part is a constant, we're better off using IILH.
   3631   if (HighOp.getOpcode() == ISD::Constant)
   3632     return Op;
   3633 
   3634   // If the low part is a constant that is outside the range of LHI,
   3635   // then we're better off using IILF.
   3636   if (LowOp.getOpcode() == ISD::Constant) {
   3637     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
   3638     if (!isInt<16>(Value))
   3639       return Op;
   3640   }
   3641 
   3642   // Check whether the high part is an AND that doesn't change the
   3643   // high 32 bits and just masks out low bits.  We can skip it if so.
   3644   if (HighOp.getOpcode() == ISD::AND &&
   3645       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
   3646     SDValue HighOp0 = HighOp.getOperand(0);
   3647     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
   3648     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
   3649       HighOp = HighOp0;
   3650   }
   3651 
   3652   // Take advantage of the fact that all GR32 operations only change the
   3653   // low 32 bits by truncating Low to an i32 and inserting it directly
   3654   // using a subreg.  The interesting cases are those where the truncation
   3655   // can be folded.
   3656   SDLoc DL(Op);
   3657   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
   3658   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
   3659                                    MVT::i64, HighOp, Low32);
   3660 }
   3661 
   3662 // Lower SADDO/SSUBO/UADDO/USUBO nodes.
   3663 SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
   3664                                           SelectionDAG &DAG) const {
   3665   SDNode *N = Op.getNode();
   3666   SDValue LHS = N->getOperand(0);
   3667   SDValue RHS = N->getOperand(1);
   3668   SDLoc DL(N);
   3669   unsigned BaseOp = 0;
   3670   unsigned CCValid = 0;
   3671   unsigned CCMask = 0;
   3672 
   3673   switch (Op.getOpcode()) {
   3674   default: llvm_unreachable("Unknown instruction!");
   3675   case ISD::SADDO:
   3676     BaseOp = SystemZISD::SADDO;
   3677     CCValid = SystemZ::CCMASK_ARITH;
   3678     CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
   3679     break;
   3680   case ISD::SSUBO:
   3681     BaseOp = SystemZISD::SSUBO;
   3682     CCValid = SystemZ::CCMASK_ARITH;
   3683     CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
   3684     break;
   3685   case ISD::UADDO:
   3686     BaseOp = SystemZISD::UADDO;
   3687     CCValid = SystemZ::CCMASK_LOGICAL;
   3688     CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
   3689     break;
   3690   case ISD::USUBO:
   3691     BaseOp = SystemZISD::USUBO;
   3692     CCValid = SystemZ::CCMASK_LOGICAL;
   3693     CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
   3694     break;
   3695   }
   3696 
   3697   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
   3698   SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
   3699 
   3700   SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
   3701   if (N->getValueType(1) == MVT::i1)
   3702     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
   3703 
   3704   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
   3705 }
   3706 
   3707 static bool isAddCarryChain(SDValue Carry) {
   3708   while (Carry.getOpcode() == ISD::ADDCARRY)
   3709     Carry = Carry.getOperand(2);
   3710   return Carry.getOpcode() == ISD::UADDO;
   3711 }
   3712 
   3713 static bool isSubBorrowChain(SDValue Carry) {
   3714   while (Carry.getOpcode() == ISD::SUBCARRY)
   3715     Carry = Carry.getOperand(2);
   3716   return Carry.getOpcode() == ISD::USUBO;
   3717 }
   3718 
   3719 // Lower ADDCARRY/SUBCARRY nodes.
   3720 SDValue SystemZTargetLowering::lowerADDSUBCARRY(SDValue Op,
   3721                                                 SelectionDAG &DAG) const {
   3722 
   3723   SDNode *N = Op.getNode();
   3724   MVT VT = N->getSimpleValueType(0);
   3725 
   3726   // Let legalize expand this if it isn't a legal type yet.
   3727   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
   3728     return SDValue();
   3729 
   3730   SDValue LHS = N->getOperand(0);
   3731   SDValue RHS = N->getOperand(1);
   3732   SDValue Carry = Op.getOperand(2);
   3733   SDLoc DL(N);
   3734   unsigned BaseOp = 0;
   3735   unsigned CCValid = 0;
   3736   unsigned CCMask = 0;
   3737 
   3738   switch (Op.getOpcode()) {
   3739   default: llvm_unreachable("Unknown instruction!");
   3740   case ISD::ADDCARRY:
   3741     if (!isAddCarryChain(Carry))
   3742       return SDValue();
   3743 
   3744     BaseOp = SystemZISD::ADDCARRY;
   3745     CCValid = SystemZ::CCMASK_LOGICAL;
   3746     CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
   3747     break;
   3748   case ISD::SUBCARRY:
   3749     if (!isSubBorrowChain(Carry))
   3750       return SDValue();
   3751 
   3752     BaseOp = SystemZISD::SUBCARRY;
   3753     CCValid = SystemZ::CCMASK_LOGICAL;
   3754     CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
   3755     break;
   3756   }
   3757 
   3758   // Set the condition code from the carry flag.
   3759   Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
   3760                       DAG.getConstant(CCValid, DL, MVT::i32),
   3761                       DAG.getConstant(CCMask, DL, MVT::i32));
   3762 
   3763   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
   3764   SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
   3765 
   3766   SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
   3767   if (N->getValueType(1) == MVT::i1)
   3768     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
   3769 
   3770   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
   3771 }
   3772 
   3773 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
   3774                                           SelectionDAG &DAG) const {
   3775   EVT VT = Op.getValueType();
   3776   SDLoc DL(Op);
   3777   Op = Op.getOperand(0);
   3778 
   3779   // Handle vector types via VPOPCT.
   3780   if (VT.isVector()) {
   3781     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
   3782     Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
   3783     switch (VT.getScalarSizeInBits()) {
   3784     case 8:
   3785       break;
   3786     case 16: {
   3787       Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
   3788       SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
   3789       SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
   3790       Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
   3791       Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
   3792       break;
   3793     }
   3794     case 32: {
   3795       SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
   3796                                             DAG.getConstant(0, DL, MVT::i32));
   3797       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
   3798       break;
   3799     }
   3800     case 64: {
   3801       SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
   3802                                             DAG.getConstant(0, DL, MVT::i32));
   3803       Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
   3804       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
   3805       break;
   3806     }
   3807     default:
   3808       llvm_unreachable("Unexpected type");
   3809     }
   3810     return Op;
   3811   }
   3812 
   3813   // Get the known-zero mask for the operand.
   3814   KnownBits Known = DAG.computeKnownBits(Op);
   3815   unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
   3816   if (NumSignificantBits == 0)
   3817     return DAG.getConstant(0, DL, VT);
   3818 
   3819   // Skip known-zero high parts of the operand.
   3820   int64_t OrigBitSize = VT.getSizeInBits();
   3821   int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
   3822   BitSize = std::min(BitSize, OrigBitSize);
   3823 
   3824   // The POPCNT instruction counts the number of bits in each byte.
   3825   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
   3826   Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
   3827   Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
   3828 
   3829   // Add up per-byte counts in a binary tree.  All bits of Op at
   3830   // position larger than BitSize remain zero throughout.
   3831   for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
   3832     SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
   3833     if (BitSize != OrigBitSize)
   3834       Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
   3835                         DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
   3836     Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
   3837   }
   3838 
   3839   // Extract overall result from high byte.
   3840   if (BitSize > 8)
   3841     Op = DAG.getNode(ISD::SRL, DL, VT, Op,
   3842                      DAG.getConstant(BitSize - 8, DL, VT));
   3843 
   3844   return Op;
   3845 }
   3846 
   3847 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
   3848                                                  SelectionDAG &DAG) const {
   3849   SDLoc DL(Op);
   3850   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
   3851     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
   3852   SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
   3853     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
   3854 
   3855   // The only fence that needs an instruction is a sequentially-consistent
   3856   // cross-thread fence.
   3857   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
   3858       FenceSSID == SyncScope::System) {
   3859     return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
   3860                                       Op.getOperand(0)),
   3861                    0);
   3862   }
   3863 
   3864   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
   3865   return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
   3866 }
   3867 
   3868 // Op is an atomic load.  Lower it into a normal volatile load.
   3869 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
   3870                                                 SelectionDAG &DAG) const {
   3871   auto *Node = cast<AtomicSDNode>(Op.getNode());
   3872   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
   3873                         Node->getChain(), Node->getBasePtr(),
   3874                         Node->getMemoryVT(), Node->getMemOperand());
   3875 }
   3876 
   3877 // Op is an atomic store.  Lower it into a normal volatile store.
   3878 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
   3879                                                  SelectionDAG &DAG) const {
   3880   auto *Node = cast<AtomicSDNode>(Op.getNode());
   3881   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
   3882                                     Node->getBasePtr(), Node->getMemoryVT(),
   3883                                     Node->getMemOperand());
   3884   // We have to enforce sequential consistency by performing a
   3885   // serialization operation after the store.
   3886   if (Node->getOrdering() == AtomicOrdering::SequentiallyConsistent)
   3887     Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op),
   3888                                        MVT::Other, Chain), 0);
   3889   return Chain;
   3890 }
   3891 
   3892 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
   3893 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
   3894 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
   3895                                                    SelectionDAG &DAG,
   3896                                                    unsigned Opcode) const {
   3897   auto *Node = cast<AtomicSDNode>(Op.getNode());
   3898 
   3899   // 32-bit operations need no code outside the main loop.
   3900   EVT NarrowVT = Node->getMemoryVT();
   3901   EVT WideVT = MVT::i32;
   3902   if (NarrowVT == WideVT)
   3903     return Op;
   3904 
   3905   int64_t BitSize = NarrowVT.getSizeInBits();
   3906   SDValue ChainIn = Node->getChain();
   3907   SDValue Addr = Node->getBasePtr();
   3908   SDValue Src2 = Node->getVal();
   3909   MachineMemOperand *MMO = Node->getMemOperand();
   3910   SDLoc DL(Node);
   3911   EVT PtrVT = Addr.getValueType();
   3912 
   3913   // Convert atomic subtracts of constants into additions.
   3914   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
   3915     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
   3916       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
   3917       Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
   3918     }
   3919 
   3920   // Get the address of the containing word.
   3921   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
   3922                                     DAG.getConstant(-4, DL, PtrVT));
   3923 
   3924   // Get the number of bits that the word must be rotated left in order
   3925   // to bring the field to the top bits of a GR32.
   3926   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
   3927                                  DAG.getConstant(3, DL, PtrVT));
   3928   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
   3929 
   3930   // Get the complementing shift amount, for rotating a field in the top
   3931   // bits back to its proper position.
   3932   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
   3933                                     DAG.getConstant(0, DL, WideVT), BitShift);
   3934 
   3935   // Extend the source operand to 32 bits and prepare it for the inner loop.
   3936   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
   3937   // operations require the source to be shifted in advance.  (This shift
   3938   // can be folded if the source is constant.)  For AND and NAND, the lower
   3939   // bits must be set, while for other opcodes they should be left clear.
   3940   if (Opcode != SystemZISD::ATOMIC_SWAPW)
   3941     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
   3942                        DAG.getConstant(32 - BitSize, DL, WideVT));
   3943   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
   3944       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
   3945     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
   3946                        DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
   3947 
   3948   // Construct the ATOMIC_LOADW_* node.
   3949   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
   3950   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
   3951                     DAG.getConstant(BitSize, DL, WideVT) };
   3952   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
   3953                                              NarrowVT, MMO);
   3954 
   3955   // Rotate the result of the final CS so that the field is in the lower
   3956   // bits of a GR32, then truncate it.
   3957   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
   3958                                     DAG.getConstant(BitSize, DL, WideVT));
   3959   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
   3960 
   3961   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
   3962   return DAG.getMergeValues(RetOps, DL);
   3963 }
   3964 
   3965 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
   3966 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
   3967 // operations into additions.
   3968 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
   3969                                                     SelectionDAG &DAG) const {
   3970   auto *Node = cast<AtomicSDNode>(Op.getNode());
   3971   EVT MemVT = Node->getMemoryVT();
   3972   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
   3973     // A full-width operation.
   3974     assert(Op.getValueType() == MemVT && "Mismatched VTs");
   3975     SDValue Src2 = Node->getVal();
   3976     SDValue NegSrc2;
   3977     SDLoc DL(Src2);
   3978 
   3979     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
   3980       // Use an addition if the operand is constant and either LAA(G) is
   3981       // available or the negative value is in the range of A(G)FHI.
   3982       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
   3983       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
   3984         NegSrc2 = DAG.getConstant(Value, DL, MemVT);
   3985     } else if (Subtarget.hasInterlockedAccess1())
   3986       // Use LAA(G) if available.
   3987       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
   3988                             Src2);
   3989 
   3990     if (NegSrc2.getNode())
   3991       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
   3992                            Node->getChain(), Node->getBasePtr(), NegSrc2,
   3993                            Node->getMemOperand());
   3994 
   3995     // Use the node as-is.
   3996     return Op;
   3997   }
   3998 
   3999   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
   4000 }
   4001 
   4002 // Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
   4003 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
   4004                                                     SelectionDAG &DAG) const {
   4005   auto *Node = cast<AtomicSDNode>(Op.getNode());
   4006   SDValue ChainIn = Node->getOperand(0);
   4007   SDValue Addr = Node->getOperand(1);
   4008   SDValue CmpVal = Node->getOperand(2);
   4009   SDValue SwapVal = Node->getOperand(3);
   4010   MachineMemOperand *MMO = Node->getMemOperand();
   4011   SDLoc DL(Node);
   4012 
   4013   // We have native support for 32-bit and 64-bit compare and swap, but we
   4014   // still need to expand extracting the "success" result from the CC.
   4015   EVT NarrowVT = Node->getMemoryVT();
   4016   EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
   4017   if (NarrowVT == WideVT) {
   4018     SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
   4019     SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
   4020     SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
   4021                                                DL, Tys, Ops, NarrowVT, MMO);
   4022     SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
   4023                                 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
   4024 
   4025     DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
   4026     DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
   4027     DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
   4028     return SDValue();
   4029   }
   4030 
   4031   // Convert 8-bit and 16-bit compare and swap to a loop, implemented
   4032   // via a fullword ATOMIC_CMP_SWAPW operation.
   4033   int64_t BitSize = NarrowVT.getSizeInBits();
   4034   EVT PtrVT = Addr.getValueType();
   4035 
   4036   // Get the address of the containing word.
   4037   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
   4038                                     DAG.getConstant(-4, DL, PtrVT));
   4039 
   4040   // Get the number of bits that the word must be rotated left in order
   4041   // to bring the field to the top bits of a GR32.
   4042   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
   4043                                  DAG.getConstant(3, DL, PtrVT));
   4044   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
   4045 
   4046   // Get the complementing shift amount, for rotating a field in the top
   4047   // bits back to its proper position.
   4048   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
   4049                                     DAG.getConstant(0, DL, WideVT), BitShift);
   4050 
   4051   // Construct the ATOMIC_CMP_SWAPW node.
   4052   SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
   4053   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
   4054                     NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
   4055   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
   4056                                              VTList, Ops, NarrowVT, MMO);
   4057   SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
   4058                               SystemZ::CCMASK_ICMP, SystemZ::CCMASK_CMP_EQ);
   4059 
   4060   // emitAtomicCmpSwapW() will zero extend the result (original value).
   4061   SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
   4062                                 DAG.getValueType(NarrowVT));
   4063   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
   4064   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
   4065   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
   4066   return SDValue();
   4067 }
   4068 
   4069 MachineMemOperand::Flags
   4070 SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
   4071   // Because of how we convert atomic_load and atomic_store to normal loads and
   4072   // stores in the DAG, we need to ensure that the MMOs are marked volatile
   4073   // since DAGCombine hasn't been updated to account for atomic, but non
   4074   // volatile loads.  (See D57601)
   4075   if (auto *SI = dyn_cast<StoreInst>(&I))
   4076     if (SI->isAtomic())
   4077       return MachineMemOperand::MOVolatile;
   4078   if (auto *LI = dyn_cast<LoadInst>(&I))
   4079     if (LI->isAtomic())
   4080       return MachineMemOperand::MOVolatile;
   4081   if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
   4082     if (AI->isAtomic())
   4083       return MachineMemOperand::MOVolatile;
   4084   if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
   4085     if (AI->isAtomic())
   4086       return MachineMemOperand::MOVolatile;
   4087   return MachineMemOperand::MONone;
   4088 }
   4089 
   4090 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
   4091                                               SelectionDAG &DAG) const {
   4092   MachineFunction &MF = DAG.getMachineFunction();
   4093   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
   4094   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
   4095     report_fatal_error("Variable-sized stack allocations are not supported "
   4096                        "in GHC calling convention");
   4097   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
   4098                             SystemZ::R15D, Op.getValueType());
   4099 }
   4100 
   4101 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
   4102                                                  SelectionDAG &DAG) const {
   4103   MachineFunction &MF = DAG.getMachineFunction();
   4104   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
   4105   bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
   4106 
   4107   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
   4108     report_fatal_error("Variable-sized stack allocations are not supported "
   4109                        "in GHC calling convention");
   4110 
   4111   SDValue Chain = Op.getOperand(0);
   4112   SDValue NewSP = Op.getOperand(1);
   4113   SDValue Backchain;
   4114   SDLoc DL(Op);
   4115 
   4116   if (StoreBackchain) {
   4117     SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
   4118     Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
   4119                             MachinePointerInfo());
   4120   }
   4121 
   4122   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
   4123 
   4124   if (StoreBackchain)
   4125     Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
   4126                          MachinePointerInfo());
   4127 
   4128   return Chain;
   4129 }
   4130 
   4131 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
   4132                                              SelectionDAG &DAG) const {
   4133   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
   4134   if (!IsData)
   4135     // Just preserve the chain.
   4136     return Op.getOperand(0);
   4137 
   4138   SDLoc DL(Op);
   4139   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
   4140   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
   4141   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
   4142   SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
   4143                    Op.getOperand(1)};
   4144   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
   4145                                  Node->getVTList(), Ops,
   4146                                  Node->getMemoryVT(), Node->getMemOperand());
   4147 }
   4148 
   4149 // Convert condition code in CCReg to an i32 value.
   4150 static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg) {
   4151   SDLoc DL(CCReg);
   4152   SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
   4153   return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
   4154                      DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
   4155 }
   4156 
   4157 SDValue
   4158 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
   4159                                               SelectionDAG &DAG) const {
   4160   unsigned Opcode, CCValid;
   4161   if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
   4162     assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
   4163     SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
   4164     SDValue CC = getCCResult(DAG, SDValue(Node, 0));
   4165     DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
   4166     return SDValue();
   4167   }
   4168 
   4169   return SDValue();
   4170 }
   4171 
   4172 SDValue
   4173 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
   4174                                                SelectionDAG &DAG) const {
   4175   unsigned Opcode, CCValid;
   4176   if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
   4177     SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
   4178     if (Op->getNumValues() == 1)
   4179       return getCCResult(DAG, SDValue(Node, 0));
   4180     assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
   4181     return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
   4182                        SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
   4183   }
   4184 
   4185   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   4186   switch (Id) {
   4187   case Intrinsic::thread_pointer:
   4188     return lowerThreadPointer(SDLoc(Op), DAG);
   4189 
   4190   case Intrinsic::s390_vpdi:
   4191     return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
   4192                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
   4193 
   4194   case Intrinsic::s390_vperm:
   4195     return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
   4196                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
   4197 
   4198   case Intrinsic::s390_vuphb:
   4199   case Intrinsic::s390_vuphh:
   4200   case Intrinsic::s390_vuphf:
   4201     return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
   4202                        Op.getOperand(1));
   4203 
   4204   case Intrinsic::s390_vuplhb:
   4205   case Intrinsic::s390_vuplhh:
   4206   case Intrinsic::s390_vuplhf:
   4207     return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
   4208                        Op.getOperand(1));
   4209 
   4210   case Intrinsic::s390_vuplb:
   4211   case Intrinsic::s390_vuplhw:
   4212   case Intrinsic::s390_vuplf:
   4213     return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
   4214                        Op.getOperand(1));
   4215 
   4216   case Intrinsic::s390_vupllb:
   4217   case Intrinsic::s390_vupllh:
   4218   case Intrinsic::s390_vupllf:
   4219     return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
   4220                        Op.getOperand(1));
   4221 
   4222   case Intrinsic::s390_vsumb:
   4223   case Intrinsic::s390_vsumh:
   4224   case Intrinsic::s390_vsumgh:
   4225   case Intrinsic::s390_vsumgf:
   4226   case Intrinsic::s390_vsumqf:
   4227   case Intrinsic::s390_vsumqg:
   4228     return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
   4229                        Op.getOperand(1), Op.getOperand(2));
   4230   }
   4231 
   4232   return SDValue();
   4233 }
   4234 
   4235 namespace {
   4236 // Says that SystemZISD operation Opcode can be used to perform the equivalent
   4237 // of a VPERM with permute vector Bytes.  If Opcode takes three operands,
   4238 // Operand is the constant third operand, otherwise it is the number of
   4239 // bytes in each element of the result.
   4240 struct Permute {
   4241   unsigned Opcode;
   4242   unsigned Operand;
   4243   unsigned char Bytes[SystemZ::VectorBytes];
   4244 };
   4245 }
   4246 
   4247 static const Permute PermuteForms[] = {
   4248   // VMRHG
   4249   { SystemZISD::MERGE_HIGH, 8,
   4250     { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
   4251   // VMRHF
   4252   { SystemZISD::MERGE_HIGH, 4,
   4253     { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
   4254   // VMRHH
   4255   { SystemZISD::MERGE_HIGH, 2,
   4256     { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
   4257   // VMRHB
   4258   { SystemZISD::MERGE_HIGH, 1,
   4259     { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
   4260   // VMRLG
   4261   { SystemZISD::MERGE_LOW, 8,
   4262     { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
   4263   // VMRLF
   4264   { SystemZISD::MERGE_LOW, 4,
   4265     { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
   4266   // VMRLH
   4267   { SystemZISD::MERGE_LOW, 2,
   4268     { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
   4269   // VMRLB
   4270   { SystemZISD::MERGE_LOW, 1,
   4271     { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
   4272   // VPKG
   4273   { SystemZISD::PACK, 4,
   4274     { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
   4275   // VPKF
   4276   { SystemZISD::PACK, 2,
   4277     { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
   4278   // VPKH
   4279   { SystemZISD::PACK, 1,
   4280     { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
   4281   // VPDI V1, V2, 4  (low half of V1, high half of V2)
   4282   { SystemZISD::PERMUTE_DWORDS, 4,
   4283     { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
   4284   // VPDI V1, V2, 1  (high half of V1, low half of V2)
   4285   { SystemZISD::PERMUTE_DWORDS, 1,
   4286     { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
   4287 };
   4288 
   4289 // Called after matching a vector shuffle against a particular pattern.
   4290 // Both the original shuffle and the pattern have two vector operands.
   4291 // OpNos[0] is the operand of the original shuffle that should be used for
   4292 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
   4293 // OpNos[1] is the same for operand 1 of the pattern.  Resolve these -1s and
   4294 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
   4295 // for operands 0 and 1 of the pattern.
   4296 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
   4297   if (OpNos[0] < 0) {
   4298     if (OpNos[1] < 0)
   4299       return false;
   4300     OpNo0 = OpNo1 = OpNos[1];
   4301   } else if (OpNos[1] < 0) {
   4302     OpNo0 = OpNo1 = OpNos[0];
   4303   } else {
   4304     OpNo0 = OpNos[0];
   4305     OpNo1 = OpNos[1];
   4306   }
   4307   return true;
   4308 }
   4309 
   4310 // Bytes is a VPERM-like permute vector, except that -1 is used for
   4311 // undefined bytes.  Return true if the VPERM can be implemented using P.
   4312 // When returning true set OpNo0 to the VPERM operand that should be
   4313 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
   4314 //
   4315 // For example, if swapping the VPERM operands allows P to match, OpNo0
   4316 // will be 1 and OpNo1 will be 0.  If instead Bytes only refers to one
   4317 // operand, but rewriting it to use two duplicated operands allows it to
   4318 // match P, then OpNo0 and OpNo1 will be the same.
   4319 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
   4320                          unsigned &OpNo0, unsigned &OpNo1) {
   4321   int OpNos[] = { -1, -1 };
   4322   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
   4323     int Elt = Bytes[I];
   4324     if (Elt >= 0) {
   4325       // Make sure that the two permute vectors use the same suboperand
   4326       // byte number.  Only the operand numbers (the high bits) are
   4327       // allowed to differ.
   4328       if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
   4329         return false;
   4330       int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
   4331       int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
   4332       // Make sure that the operand mappings are consistent with previous
   4333       // elements.
   4334       if (OpNos[ModelOpNo] == 1 - RealOpNo)
   4335         return false;
   4336       OpNos[ModelOpNo] = RealOpNo;
   4337     }
   4338   }
   4339   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
   4340 }
   4341 
   4342 // As above, but search for a matching permute.
   4343 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
   4344                                    unsigned &OpNo0, unsigned &OpNo1) {
   4345   for (auto &P : PermuteForms)
   4346     if (matchPermute(Bytes, P, OpNo0, OpNo1))
   4347       return &P;
   4348   return nullptr;
   4349 }
   4350 
   4351 // Bytes is a VPERM-like permute vector, except that -1 is used for
   4352 // undefined bytes.  This permute is an operand of an outer permute.
   4353 // See whether redistributing the -1 bytes gives a shuffle that can be
   4354 // implemented using P.  If so, set Transform to a VPERM-like permute vector
   4355 // that, when applied to the result of P, gives the original permute in Bytes.
   4356 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
   4357                                const Permute &P,
   4358                                SmallVectorImpl<int> &Transform) {
   4359   unsigned To = 0;
   4360   for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
   4361     int Elt = Bytes[From];
   4362     if (Elt < 0)
   4363       // Byte number From of the result is undefined.
   4364       Transform[From] = -1;
   4365     else {
   4366       while (P.Bytes[To] != Elt) {
   4367         To += 1;
   4368         if (To == SystemZ::VectorBytes)
   4369           return false;
   4370       }
   4371       Transform[From] = To;
   4372     }
   4373   }
   4374   return true;
   4375 }
   4376 
   4377 // As above, but search for a matching permute.
   4378 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
   4379                                          SmallVectorImpl<int> &Transform) {
   4380   for (auto &P : PermuteForms)
   4381     if (matchDoublePermute(Bytes, P, Transform))
   4382       return &P;
   4383   return nullptr;
   4384 }
   4385 
   4386 // Convert the mask of the given shuffle op into a byte-level mask,
   4387 // as if it had type vNi8.
   4388 static bool getVPermMask(SDValue ShuffleOp,
   4389                          SmallVectorImpl<int> &Bytes) {
   4390   EVT VT = ShuffleOp.getValueType();
   4391   unsigned NumElements = VT.getVectorNumElements();
   4392   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
   4393 
   4394   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
   4395     Bytes.resize(NumElements * BytesPerElement, -1);
   4396     for (unsigned I = 0; I < NumElements; ++I) {
   4397       int Index = VSN->getMaskElt(I);
   4398       if (Index >= 0)
   4399         for (unsigned J = 0; J < BytesPerElement; ++J)
   4400           Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
   4401     }
   4402     return true;
   4403   }
   4404   if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
   4405       isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
   4406     unsigned Index = ShuffleOp.getConstantOperandVal(1);
   4407     Bytes.resize(NumElements * BytesPerElement, -1);
   4408     for (unsigned I = 0; I < NumElements; ++I)
   4409       for (unsigned J = 0; J < BytesPerElement; ++J)
   4410         Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
   4411     return true;
   4412   }
   4413   return false;
   4414 }
   4415 
   4416 // Bytes is a VPERM-like permute vector, except that -1 is used for
   4417 // undefined bytes.  See whether bytes [Start, Start + BytesPerElement) of
   4418 // the result come from a contiguous sequence of bytes from one input.
   4419 // Set Base to the selector for the first byte if so.
   4420 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
   4421                             unsigned BytesPerElement, int &Base) {
   4422   Base = -1;
   4423   for (unsigned I = 0; I < BytesPerElement; ++I) {
   4424     if (Bytes[Start + I] >= 0) {
   4425       unsigned Elem = Bytes[Start + I];
   4426       if (Base < 0) {
   4427         Base = Elem - I;
   4428         // Make sure the bytes would come from one input operand.
   4429         if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
   4430           return false;
   4431       } else if (unsigned(Base) != Elem - I)
   4432         return false;
   4433     }
   4434   }
   4435   return true;
   4436 }
   4437 
   4438 // Bytes is a VPERM-like permute vector, except that -1 is used for
   4439 // undefined bytes.  Return true if it can be performed using VSLDB.
   4440 // When returning true, set StartIndex to the shift amount and OpNo0
   4441 // and OpNo1 to the VPERM operands that should be used as the first
   4442 // and second shift operand respectively.
   4443 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
   4444                                unsigned &StartIndex, unsigned &OpNo0,
   4445                                unsigned &OpNo1) {
   4446   int OpNos[] = { -1, -1 };
   4447   int Shift = -1;
   4448   for (unsigned I = 0; I < 16; ++I) {
   4449     int Index = Bytes[I];
   4450     if (Index >= 0) {
   4451       int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
   4452       int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
   4453       int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
   4454       if (Shift < 0)
   4455         Shift = ExpectedShift;
   4456       else if (Shift != ExpectedShift)
   4457         return false;
   4458       // Make sure that the operand mappings are consistent with previous
   4459       // elements.
   4460       if (OpNos[ModelOpNo] == 1 - RealOpNo)
   4461         return false;
   4462       OpNos[ModelOpNo] = RealOpNo;
   4463     }
   4464   }
   4465   StartIndex = Shift;
   4466   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
   4467 }
   4468 
   4469 // Create a node that performs P on operands Op0 and Op1, casting the
   4470 // operands to the appropriate type.  The type of the result is determined by P.
   4471 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
   4472                               const Permute &P, SDValue Op0, SDValue Op1) {
   4473   // VPDI (PERMUTE_DWORDS) always operates on v2i64s.  The input
   4474   // elements of a PACK are twice as wide as the outputs.
   4475   unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
   4476                       P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
   4477                       P.Operand);
   4478   // Cast both operands to the appropriate type.
   4479   MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
   4480                               SystemZ::VectorBytes / InBytes);
   4481   Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
   4482   Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
   4483   SDValue Op;
   4484   if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
   4485     SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
   4486     Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
   4487   } else if (P.Opcode == SystemZISD::PACK) {
   4488     MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
   4489                                  SystemZ::VectorBytes / P.Operand);
   4490     Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
   4491   } else {
   4492     Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
   4493   }
   4494   return Op;
   4495 }
   4496 
   4497 static bool isZeroVector(SDValue N) {
   4498   if (N->getOpcode() == ISD::BITCAST)
   4499     N = N->getOperand(0);
   4500   if (N->getOpcode() == ISD::SPLAT_VECTOR)
   4501     if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
   4502       return Op->getZExtValue() == 0;
   4503   return ISD::isBuildVectorAllZeros(N.getNode());
   4504 }
   4505 
   4506 // Return the index of the zero/undef vector, or UINT32_MAX if not found.
   4507 static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
   4508   for (unsigned I = 0; I < Num ; I++)
   4509     if (isZeroVector(Ops[I]))
   4510       return I;
   4511   return UINT32_MAX;
   4512 }
   4513 
   4514 // Bytes is a VPERM-like permute vector, except that -1 is used for
   4515 // undefined bytes.  Implement it on operands Ops[0] and Ops[1] using
   4516 // VSLDB or VPERM.
   4517 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
   4518                                      SDValue *Ops,
   4519                                      const SmallVectorImpl<int> &Bytes) {
   4520   for (unsigned I = 0; I < 2; ++I)
   4521     Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
   4522 
   4523   // First see whether VSLDB can be used.
   4524   unsigned StartIndex, OpNo0, OpNo1;
   4525   if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
   4526     return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
   4527                        Ops[OpNo1],
   4528                        DAG.getTargetConstant(StartIndex, DL, MVT::i32));
   4529 
   4530   // Fall back on VPERM.  Construct an SDNode for the permute vector.  Try to
   4531   // eliminate a zero vector by reusing any zero index in the permute vector.
   4532   unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
   4533   if (ZeroVecIdx != UINT32_MAX) {
   4534     bool MaskFirst = true;
   4535     int ZeroIdx = -1;
   4536     for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
   4537       unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
   4538       unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
   4539       if (OpNo == ZeroVecIdx && I == 0) {
   4540         // If the first byte is zero, use mask as first operand.
   4541         ZeroIdx = 0;
   4542         break;
   4543       }
   4544       if (OpNo != ZeroVecIdx && Byte == 0) {
   4545         // If mask contains a zero, use it by placing that vector first.
   4546         ZeroIdx = I + SystemZ::VectorBytes;
   4547         MaskFirst = false;
   4548         break;
   4549       }
   4550     }
   4551     if (ZeroIdx != -1) {
   4552       SDValue IndexNodes[SystemZ::VectorBytes];
   4553       for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
   4554         if (Bytes[I] >= 0) {
   4555           unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
   4556           unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
   4557           if (OpNo == ZeroVecIdx)
   4558             IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
   4559           else {
   4560             unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
   4561             IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
   4562           }
   4563         } else
   4564           IndexNodes[I] = DAG.getUNDEF(MVT::i32);
   4565       }
   4566       SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
   4567       SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
   4568       if (MaskFirst)
   4569         return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
   4570                            Mask);
   4571       else
   4572         return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
   4573                            Mask);
   4574     }
   4575   }
   4576 
   4577   SDValue IndexNodes[SystemZ::VectorBytes];
   4578   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
   4579     if (Bytes[I] >= 0)
   4580       IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
   4581     else
   4582       IndexNodes[I] = DAG.getUNDEF(MVT::i32);
   4583   SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
   4584   return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
   4585                      (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
   4586 }
   4587 
   4588 namespace {
   4589 // Describes a general N-operand vector shuffle.
   4590 struct GeneralShuffle {
   4591   GeneralShuffle(EVT vt) : VT(vt), UnpackFromEltSize(UINT_MAX) {}
   4592   void addUndef();
   4593   bool add(SDValue, unsigned);
   4594   SDValue getNode(SelectionDAG &, const SDLoc &);
   4595   void tryPrepareForUnpack();
   4596   bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
   4597   SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
   4598 
   4599   // The operands of the shuffle.
   4600   SmallVector<SDValue, SystemZ::VectorBytes> Ops;
   4601 
   4602   // Index I is -1 if byte I of the result is undefined.  Otherwise the
   4603   // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
   4604   // Bytes[I] / SystemZ::VectorBytes.
   4605   SmallVector<int, SystemZ::VectorBytes> Bytes;
   4606 
   4607   // The type of the shuffle result.
   4608   EVT VT;
   4609 
   4610   // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
   4611   unsigned UnpackFromEltSize;
   4612 };
   4613 }
   4614 
   4615 // Add an extra undefined element to the shuffle.
   4616 void GeneralShuffle::addUndef() {
   4617   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
   4618   for (unsigned I = 0; I < BytesPerElement; ++I)
   4619     Bytes.push_back(-1);
   4620 }
   4621 
   4622 // Add an extra element to the shuffle, taking it from element Elem of Op.
   4623 // A null Op indicates a vector input whose value will be calculated later;
   4624 // there is at most one such input per shuffle and it always has the same
   4625 // type as the result. Aborts and returns false if the source vector elements
   4626 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
   4627 // LLVM they become implicitly extended, but this is rare and not optimized.
   4628 bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
   4629   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
   4630 
   4631   // The source vector can have wider elements than the result,
   4632   // either through an explicit TRUNCATE or because of type legalization.
   4633   // We want the least significant part.
   4634   EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
   4635   unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
   4636 
   4637   // Return false if the source elements are smaller than their destination
   4638   // elements.
   4639   if (FromBytesPerElement < BytesPerElement)
   4640     return false;
   4641 
   4642   unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
   4643                    (FromBytesPerElement - BytesPerElement));
   4644 
   4645   // Look through things like shuffles and bitcasts.
   4646   while (Op.getNode()) {
   4647     if (Op.getOpcode() == ISD::BITCAST)
   4648       Op = Op.getOperand(0);
   4649     else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
   4650       // See whether the bytes we need come from a contiguous part of one
   4651       // operand.
   4652       SmallVector<int, SystemZ::VectorBytes> OpBytes;
   4653       if (!getVPermMask(Op, OpBytes))
   4654         break;
   4655       int NewByte;
   4656       if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
   4657         break;
   4658       if (NewByte < 0) {
   4659         addUndef();
   4660         return true;
   4661       }
   4662       Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
   4663       Byte = unsigned(NewByte) % SystemZ::VectorBytes;
   4664     } else if (Op.isUndef()) {
   4665       addUndef();
   4666       return true;
   4667     } else
   4668       break;
   4669   }
   4670 
   4671   // Make sure that the source of the extraction is in Ops.
   4672   unsigned OpNo = 0;
   4673   for (; OpNo < Ops.size(); ++OpNo)
   4674     if (Ops[OpNo] == Op)
   4675       break;
   4676   if (OpNo == Ops.size())
   4677     Ops.push_back(Op);
   4678 
   4679   // Add the element to Bytes.
   4680   unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
   4681   for (unsigned I = 0; I < BytesPerElement; ++I)
   4682     Bytes.push_back(Base + I);
   4683 
   4684   return true;
   4685 }
   4686 
   4687 // Return SDNodes for the completed shuffle.
   4688 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
   4689   assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
   4690 
   4691   if (Ops.size() == 0)
   4692     return DAG.getUNDEF(VT);
   4693 
   4694   // Use a single unpack if possible as the last operation.
   4695   tryPrepareForUnpack();
   4696 
   4697   // Make sure that there are at least two shuffle operands.
   4698   if (Ops.size() == 1)
   4699     Ops.push_back(DAG.getUNDEF(MVT::v16i8));
   4700 
   4701   // Create a tree of shuffles, deferring root node until after the loop.
   4702   // Try to redistribute the undefined elements of non-root nodes so that
   4703   // the non-root shuffles match something like a pack or merge, then adjust
   4704   // the parent node's permute vector to compensate for the new order.
   4705   // Among other things, this copes with vectors like <2 x i16> that were
   4706   // padded with undefined elements during type legalization.
   4707   //
   4708   // In the best case this redistribution will lead to the whole tree
   4709   // using packs and merges.  It should rarely be a loss in other cases.
   4710   unsigned Stride = 1;
   4711   for (; Stride * 2 < Ops.size(); Stride *= 2) {
   4712     for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
   4713       SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
   4714 
   4715       // Create a mask for just these two operands.
   4716       SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
   4717       for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
   4718         unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
   4719         unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
   4720         if (OpNo == I)
   4721           NewBytes[J] = Byte;
   4722         else if (OpNo == I + Stride)
   4723           NewBytes[J] = SystemZ::VectorBytes + Byte;
   4724         else
   4725           NewBytes[J] = -1;
   4726       }
   4727       // See if it would be better to reorganize NewMask to avoid using VPERM.
   4728       SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
   4729       if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
   4730         Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
   4731         // Applying NewBytesMap to Ops[I] gets back to NewBytes.
   4732         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
   4733           if (NewBytes[J] >= 0) {
   4734             assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
   4735                    "Invalid double permute");
   4736             Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
   4737           } else
   4738             assert(NewBytesMap[J] < 0 && "Invalid double permute");
   4739         }
   4740       } else {
   4741         // Just use NewBytes on the operands.
   4742         Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
   4743         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
   4744           if (NewBytes[J] >= 0)
   4745             Bytes[J] = I * SystemZ::VectorBytes + J;
   4746       }
   4747     }
   4748   }
   4749 
   4750   // Now we just have 2 inputs.  Put the second operand in Ops[1].
   4751   if (Stride > 1) {
   4752     Ops[1] = Ops[Stride];
   4753     for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
   4754       if (Bytes[I] >= int(SystemZ::VectorBytes))
   4755         Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
   4756   }
   4757 
   4758   // Look for an instruction that can do the permute without resorting
   4759   // to VPERM.
   4760   unsigned OpNo0, OpNo1;
   4761   SDValue Op;
   4762   if (unpackWasPrepared() && Ops[1].isUndef())
   4763     Op = Ops[0];
   4764   else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
   4765     Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
   4766   else
   4767     Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
   4768 
   4769   Op = insertUnpackIfPrepared(DAG, DL, Op);
   4770 
   4771   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
   4772 }
   4773 
   4774 #ifndef NDEBUG
   4775 static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
   4776   dbgs() << Msg.c_str() << " { ";
   4777   for (unsigned i = 0; i < Bytes.size(); i++)
   4778     dbgs() << Bytes[i] << " ";
   4779   dbgs() << "}\n";
   4780 }
   4781 #endif
   4782 
   4783 // If the Bytes vector matches an unpack operation, prepare to do the unpack
   4784 // after all else by removing the zero vector and the effect of the unpack on
   4785 // Bytes.
   4786 void GeneralShuffle::tryPrepareForUnpack() {
   4787   uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
   4788   if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
   4789     return;
   4790 
   4791   // Only do this if removing the zero vector reduces the depth, otherwise
   4792   // the critical path will increase with the final unpack.
   4793   if (Ops.size() > 2 &&
   4794       Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
   4795     return;
   4796 
   4797   // Find an unpack that would allow removing the zero vector from Ops.
   4798   UnpackFromEltSize = 1;
   4799   for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
   4800     bool MatchUnpack = true;
   4801     SmallVector<int, SystemZ::VectorBytes> SrcBytes;
   4802     for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
   4803       unsigned ToEltSize = UnpackFromEltSize * 2;
   4804       bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
   4805       if (!IsZextByte)
   4806         SrcBytes.push_back(Bytes[Elt]);
   4807       if (Bytes[Elt] != -1) {
   4808         unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
   4809         if (IsZextByte != (OpNo == ZeroVecOpNo)) {
   4810           MatchUnpack = false;
   4811           break;
   4812         }
   4813       }
   4814     }
   4815     if (MatchUnpack) {
   4816       if (Ops.size() == 2) {
   4817         // Don't use unpack if a single source operand needs rearrangement.
   4818         for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++)
   4819           if (SrcBytes[i] != -1 && SrcBytes[i] % 16 != int(i)) {
   4820             UnpackFromEltSize = UINT_MAX;
   4821             return;
   4822           }
   4823       }
   4824       break;
   4825     }
   4826   }
   4827   if (UnpackFromEltSize > 4)
   4828     return;
   4829 
   4830   LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
   4831              << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
   4832              << ".\n";
   4833              dumpBytes(Bytes, "Original Bytes vector:"););
   4834 
   4835   // Apply the unpack in reverse to the Bytes array.
   4836   unsigned B = 0;
   4837   for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
   4838     Elt += UnpackFromEltSize;
   4839     for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
   4840       Bytes[B] = Bytes[Elt];
   4841   }
   4842   while (B < SystemZ::VectorBytes)
   4843     Bytes[B++] = -1;
   4844 
   4845   // Remove the zero vector from Ops
   4846   Ops.erase(&Ops[ZeroVecOpNo]);
   4847   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
   4848     if (Bytes[I] >= 0) {
   4849       unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
   4850       if (OpNo > ZeroVecOpNo)
   4851         Bytes[I] -= SystemZ::VectorBytes;
   4852     }
   4853 
   4854   LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
   4855              dbgs() << "\n";);
   4856 }
   4857 
   4858 SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
   4859                                                const SDLoc &DL,
   4860                                                SDValue Op) {
   4861   if (!unpackWasPrepared())
   4862     return Op;
   4863   unsigned InBits = UnpackFromEltSize * 8;
   4864   EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
   4865                                 SystemZ::VectorBits / InBits);
   4866   SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
   4867   unsigned OutBits = InBits * 2;
   4868   EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
   4869                                SystemZ::VectorBits / OutBits);
   4870   return DAG.getNode(SystemZISD::UNPACKL_HIGH, DL, OutVT, PackedOp);
   4871 }
   4872 
   4873 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
   4874 static bool isScalarToVector(SDValue Op) {
   4875   for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
   4876     if (!Op.getOperand(I).isUndef())
   4877       return false;
   4878   return true;
   4879 }
   4880 
   4881 // Return a vector of type VT that contains Value in the first element.
   4882 // The other elements don't matter.
   4883 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
   4884                                    SDValue Value) {
   4885   // If we have a constant, replicate it to all elements and let the
   4886   // BUILD_VECTOR lowering take care of it.
   4887   if (Value.getOpcode() == ISD::Constant ||
   4888       Value.getOpcode() == ISD::ConstantFP) {
   4889     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
   4890     return DAG.getBuildVector(VT, DL, Ops);
   4891   }
   4892   if (Value.isUndef())
   4893     return DAG.getUNDEF(VT);
   4894   return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
   4895 }
   4896 
   4897 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
   4898 // element 1.  Used for cases in which replication is cheap.
   4899 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
   4900                                  SDValue Op0, SDValue Op1) {
   4901   if (Op0.isUndef()) {
   4902     if (Op1.isUndef())
   4903       return DAG.getUNDEF(VT);
   4904     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
   4905   }
   4906   if (Op1.isUndef())
   4907     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
   4908   return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
   4909                      buildScalarToVector(DAG, DL, VT, Op0),
   4910                      buildScalarToVector(DAG, DL, VT, Op1));
   4911 }
   4912 
   4913 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
   4914 // vector for them.
   4915 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
   4916                           SDValue Op1) {
   4917   if (Op0.isUndef() && Op1.isUndef())
   4918     return DAG.getUNDEF(MVT::v2i64);
   4919   // If one of the two inputs is undefined then replicate the other one,
   4920   // in order to avoid using another register unnecessarily.
   4921   if (Op0.isUndef())
   4922     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
   4923   else if (Op1.isUndef())
   4924     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
   4925   else {
   4926     Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
   4927     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
   4928   }
   4929   return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
   4930 }
   4931 
   4932 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
   4933 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
   4934 // the non-EXTRACT_VECTOR_ELT elements.  See if the given BUILD_VECTOR
   4935 // would benefit from this representation and return it if so.
   4936 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
   4937                                      BuildVectorSDNode *BVN) {
   4938   EVT VT = BVN->getValueType(0);
   4939   unsigned NumElements = VT.getVectorNumElements();
   4940 
   4941   // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
   4942   // on byte vectors.  If there are non-EXTRACT_VECTOR_ELT elements that still
   4943   // need a BUILD_VECTOR, add an additional placeholder operand for that
   4944   // BUILD_VECTOR and store its operands in ResidueOps.
   4945   GeneralShuffle GS(VT);
   4946   SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
   4947   bool FoundOne = false;
   4948   for (unsigned I = 0; I < NumElements; ++I) {
   4949     SDValue Op = BVN->getOperand(I);
   4950     if (Op.getOpcode() == ISD::TRUNCATE)
   4951       Op = Op.getOperand(0);
   4952     if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   4953         Op.getOperand(1).getOpcode() == ISD::Constant) {
   4954       unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   4955       if (!GS.add(Op.getOperand(0), Elem))
   4956         return SDValue();
   4957       FoundOne = true;
   4958     } else if (Op.isUndef()) {
   4959       GS.addUndef();
   4960     } else {
   4961       if (!GS.add(SDValue(), ResidueOps.size()))
   4962         return SDValue();
   4963       ResidueOps.push_back(BVN->getOperand(I));
   4964     }
   4965   }
   4966 
   4967   // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
   4968   if (!FoundOne)
   4969     return SDValue();
   4970 
   4971   // Create the BUILD_VECTOR for the remaining elements, if any.
   4972   if (!ResidueOps.empty()) {
   4973     while (ResidueOps.size() < NumElements)
   4974       ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
   4975     for (auto &Op : GS.Ops) {
   4976       if (!Op.getNode()) {
   4977         Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
   4978         break;
   4979       }
   4980     }
   4981   }
   4982   return GS.getNode(DAG, SDLoc(BVN));
   4983 }
   4984 
   4985 bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
   4986   if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
   4987     return true;
   4988   if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
   4989     return true;
   4990   return false;
   4991 }
   4992 
   4993 // Combine GPR scalar values Elems into a vector of type VT.
   4994 SDValue
   4995 SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
   4996                                    SmallVectorImpl<SDValue> &Elems) const {
   4997   // See whether there is a single replicated value.
   4998   SDValue Single;
   4999   unsigned int NumElements = Elems.size();
   5000   unsigned int Count = 0;
   5001   for (auto Elem : Elems) {
   5002     if (!Elem.isUndef()) {
   5003       if (!Single.getNode())
   5004         Single = Elem;
   5005       else if (Elem != Single) {
   5006         Single = SDValue();
   5007         break;
   5008       }
   5009       Count += 1;
   5010     }
   5011   }
   5012   // There are three cases here:
   5013   //
   5014   // - if the only defined element is a loaded one, the best sequence
   5015   //   is a replicating load.
   5016   //
   5017   // - otherwise, if the only defined element is an i64 value, we will
   5018   //   end up with the same VLVGP sequence regardless of whether we short-cut
   5019   //   for replication or fall through to the later code.
   5020   //
   5021   // - otherwise, if the only defined element is an i32 or smaller value,
   5022   //   we would need 2 instructions to replicate it: VLVGP followed by VREPx.
   5023   //   This is only a win if the single defined element is used more than once.
   5024   //   In other cases we're better off using a single VLVGx.
   5025   if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
   5026     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
   5027 
   5028   // If all elements are loads, use VLREP/VLEs (below).
   5029   bool AllLoads = true;
   5030   for (auto Elem : Elems)
   5031     if (!isVectorElementLoad(Elem)) {
   5032       AllLoads = false;
   5033       break;
   5034     }
   5035 
   5036   // The best way of building a v2i64 from two i64s is to use VLVGP.
   5037   if (VT == MVT::v2i64 && !AllLoads)
   5038     return joinDwords(DAG, DL, Elems[0], Elems[1]);
   5039 
   5040   // Use a 64-bit merge high to combine two doubles.
   5041   if (VT == MVT::v2f64 && !AllLoads)
   5042     return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
   5043 
   5044   // Build v4f32 values directly from the FPRs:
   5045   //
   5046   //   <Axxx> <Bxxx> <Cxxxx> <Dxxx>
   5047   //         V              V         VMRHF
   5048   //      <ABxx>         <CDxx>
   5049   //                V                 VMRHG
   5050   //              <ABCD>
   5051   if (VT == MVT::v4f32 && !AllLoads) {
   5052     SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
   5053     SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
   5054     // Avoid unnecessary undefs by reusing the other operand.
   5055     if (Op01.isUndef())
   5056       Op01 = Op23;
   5057     else if (Op23.isUndef())
   5058       Op23 = Op01;
   5059     // Merging identical replications is a no-op.
   5060     if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
   5061       return Op01;
   5062     Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
   5063     Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
   5064     SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
   5065                              DL, MVT::v2i64, Op01, Op23);
   5066     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
   5067   }
   5068 
   5069   // Collect the constant terms.
   5070   SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
   5071   SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
   5072 
   5073   unsigned NumConstants = 0;
   5074   for (unsigned I = 0; I < NumElements; ++I) {
   5075     SDValue Elem = Elems[I];
   5076     if (Elem.getOpcode() == ISD::Constant ||
   5077         Elem.getOpcode() == ISD::ConstantFP) {
   5078       NumConstants += 1;
   5079       Constants[I] = Elem;
   5080       Done[I] = true;
   5081     }
   5082   }
   5083   // If there was at least one constant, fill in the other elements of
   5084   // Constants with undefs to get a full vector constant and use that
   5085   // as the starting point.
   5086   SDValue Result;
   5087   SDValue ReplicatedVal;
   5088   if (NumConstants > 0) {
   5089     for (unsigned I = 0; I < NumElements; ++I)
   5090       if (!Constants[I].getNode())
   5091         Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
   5092     Result = DAG.getBuildVector(VT, DL, Constants);
   5093   } else {
   5094     // Otherwise try to use VLREP or VLVGP to start the sequence in order to
   5095     // avoid a false dependency on any previous contents of the vector
   5096     // register.
   5097 
   5098     // Use a VLREP if at least one element is a load. Make sure to replicate
   5099     // the load with the most elements having its value.
   5100     std::map<const SDNode*, unsigned> UseCounts;
   5101     SDNode *LoadMaxUses = nullptr;
   5102     for (unsigned I = 0; I < NumElements; ++I)
   5103       if (isVectorElementLoad(Elems[I])) {
   5104         SDNode *Ld = Elems[I].getNode();
   5105         UseCounts[Ld]++;
   5106         if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < UseCounts[Ld])
   5107           LoadMaxUses = Ld;
   5108       }
   5109     if (LoadMaxUses != nullptr) {
   5110       ReplicatedVal = SDValue(LoadMaxUses, 0);
   5111       Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
   5112     } else {
   5113       // Try to use VLVGP.
   5114       unsigned I1 = NumElements / 2 - 1;
   5115       unsigned I2 = NumElements - 1;
   5116       bool Def1 = !Elems[I1].isUndef();
   5117       bool Def2 = !Elems[I2].isUndef();
   5118       if (Def1 || Def2) {
   5119         SDValue Elem1 = Elems[Def1 ? I1 : I2];
   5120         SDValue Elem2 = Elems[Def2 ? I2 : I1];
   5121         Result = DAG.getNode(ISD::BITCAST, DL, VT,
   5122                              joinDwords(DAG, DL, Elem1, Elem2));
   5123         Done[I1] = true;
   5124         Done[I2] = true;
   5125       } else
   5126         Result = DAG.getUNDEF(VT);
   5127     }
   5128   }
   5129 
   5130   // Use VLVGx to insert the other elements.
   5131   for (unsigned I = 0; I < NumElements; ++I)
   5132     if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
   5133       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
   5134                            DAG.getConstant(I, DL, MVT::i32));
   5135   return Result;
   5136 }
   5137 
   5138 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
   5139                                                  SelectionDAG &DAG) const {
   5140   auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
   5141   SDLoc DL(Op);
   5142   EVT VT = Op.getValueType();
   5143 
   5144   if (BVN->isConstant()) {
   5145     if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
   5146       return Op;
   5147 
   5148     // Fall back to loading it from memory.
   5149     return SDValue();
   5150   }
   5151 
   5152   // See if we should use shuffles to construct the vector from other vectors.
   5153   if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
   5154     return Res;
   5155 
   5156   // Detect SCALAR_TO_VECTOR conversions.
   5157   if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
   5158     return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
   5159 
   5160   // Otherwise use buildVector to build the vector up from GPRs.
   5161   unsigned NumElements = Op.getNumOperands();
   5162   SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
   5163   for (unsigned I = 0; I < NumElements; ++I)
   5164     Ops[I] = Op.getOperand(I);
   5165   return buildVector(DAG, DL, VT, Ops);
   5166 }
   5167 
   5168 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
   5169                                                    SelectionDAG &DAG) const {
   5170   auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
   5171   SDLoc DL(Op);
   5172   EVT VT = Op.getValueType();
   5173   unsigned NumElements = VT.getVectorNumElements();
   5174 
   5175   if (VSN->isSplat()) {
   5176     SDValue Op0 = Op.getOperand(0);
   5177     unsigned Index = VSN->getSplatIndex();
   5178     assert(Index < VT.getVectorNumElements() &&
   5179            "Splat index should be defined and in first operand");
   5180     // See whether the value we're splatting is directly available as a scalar.
   5181     if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
   5182         Op0.getOpcode() == ISD::BUILD_VECTOR)
   5183       return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
   5184     // Otherwise keep it as a vector-to-vector operation.
   5185     return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
   5186                        DAG.getTargetConstant(Index, DL, MVT::i32));
   5187   }
   5188 
   5189   GeneralShuffle GS(VT);
   5190   for (unsigned I = 0; I < NumElements; ++I) {
   5191     int Elt = VSN->getMaskElt(I);
   5192     if (Elt < 0)
   5193       GS.addUndef();
   5194     else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
   5195                      unsigned(Elt) % NumElements))
   5196       return SDValue();
   5197   }
   5198   return GS.getNode(DAG, SDLoc(VSN));
   5199 }
   5200 
   5201 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
   5202                                                      SelectionDAG &DAG) const {
   5203   SDLoc DL(Op);
   5204   // Just insert the scalar into element 0 of an undefined vector.
   5205   return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
   5206                      Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
   5207                      Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
   5208 }
   5209 
   5210 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
   5211                                                       SelectionDAG &DAG) const {
   5212   // Handle insertions of floating-point values.
   5213   SDLoc DL(Op);
   5214   SDValue Op0 = Op.getOperand(0);
   5215   SDValue Op1 = Op.getOperand(1);
   5216   SDValue Op2 = Op.getOperand(2);
   5217   EVT VT = Op.getValueType();
   5218 
   5219   // Insertions into constant indices of a v2f64 can be done using VPDI.
   5220   // However, if the inserted value is a bitcast or a constant then it's
   5221   // better to use GPRs, as below.
   5222   if (VT == MVT::v2f64 &&
   5223       Op1.getOpcode() != ISD::BITCAST &&
   5224       Op1.getOpcode() != ISD::ConstantFP &&
   5225       Op2.getOpcode() == ISD::Constant) {
   5226     uint64_t Index = cast<ConstantSDNode>(Op2)->getZExtValue();
   5227     unsigned Mask = VT.getVectorNumElements() - 1;
   5228     if (Index <= Mask)
   5229       return Op;
   5230   }
   5231 
   5232   // Otherwise bitcast to the equivalent integer form and insert via a GPR.
   5233   MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
   5234   MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
   5235   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
   5236                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
   5237                             DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
   5238   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
   5239 }
   5240 
   5241 SDValue
   5242 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
   5243                                                SelectionDAG &DAG) const {
   5244   // Handle extractions of floating-point values.
   5245   SDLoc DL(Op);
   5246   SDValue Op0 = Op.getOperand(0);
   5247   SDValue Op1 = Op.getOperand(1);
   5248   EVT VT = Op.getValueType();
   5249   EVT VecVT = Op0.getValueType();
   5250 
   5251   // Extractions of constant indices can be done directly.
   5252   if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
   5253     uint64_t Index = CIndexN->getZExtValue();
   5254     unsigned Mask = VecVT.getVectorNumElements() - 1;
   5255     if (Index <= Mask)
   5256       return Op;
   5257   }
   5258 
   5259   // Otherwise bitcast to the equivalent integer form and extract via a GPR.
   5260   MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
   5261   MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
   5262   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
   5263                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
   5264   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
   5265 }
   5266 
   5267 SDValue SystemZTargetLowering::
   5268 lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
   5269   SDValue PackedOp = Op.getOperand(0);
   5270   EVT OutVT = Op.getValueType();
   5271   EVT InVT = PackedOp.getValueType();
   5272   unsigned ToBits = OutVT.getScalarSizeInBits();
   5273   unsigned FromBits = InVT.getScalarSizeInBits();
   5274   do {
   5275     FromBits *= 2;
   5276     EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
   5277                                  SystemZ::VectorBits / FromBits);
   5278     PackedOp =
   5279       DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(PackedOp), OutVT, PackedOp);
   5280   } while (FromBits != ToBits);
   5281   return PackedOp;
   5282 }
   5283 
   5284 // Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
   5285 SDValue SystemZTargetLowering::
   5286 lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
   5287   SDValue PackedOp = Op.getOperand(0);
   5288   SDLoc DL(Op);
   5289   EVT OutVT = Op.getValueType();
   5290   EVT InVT = PackedOp.getValueType();
   5291   unsigned InNumElts = InVT.getVectorNumElements();
   5292   unsigned OutNumElts = OutVT.getVectorNumElements();
   5293   unsigned NumInPerOut = InNumElts / OutNumElts;
   5294 
   5295   SDValue ZeroVec =
   5296     DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
   5297 
   5298   SmallVector<int, 16> Mask(InNumElts);
   5299   unsigned ZeroVecElt = InNumElts;
   5300   for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
   5301     unsigned MaskElt = PackedElt * NumInPerOut;
   5302     unsigned End = MaskElt + NumInPerOut - 1;
   5303     for (; MaskElt < End; MaskElt++)
   5304       Mask[MaskElt] = ZeroVecElt++;
   5305     Mask[MaskElt] = PackedElt;
   5306   }
   5307   SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
   5308   return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
   5309 }
   5310 
   5311 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
   5312                                           unsigned ByScalar) const {
   5313   // Look for cases where a vector shift can use the *_BY_SCALAR form.
   5314   SDValue Op0 = Op.getOperand(0);
   5315   SDValue Op1 = Op.getOperand(1);
   5316   SDLoc DL(Op);
   5317   EVT VT = Op.getValueType();
   5318   unsigned ElemBitSize = VT.getScalarSizeInBits();
   5319 
   5320   // See whether the shift vector is a splat represented as BUILD_VECTOR.
   5321   if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
   5322     APInt SplatBits, SplatUndef;
   5323     unsigned SplatBitSize;
   5324     bool HasAnyUndefs;
   5325     // Check for constant splats.  Use ElemBitSize as the minimum element
   5326     // width and reject splats that need wider elements.
   5327     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
   5328                              ElemBitSize, true) &&
   5329         SplatBitSize == ElemBitSize) {
   5330       SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
   5331                                       DL, MVT::i32);
   5332       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
   5333     }
   5334     // Check for variable splats.
   5335     BitVector UndefElements;
   5336     SDValue Splat = BVN->getSplatValue(&UndefElements);
   5337     if (Splat) {
   5338       // Since i32 is the smallest legal type, we either need a no-op
   5339       // or a truncation.
   5340       SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
   5341       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
   5342     }
   5343   }
   5344 
   5345   // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
   5346   // and the shift amount is directly available in a GPR.
   5347   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
   5348     if (VSN->isSplat()) {
   5349       SDValue VSNOp0 = VSN->getOperand(0);
   5350       unsigned Index = VSN->getSplatIndex();
   5351       assert(Index < VT.getVectorNumElements() &&
   5352              "Splat index should be defined and in first operand");
   5353       if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
   5354           VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
   5355         // Since i32 is the smallest legal type, we either need a no-op
   5356         // or a truncation.
   5357         SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
   5358                                     VSNOp0.getOperand(Index));
   5359         return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
   5360       }
   5361     }
   5362   }
   5363 
   5364   // Otherwise just treat the current form as legal.
   5365   return Op;
   5366 }
   5367 
   5368 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
   5369                                               SelectionDAG &DAG) const {
   5370   switch (Op.getOpcode()) {
   5371   case ISD::FRAMEADDR:
   5372     return lowerFRAMEADDR(Op, DAG);
   5373   case ISD::RETURNADDR:
   5374     return lowerRETURNADDR(Op, DAG);
   5375   case ISD::BR_CC:
   5376     return lowerBR_CC(Op, DAG);
   5377   case ISD::SELECT_CC:
   5378     return lowerSELECT_CC(Op, DAG);
   5379   case ISD::SETCC:
   5380     return lowerSETCC(Op, DAG);
   5381   case ISD::STRICT_FSETCC:
   5382     return lowerSTRICT_FSETCC(Op, DAG, false);
   5383   case ISD::STRICT_FSETCCS:
   5384     return lowerSTRICT_FSETCC(Op, DAG, true);
   5385   case ISD::GlobalAddress:
   5386     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
   5387   case ISD::GlobalTLSAddress:
   5388     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
   5389   case ISD::BlockAddress:
   5390     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
   5391   case ISD::JumpTable:
   5392     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
   5393   case ISD::ConstantPool:
   5394     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
   5395   case ISD::BITCAST:
   5396     return lowerBITCAST(Op, DAG);
   5397   case ISD::VASTART:
   5398     return lowerVASTART(Op, DAG);
   5399   case ISD::VACOPY:
   5400     return lowerVACOPY(Op, DAG);
   5401   case ISD::DYNAMIC_STACKALLOC:
   5402     return lowerDYNAMIC_STACKALLOC(Op, DAG);
   5403   case ISD::GET_DYNAMIC_AREA_OFFSET:
   5404     return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
   5405   case ISD::SMUL_LOHI:
   5406     return lowerSMUL_LOHI(Op, DAG);
   5407   case ISD::UMUL_LOHI:
   5408     return lowerUMUL_LOHI(Op, DAG);
   5409   case ISD::SDIVREM:
   5410     return lowerSDIVREM(Op, DAG);
   5411   case ISD::UDIVREM:
   5412     return lowerUDIVREM(Op, DAG);
   5413   case ISD::SADDO:
   5414   case ISD::SSUBO:
   5415   case ISD::UADDO:
   5416   case ISD::USUBO:
   5417     return lowerXALUO(Op, DAG);
   5418   case ISD::ADDCARRY:
   5419   case ISD::SUBCARRY:
   5420     return lowerADDSUBCARRY(Op, DAG);
   5421   case ISD::OR:
   5422     return lowerOR(Op, DAG);
   5423   case ISD::CTPOP:
   5424     return lowerCTPOP(Op, DAG);
   5425   case ISD::ATOMIC_FENCE:
   5426     return lowerATOMIC_FENCE(Op, DAG);
   5427   case ISD::ATOMIC_SWAP:
   5428     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
   5429   case ISD::ATOMIC_STORE:
   5430     return lowerATOMIC_STORE(Op, DAG);
   5431   case ISD::ATOMIC_LOAD:
   5432     return lowerATOMIC_LOAD(Op, DAG);
   5433   case ISD::ATOMIC_LOAD_ADD:
   5434     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
   5435   case ISD::ATOMIC_LOAD_SUB:
   5436     return lowerATOMIC_LOAD_SUB(Op, DAG);
   5437   case ISD::ATOMIC_LOAD_AND:
   5438     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
   5439   case ISD::ATOMIC_LOAD_OR:
   5440     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
   5441   case ISD::ATOMIC_LOAD_XOR:
   5442     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
   5443   case ISD::ATOMIC_LOAD_NAND:
   5444     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
   5445   case ISD::ATOMIC_LOAD_MIN:
   5446     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
   5447   case ISD::ATOMIC_LOAD_MAX:
   5448     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
   5449   case ISD::ATOMIC_LOAD_UMIN:
   5450     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
   5451   case ISD::ATOMIC_LOAD_UMAX:
   5452     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
   5453   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
   5454     return lowerATOMIC_CMP_SWAP(Op, DAG);
   5455   case ISD::STACKSAVE:
   5456     return lowerSTACKSAVE(Op, DAG);
   5457   case ISD::STACKRESTORE:
   5458     return lowerSTACKRESTORE(Op, DAG);
   5459   case ISD::PREFETCH:
   5460     return lowerPREFETCH(Op, DAG);
   5461   case ISD::INTRINSIC_W_CHAIN:
   5462     return lowerINTRINSIC_W_CHAIN(Op, DAG);
   5463   case ISD::INTRINSIC_WO_CHAIN:
   5464     return lowerINTRINSIC_WO_CHAIN(Op, DAG);
   5465   case ISD::BUILD_VECTOR:
   5466     return lowerBUILD_VECTOR(Op, DAG);
   5467   case ISD::VECTOR_SHUFFLE:
   5468     return lowerVECTOR_SHUFFLE(Op, DAG);
   5469   case ISD::SCALAR_TO_VECTOR:
   5470     return lowerSCALAR_TO_VECTOR(Op, DAG);
   5471   case ISD::INSERT_VECTOR_ELT:
   5472     return lowerINSERT_VECTOR_ELT(Op, DAG);
   5473   case ISD::EXTRACT_VECTOR_ELT:
   5474     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
   5475   case ISD::SIGN_EXTEND_VECTOR_INREG:
   5476     return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
   5477   case ISD::ZERO_EXTEND_VECTOR_INREG:
   5478     return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
   5479   case ISD::SHL:
   5480     return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
   5481   case ISD::SRL:
   5482     return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
   5483   case ISD::SRA:
   5484     return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
   5485   default:
   5486     llvm_unreachable("Unexpected node to lower");
   5487   }
   5488 }
   5489 
   5490 // Lower operations with invalid operand or result types (currently used
   5491 // only for 128-bit integer types).
   5492 
   5493 static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In) {
   5494   SDLoc DL(In);
   5495   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
   5496                            DAG.getIntPtrConstant(0, DL));
   5497   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
   5498                            DAG.getIntPtrConstant(1, DL));
   5499   SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
   5500                                     MVT::Untyped, Hi, Lo);
   5501   return SDValue(Pair, 0);
   5502 }
   5503 
   5504 static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In) {
   5505   SDLoc DL(In);
   5506   SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
   5507                                           DL, MVT::i64, In);
   5508   SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
   5509                                           DL, MVT::i64, In);
   5510   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
   5511 }
   5512 
   5513 void
   5514 SystemZTargetLowering::LowerOperationWrapper(SDNode *N,
   5515                                              SmallVectorImpl<SDValue> &Results,
   5516                                              SelectionDAG &DAG) const {
   5517   switch (N->getOpcode()) {
   5518   case ISD::ATOMIC_LOAD: {
   5519     SDLoc DL(N);
   5520     SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other);
   5521     SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
   5522     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
   5523     SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
   5524                                           DL, Tys, Ops, MVT::i128, MMO);
   5525     Results.push_back(lowerGR128ToI128(DAG, Res));
   5526     Results.push_back(Res.getValue(1));
   5527     break;
   5528   }
   5529   case ISD::ATOMIC_STORE: {
   5530     SDLoc DL(N);
   5531     SDVTList Tys = DAG.getVTList(MVT::Other);
   5532     SDValue Ops[] = { N->getOperand(0),
   5533                       lowerI128ToGR128(DAG, N->getOperand(2)),
   5534                       N->getOperand(1) };
   5535     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
   5536     SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
   5537                                           DL, Tys, Ops, MVT::i128, MMO);
   5538     // We have to enforce sequential consistency by performing a
   5539     // serialization operation after the store.
   5540     if (cast<AtomicSDNode>(N)->getOrdering() ==
   5541         AtomicOrdering::SequentiallyConsistent)
   5542       Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
   5543                                        MVT::Other, Res), 0);
   5544     Results.push_back(Res);
   5545     break;
   5546   }
   5547   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
   5548     SDLoc DL(N);
   5549     SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other);
   5550     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
   5551                       lowerI128ToGR128(DAG, N->getOperand(2)),
   5552                       lowerI128ToGR128(DAG, N->getOperand(3)) };
   5553     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
   5554     SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
   5555                                           DL, Tys, Ops, MVT::i128, MMO);
   5556     SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
   5557                                 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
   5558     Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
   5559     Results.push_back(lowerGR128ToI128(DAG, Res));
   5560     Results.push_back(Success);
   5561     Results.push_back(Res.getValue(2));
   5562     break;
   5563   }
   5564   default:
   5565     llvm_unreachable("Unexpected node to lower");
   5566   }
   5567 }
   5568 
   5569 void
   5570 SystemZTargetLowering::ReplaceNodeResults(SDNode *N,
   5571                                           SmallVectorImpl<SDValue> &Results,
   5572                                           SelectionDAG &DAG) const {
   5573   return LowerOperationWrapper(N, Results, DAG);
   5574 }
   5575 
   5576 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
   5577 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
   5578   switch ((SystemZISD::NodeType)Opcode) {
   5579     case SystemZISD::FIRST_NUMBER: break;
   5580     OPCODE(RET_FLAG);
   5581     OPCODE(CALL);
   5582     OPCODE(SIBCALL);
   5583     OPCODE(TLS_GDCALL);
   5584     OPCODE(TLS_LDCALL);
   5585     OPCODE(PCREL_WRAPPER);
   5586     OPCODE(PCREL_OFFSET);
   5587     OPCODE(ICMP);
   5588     OPCODE(FCMP);
   5589     OPCODE(STRICT_FCMP);
   5590     OPCODE(STRICT_FCMPS);
   5591     OPCODE(TM);
   5592     OPCODE(BR_CCMASK);
   5593     OPCODE(SELECT_CCMASK);
   5594     OPCODE(ADJDYNALLOC);
   5595     OPCODE(PROBED_ALLOCA);
   5596     OPCODE(POPCNT);
   5597     OPCODE(SMUL_LOHI);
   5598     OPCODE(UMUL_LOHI);
   5599     OPCODE(SDIVREM);
   5600     OPCODE(UDIVREM);
   5601     OPCODE(SADDO);
   5602     OPCODE(SSUBO);
   5603     OPCODE(UADDO);
   5604     OPCODE(USUBO);
   5605     OPCODE(ADDCARRY);
   5606     OPCODE(SUBCARRY);
   5607     OPCODE(GET_CCMASK);
   5608     OPCODE(MVC);
   5609     OPCODE(MVC_LOOP);
   5610     OPCODE(NC);
   5611     OPCODE(NC_LOOP);
   5612     OPCODE(OC);
   5613     OPCODE(OC_LOOP);
   5614     OPCODE(XC);
   5615     OPCODE(XC_LOOP);
   5616     OPCODE(CLC);
   5617     OPCODE(CLC_LOOP);
   5618     OPCODE(STPCPY);
   5619     OPCODE(STRCMP);
   5620     OPCODE(SEARCH_STRING);
   5621     OPCODE(IPM);
   5622     OPCODE(MEMBARRIER);
   5623     OPCODE(TBEGIN);
   5624     OPCODE(TBEGIN_NOFLOAT);
   5625     OPCODE(TEND);
   5626     OPCODE(BYTE_MASK);
   5627     OPCODE(ROTATE_MASK);
   5628     OPCODE(REPLICATE);
   5629     OPCODE(JOIN_DWORDS);
   5630     OPCODE(SPLAT);
   5631     OPCODE(MERGE_HIGH);
   5632     OPCODE(MERGE_LOW);
   5633     OPCODE(SHL_DOUBLE);
   5634     OPCODE(PERMUTE_DWORDS);
   5635     OPCODE(PERMUTE);
   5636     OPCODE(PACK);
   5637     OPCODE(PACKS_CC);
   5638     OPCODE(PACKLS_CC);
   5639     OPCODE(UNPACK_HIGH);
   5640     OPCODE(UNPACKL_HIGH);
   5641     OPCODE(UNPACK_LOW);
   5642     OPCODE(UNPACKL_LOW);
   5643     OPCODE(VSHL_BY_SCALAR);
   5644     OPCODE(VSRL_BY_SCALAR);
   5645     OPCODE(VSRA_BY_SCALAR);
   5646     OPCODE(VSUM);
   5647     OPCODE(VICMPE);
   5648     OPCODE(VICMPH);
   5649     OPCODE(VICMPHL);
   5650     OPCODE(VICMPES);
   5651     OPCODE(VICMPHS);
   5652     OPCODE(VICMPHLS);
   5653     OPCODE(VFCMPE);
   5654     OPCODE(STRICT_VFCMPE);
   5655     OPCODE(STRICT_VFCMPES);
   5656     OPCODE(VFCMPH);
   5657     OPCODE(STRICT_VFCMPH);
   5658     OPCODE(STRICT_VFCMPHS);
   5659     OPCODE(VFCMPHE);
   5660     OPCODE(STRICT_VFCMPHE);
   5661     OPCODE(STRICT_VFCMPHES);
   5662     OPCODE(VFCMPES);
   5663     OPCODE(VFCMPHS);
   5664     OPCODE(VFCMPHES);
   5665     OPCODE(VFTCI);
   5666     OPCODE(VEXTEND);
   5667     OPCODE(STRICT_VEXTEND);
   5668     OPCODE(VROUND);
   5669     OPCODE(STRICT_VROUND);
   5670     OPCODE(VTM);
   5671     OPCODE(VFAE_CC);
   5672     OPCODE(VFAEZ_CC);
   5673     OPCODE(VFEE_CC);
   5674     OPCODE(VFEEZ_CC);
   5675     OPCODE(VFENE_CC);
   5676     OPCODE(VFENEZ_CC);
   5677     OPCODE(VISTR_CC);
   5678     OPCODE(VSTRC_CC);
   5679     OPCODE(VSTRCZ_CC);
   5680     OPCODE(VSTRS_CC);
   5681     OPCODE(VSTRSZ_CC);
   5682     OPCODE(TDC);
   5683     OPCODE(ATOMIC_SWAPW);
   5684     OPCODE(ATOMIC_LOADW_ADD);
   5685     OPCODE(ATOMIC_LOADW_SUB);
   5686     OPCODE(ATOMIC_LOADW_AND);
   5687     OPCODE(ATOMIC_LOADW_OR);
   5688     OPCODE(ATOMIC_LOADW_XOR);
   5689     OPCODE(ATOMIC_LOADW_NAND);
   5690     OPCODE(ATOMIC_LOADW_MIN);
   5691     OPCODE(ATOMIC_LOADW_MAX);
   5692     OPCODE(ATOMIC_LOADW_UMIN);
   5693     OPCODE(ATOMIC_LOADW_UMAX);
   5694     OPCODE(ATOMIC_CMP_SWAPW);
   5695     OPCODE(ATOMIC_CMP_SWAP);
   5696     OPCODE(ATOMIC_LOAD_128);
   5697     OPCODE(ATOMIC_STORE_128);
   5698     OPCODE(ATOMIC_CMP_SWAP_128);
   5699     OPCODE(LRV);
   5700     OPCODE(STRV);
   5701     OPCODE(VLER);
   5702     OPCODE(VSTER);
   5703     OPCODE(PREFETCH);
   5704   }
   5705   return nullptr;
   5706 #undef OPCODE
   5707 }
   5708 
   5709 // Return true if VT is a vector whose elements are a whole number of bytes
   5710 // in width. Also check for presence of vector support.
   5711 bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
   5712   if (!Subtarget.hasVector())
   5713     return false;
   5714 
   5715   return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
   5716 }
   5717 
   5718 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
   5719 // producing a result of type ResVT.  Op is a possibly bitcast version
   5720 // of the input vector and Index is the index (based on type VecVT) that
   5721 // should be extracted.  Return the new extraction if a simplification
   5722 // was possible or if Force is true.
   5723 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
   5724                                               EVT VecVT, SDValue Op,
   5725                                               unsigned Index,
   5726                                               DAGCombinerInfo &DCI,
   5727                                               bool Force) const {
   5728   SelectionDAG &DAG = DCI.DAG;
   5729 
   5730   // The number of bytes being extracted.
   5731   unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
   5732 
   5733   for (;;) {
   5734     unsigned Opcode = Op.getOpcode();
   5735     if (Opcode == ISD::BITCAST)
   5736       // Look through bitcasts.
   5737       Op = Op.getOperand(0);
   5738     else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
   5739              canTreatAsByteVector(Op.getValueType())) {
   5740       // Get a VPERM-like permute mask and see whether the bytes covered
   5741       // by the extracted element are a contiguous sequence from one
   5742       // source operand.
   5743       SmallVector<int, SystemZ::VectorBytes> Bytes;
   5744       if (!getVPermMask(Op, Bytes))
   5745         break;
   5746       int First;
   5747       if (!getShuffleInput(Bytes, Index * BytesPerElement,
   5748                            BytesPerElement, First))
   5749         break;
   5750       if (First < 0)
   5751         return DAG.getUNDEF(ResVT);
   5752       // Make sure the contiguous sequence starts at a multiple of the
   5753       // original element size.
   5754       unsigned Byte = unsigned(First) % Bytes.size();
   5755       if (Byte % BytesPerElement != 0)
   5756         break;
   5757       // We can get the extracted value directly from an input.
   5758       Index = Byte / BytesPerElement;
   5759       Op = Op.getOperand(unsigned(First) / Bytes.size());
   5760       Force = true;
   5761     } else if (Opcode == ISD::BUILD_VECTOR &&
   5762                canTreatAsByteVector(Op.getValueType())) {
   5763       // We can only optimize this case if the BUILD_VECTOR elements are
   5764       // at least as wide as the extracted value.
   5765       EVT OpVT = Op.getValueType();
   5766       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
   5767       if (OpBytesPerElement < BytesPerElement)
   5768         break;
   5769       // Make sure that the least-significant bit of the extracted value
   5770       // is the least significant bit of an input.
   5771       unsigned End = (Index + 1) * BytesPerElement;
   5772       if (End % OpBytesPerElement != 0)
   5773         break;
   5774       // We're extracting the low part of one operand of the BUILD_VECTOR.
   5775       Op = Op.getOperand(End / OpBytesPerElement - 1);
   5776       if (!Op.getValueType().isInteger()) {
   5777         EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
   5778         Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
   5779         DCI.AddToWorklist(Op.getNode());
   5780       }
   5781       EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
   5782       Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
   5783       if (VT != ResVT) {
   5784         DCI.AddToWorklist(Op.getNode());
   5785         Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
   5786       }
   5787       return Op;
   5788     } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
   5789                 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
   5790                 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
   5791                canTreatAsByteVector(Op.getValueType()) &&
   5792                canTreatAsByteVector(Op.getOperand(0).getValueType())) {
   5793       // Make sure that only the unextended bits are significant.
   5794       EVT ExtVT = Op.getValueType();
   5795       EVT OpVT = Op.getOperand(0).getValueType();
   5796       unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
   5797       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
   5798       unsigned Byte = Index * BytesPerElement;
   5799       unsigned SubByte = Byte % ExtBytesPerElement;
   5800       unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
   5801       if (SubByte < MinSubByte ||
   5802           SubByte + BytesPerElement > ExtBytesPerElement)
   5803         break;
   5804       // Get the byte offset of the unextended element
   5805       Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
   5806       // ...then add the byte offset relative to that element.
   5807       Byte += SubByte - MinSubByte;
   5808       if (Byte % BytesPerElement != 0)
   5809         break;
   5810       Op = Op.getOperand(0);
   5811       Index = Byte / BytesPerElement;
   5812       Force = true;
   5813     } else
   5814       break;
   5815   }
   5816   if (Force) {
   5817     if (Op.getValueType() != VecVT) {
   5818       Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
   5819       DCI.AddToWorklist(Op.getNode());
   5820     }
   5821     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
   5822                        DAG.getConstant(Index, DL, MVT::i32));
   5823   }
   5824   return SDValue();
   5825 }
   5826 
   5827 // Optimize vector operations in scalar value Op on the basis that Op
   5828 // is truncated to TruncVT.
   5829 SDValue SystemZTargetLowering::combineTruncateExtract(
   5830     const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
   5831   // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
   5832   // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
   5833   // of type TruncVT.
   5834   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   5835       TruncVT.getSizeInBits() % 8 == 0) {
   5836     SDValue Vec = Op.getOperand(0);
   5837     EVT VecVT = Vec.getValueType();
   5838     if (canTreatAsByteVector(VecVT)) {
   5839       if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
   5840         unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
   5841         unsigned TruncBytes = TruncVT.getStoreSize();
   5842         if (BytesPerElement % TruncBytes == 0) {
   5843           // Calculate the value of Y' in the above description.  We are
   5844           // splitting the original elements into Scale equal-sized pieces
   5845           // and for truncation purposes want the last (least-significant)
   5846           // of these pieces for IndexN.  This is easiest to do by calculating
   5847           // the start index of the following element and then subtracting 1.
   5848           unsigned Scale = BytesPerElement / TruncBytes;
   5849           unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
   5850 
   5851           // Defer the creation of the bitcast from X to combineExtract,
   5852           // which might be able to optimize the extraction.
   5853           VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
   5854                                    VecVT.getStoreSize() / TruncBytes);
   5855           EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
   5856           return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
   5857         }
   5858       }
   5859     }
   5860   }
   5861   return SDValue();
   5862 }
   5863 
   5864 SDValue SystemZTargetLowering::combineZERO_EXTEND(
   5865     SDNode *N, DAGCombinerInfo &DCI) const {
   5866   // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
   5867   SelectionDAG &DAG = DCI.DAG;
   5868   SDValue N0 = N->getOperand(0);
   5869   EVT VT = N->getValueType(0);
   5870   if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
   5871     auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
   5872     auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   5873     if (TrueOp && FalseOp) {
   5874       SDLoc DL(N0);
   5875       SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
   5876                         DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
   5877                         N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
   5878       SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
   5879       // If N0 has multiple uses, change other uses as well.
   5880       if (!N0.hasOneUse()) {
   5881         SDValue TruncSelect =
   5882           DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
   5883         DCI.CombineTo(N0.getNode(), TruncSelect);
   5884       }
   5885       return NewSelect;
   5886     }
   5887   }
   5888   return SDValue();
   5889 }
   5890 
   5891 SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
   5892     SDNode *N, DAGCombinerInfo &DCI) const {
   5893   // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
   5894   // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
   5895   // into (select_cc LHS, RHS, -1, 0, COND)
   5896   SelectionDAG &DAG = DCI.DAG;
   5897   SDValue N0 = N->getOperand(0);
   5898   EVT VT = N->getValueType(0);
   5899   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
   5900   if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
   5901     N0 = N0.getOperand(0);
   5902   if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
   5903     SDLoc DL(N0);
   5904     SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
   5905                       DAG.getConstant(-1, DL, VT), DAG.getConstant(0, DL, VT),
   5906                       N0.getOperand(2) };
   5907     return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
   5908   }
   5909   return SDValue();
   5910 }
   5911 
   5912 SDValue SystemZTargetLowering::combineSIGN_EXTEND(
   5913     SDNode *N, DAGCombinerInfo &DCI) const {
   5914   // Convert (sext (ashr (shl X, C1), C2)) to
   5915   // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
   5916   // cheap as narrower ones.
   5917   SelectionDAG &DAG = DCI.DAG;
   5918   SDValue N0 = N->getOperand(0);
   5919   EVT VT = N->getValueType(0);
   5920   if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
   5921     auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   5922     SDValue Inner = N0.getOperand(0);
   5923     if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
   5924       if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
   5925         unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
   5926         unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
   5927         unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
   5928         EVT ShiftVT = N0.getOperand(1).getValueType();
   5929         SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
   5930                                   Inner.getOperand(0));
   5931         SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
   5932                                   DAG.getConstant(NewShlAmt, SDLoc(Inner),
   5933                                                   ShiftVT));
   5934         return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
   5935                            DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
   5936       }
   5937     }
   5938   }
   5939   return SDValue();
   5940 }
   5941 
   5942 SDValue SystemZTargetLowering::combineMERGE(
   5943     SDNode *N, DAGCombinerInfo &DCI) const {
   5944   SelectionDAG &DAG = DCI.DAG;
   5945   unsigned Opcode = N->getOpcode();
   5946   SDValue Op0 = N->getOperand(0);
   5947   SDValue Op1 = N->getOperand(1);
   5948   if (Op0.getOpcode() == ISD::BITCAST)
   5949     Op0 = Op0.getOperand(0);
   5950   if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
   5951     // (z_merge_* 0, 0) -> 0.  This is mostly useful for using VLLEZF
   5952     // for v4f32.
   5953     if (Op1 == N->getOperand(0))
   5954       return Op1;
   5955     // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
   5956     EVT VT = Op1.getValueType();
   5957     unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
   5958     if (ElemBytes <= 4) {
   5959       Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
   5960                 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
   5961       EVT InVT = VT.changeVectorElementTypeToInteger();
   5962       EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
   5963                                    SystemZ::VectorBytes / ElemBytes / 2);
   5964       if (VT != InVT) {
   5965         Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
   5966         DCI.AddToWorklist(Op1.getNode());
   5967       }
   5968       SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
   5969       DCI.AddToWorklist(Op.getNode());
   5970       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
   5971     }
   5972   }
   5973   return SDValue();
   5974 }
   5975 
   5976 SDValue SystemZTargetLowering::combineLOAD(
   5977     SDNode *N, DAGCombinerInfo &DCI) const {
   5978   SelectionDAG &DAG = DCI.DAG;
   5979   EVT LdVT = N->getValueType(0);
   5980   if (LdVT.isVector() || LdVT.isInteger())
   5981     return SDValue();
   5982   // Transform a scalar load that is REPLICATEd as well as having other
   5983   // use(s) to the form where the other use(s) use the first element of the
   5984   // REPLICATE instead of the load. Otherwise instruction selection will not
   5985   // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
   5986   // point loads.
   5987 
   5988   SDValue Replicate;
   5989   SmallVector<SDNode*, 8> OtherUses;
   5990   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
   5991        UI != UE; ++UI) {
   5992     if (UI->getOpcode() == SystemZISD::REPLICATE) {
   5993       if (Replicate)
   5994         return SDValue(); // Should never happen
   5995       Replicate = SDValue(*UI, 0);
   5996     }
   5997     else if (UI.getUse().getResNo() == 0)
   5998       OtherUses.push_back(*UI);
   5999   }
   6000   if (!Replicate || OtherUses.empty())
   6001     return SDValue();
   6002 
   6003   SDLoc DL(N);
   6004   SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
   6005                               Replicate, DAG.getConstant(0, DL, MVT::i32));
   6006   // Update uses of the loaded Value while preserving old chains.
   6007   for (SDNode *U : OtherUses) {
   6008     SmallVector<SDValue, 8> Ops;
   6009     for (SDValue Op : U->ops())
   6010       Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
   6011     DAG.UpdateNodeOperands(U, Ops);
   6012   }
   6013   return SDValue(N, 0);
   6014 }
   6015 
   6016 bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
   6017   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
   6018     return true;
   6019   if (Subtarget.hasVectorEnhancements2())
   6020     if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64)
   6021       return true;
   6022   return false;
   6023 }
   6024 
   6025 static bool isVectorElementSwap(ArrayRef<int> M, EVT VT) {
   6026   if (!VT.isVector() || !VT.isSimple() ||
   6027       VT.getSizeInBits() != 128 ||
   6028       VT.getScalarSizeInBits() % 8 != 0)
   6029     return false;
   6030 
   6031   unsigned NumElts = VT.getVectorNumElements();
   6032   for (unsigned i = 0; i < NumElts; ++i) {
   6033     if (M[i] < 0) continue; // ignore UNDEF indices
   6034     if ((unsigned) M[i] != NumElts - 1 - i)
   6035       return false;
   6036   }
   6037 
   6038   return true;
   6039 }
   6040 
   6041 SDValue SystemZTargetLowering::combineSTORE(
   6042     SDNode *N, DAGCombinerInfo &DCI) const {
   6043   SelectionDAG &DAG = DCI.DAG;
   6044   auto *SN = cast<StoreSDNode>(N);
   6045   auto &Op1 = N->getOperand(1);
   6046   EVT MemVT = SN->getMemoryVT();
   6047   // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
   6048   // for the extraction to be done on a vMiN value, so that we can use VSTE.
   6049   // If X has wider elements then convert it to:
   6050   // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
   6051   if (MemVT.isInteger() && SN->isTruncatingStore()) {
   6052     if (SDValue Value =
   6053             combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
   6054       DCI.AddToWorklist(Value.getNode());
   6055 
   6056       // Rewrite the store with the new form of stored value.
   6057       return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
   6058                                SN->getBasePtr(), SN->getMemoryVT(),
   6059                                SN->getMemOperand());
   6060     }
   6061   }
   6062   // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
   6063   if (!SN->isTruncatingStore() &&
   6064       Op1.getOpcode() == ISD::BSWAP &&
   6065       Op1.getNode()->hasOneUse() &&
   6066       canLoadStoreByteSwapped(Op1.getValueType())) {
   6067 
   6068       SDValue BSwapOp = Op1.getOperand(0);
   6069 
   6070       if (BSwapOp.getValueType() == MVT::i16)
   6071         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
   6072 
   6073       SDValue Ops[] = {
   6074         N->getOperand(0), BSwapOp, N->getOperand(2)
   6075       };
   6076 
   6077       return
   6078         DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
   6079                                 Ops, MemVT, SN->getMemOperand());
   6080     }
   6081   // Combine STORE (element-swap) into VSTER
   6082   if (!SN->isTruncatingStore() &&
   6083       Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
   6084       Op1.getNode()->hasOneUse() &&
   6085       Subtarget.hasVectorEnhancements2()) {
   6086     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
   6087     ArrayRef<int> ShuffleMask = SVN->getMask();
   6088     if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
   6089       SDValue Ops[] = {
   6090         N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
   6091       };
   6092 
   6093       return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
   6094                                      DAG.getVTList(MVT::Other),
   6095                                      Ops, MemVT, SN->getMemOperand());
   6096     }
   6097   }
   6098 
   6099   return SDValue();
   6100 }
   6101 
   6102 SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
   6103     SDNode *N, DAGCombinerInfo &DCI) const {
   6104   SelectionDAG &DAG = DCI.DAG;
   6105   // Combine element-swap (LOAD) into VLER
   6106   if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
   6107       N->getOperand(0).hasOneUse() &&
   6108       Subtarget.hasVectorEnhancements2()) {
   6109     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
   6110     ArrayRef<int> ShuffleMask = SVN->getMask();
   6111     if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
   6112       SDValue Load = N->getOperand(0);
   6113       LoadSDNode *LD = cast<LoadSDNode>(Load);
   6114 
   6115       // Create the element-swapping load.
   6116       SDValue Ops[] = {
   6117         LD->getChain(),    // Chain
   6118         LD->getBasePtr()   // Ptr
   6119       };
   6120       SDValue ESLoad =
   6121         DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
   6122                                 DAG.getVTList(LD->getValueType(0), MVT::Other),
   6123                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
   6124 
   6125       // First, combine the VECTOR_SHUFFLE away.  This makes the value produced
   6126       // by the load dead.
   6127       DCI.CombineTo(N, ESLoad);
   6128 
   6129       // Next, combine the load away, we give it a bogus result value but a real
   6130       // chain result.  The result value is dead because the shuffle is dead.
   6131       DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
   6132 
   6133       // Return N so it doesn't get rechecked!
   6134       return SDValue(N, 0);
   6135     }
   6136   }
   6137 
   6138   return SDValue();
   6139 }
   6140 
   6141 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
   6142     SDNode *N, DAGCombinerInfo &DCI) const {
   6143   SelectionDAG &DAG = DCI.DAG;
   6144 
   6145   if (!Subtarget.hasVector())
   6146     return SDValue();
   6147 
   6148   // Look through bitcasts that retain the number of vector elements.
   6149   SDValue Op = N->getOperand(0);
   6150   if (Op.getOpcode() == ISD::BITCAST &&
   6151       Op.getValueType().isVector() &&
   6152       Op.getOperand(0).getValueType().isVector() &&
   6153       Op.getValueType().getVectorNumElements() ==
   6154       Op.getOperand(0).getValueType().getVectorNumElements())
   6155     Op = Op.getOperand(0);
   6156 
   6157   // Pull BSWAP out of a vector extraction.
   6158   if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
   6159     EVT VecVT = Op.getValueType();
   6160     EVT EltVT = VecVT.getVectorElementType();
   6161     Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
   6162                      Op.getOperand(0), N->getOperand(1));
   6163     DCI.AddToWorklist(Op.getNode());
   6164     Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
   6165     if (EltVT != N->getValueType(0)) {
   6166       DCI.AddToWorklist(Op.getNode());
   6167       Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
   6168     }
   6169     return Op;
   6170   }
   6171 
   6172   // Try to simplify a vector extraction.
   6173   if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
   6174     SDValue Op0 = N->getOperand(0);
   6175     EVT VecVT = Op0.getValueType();
   6176     return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
   6177                           IndexN->getZExtValue(), DCI, false);
   6178   }
   6179   return SDValue();
   6180 }
   6181 
   6182 SDValue SystemZTargetLowering::combineJOIN_DWORDS(
   6183     SDNode *N, DAGCombinerInfo &DCI) const {
   6184   SelectionDAG &DAG = DCI.DAG;
   6185   // (join_dwords X, X) == (replicate X)
   6186   if (N->getOperand(0) == N->getOperand(1))
   6187     return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
   6188                        N->getOperand(0));
   6189   return SDValue();
   6190 }
   6191 
   6192 static SDValue MergeInputChains(SDNode *N1, SDNode *N2) {
   6193   SDValue Chain1 = N1->getOperand(0);
   6194   SDValue Chain2 = N2->getOperand(0);
   6195 
   6196   // Trivial case: both nodes take the same chain.
   6197   if (Chain1 == Chain2)
   6198     return Chain1;
   6199 
   6200   // FIXME - we could handle more complex cases via TokenFactor,
   6201   // assuming we can verify that this would not create a cycle.
   6202   return SDValue();
   6203 }
   6204 
   6205 SDValue SystemZTargetLowering::combineFP_ROUND(
   6206     SDNode *N, DAGCombinerInfo &DCI) const {
   6207 
   6208   if (!Subtarget.hasVector())
   6209     return SDValue();
   6210 
   6211   // (fpround (extract_vector_elt X 0))
   6212   // (fpround (extract_vector_elt X 1)) ->
   6213   // (extract_vector_elt (VROUND X) 0)
   6214   // (extract_vector_elt (VROUND X) 2)
   6215   //
   6216   // This is a special case since the target doesn't really support v2f32s.
   6217   unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
   6218   SelectionDAG &DAG = DCI.DAG;
   6219   SDValue Op0 = N->getOperand(OpNo);
   6220   if (N->getValueType(0) == MVT::f32 &&
   6221       Op0.hasOneUse() &&
   6222       Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   6223       Op0.getOperand(0).getValueType() == MVT::v2f64 &&
   6224       Op0.getOperand(1).getOpcode() == ISD::Constant &&
   6225       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
   6226     SDValue Vec = Op0.getOperand(0);
   6227     for (auto *U : Vec->uses()) {
   6228       if (U != Op0.getNode() &&
   6229           U->hasOneUse() &&
   6230           U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   6231           U->getOperand(0) == Vec &&
   6232           U->getOperand(1).getOpcode() == ISD::Constant &&
   6233           cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
   6234         SDValue OtherRound = SDValue(*U->use_begin(), 0);
   6235         if (OtherRound.getOpcode() == N->getOpcode() &&
   6236             OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
   6237             OtherRound.getValueType() == MVT::f32) {
   6238           SDValue VRound, Chain;
   6239           if (N->isStrictFPOpcode()) {
   6240             Chain = MergeInputChains(N, OtherRound.getNode());
   6241             if (!Chain)
   6242               continue;
   6243             VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
   6244                                  {MVT::v4f32, MVT::Other}, {Chain, Vec});
   6245             Chain = VRound.getValue(1);
   6246           } else
   6247             VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
   6248                                  MVT::v4f32, Vec);
   6249           DCI.AddToWorklist(VRound.getNode());
   6250           SDValue Extract1 =
   6251             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
   6252                         VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
   6253           DCI.AddToWorklist(Extract1.getNode());
   6254           DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
   6255           if (Chain)
   6256             DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
   6257           SDValue Extract0 =
   6258             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
   6259                         VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
   6260           if (Chain)
   6261             return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
   6262                                N->getVTList(), Extract0, Chain);
   6263           return Extract0;
   6264         }
   6265       }
   6266     }
   6267   }
   6268   return SDValue();
   6269 }
   6270 
   6271 SDValue SystemZTargetLowering::combineFP_EXTEND(
   6272     SDNode *N, DAGCombinerInfo &DCI) const {
   6273 
   6274   if (!Subtarget.hasVector())
   6275     return SDValue();
   6276 
   6277   // (fpextend (extract_vector_elt X 0))
   6278   // (fpextend (extract_vector_elt X 2)) ->
   6279   // (extract_vector_elt (VEXTEND X) 0)
   6280   // (extract_vector_elt (VEXTEND X) 1)
   6281   //
   6282   // This is a special case since the target doesn't really support v2f32s.
   6283   unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
   6284   SelectionDAG &DAG = DCI.DAG;
   6285   SDValue Op0 = N->getOperand(OpNo);
   6286   if (N->getValueType(0) == MVT::f64 &&
   6287       Op0.hasOneUse() &&
   6288       Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   6289       Op0.getOperand(0).getValueType() == MVT::v4f32 &&
   6290       Op0.getOperand(1).getOpcode() == ISD::Constant &&
   6291       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
   6292     SDValue Vec = Op0.getOperand(0);
   6293     for (auto *U : Vec->uses()) {
   6294       if (U != Op0.getNode() &&
   6295           U->hasOneUse() &&
   6296           U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   6297           U->getOperand(0) == Vec &&
   6298           U->getOperand(1).getOpcode() == ISD::Constant &&
   6299           cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 2) {
   6300         SDValue OtherExtend = SDValue(*U->use_begin(), 0);
   6301         if (OtherExtend.getOpcode() == N->getOpcode() &&
   6302             OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
   6303             OtherExtend.getValueType() == MVT::f64) {
   6304           SDValue VExtend, Chain;
   6305           if (N->isStrictFPOpcode()) {
   6306             Chain = MergeInputChains(N, OtherExtend.getNode());
   6307             if (!Chain)
   6308               continue;
   6309             VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
   6310                                   {MVT::v2f64, MVT::Other}, {Chain, Vec});
   6311             Chain = VExtend.getValue(1);
   6312           } else
   6313             VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
   6314                                   MVT::v2f64, Vec);
   6315           DCI.AddToWorklist(VExtend.getNode());
   6316           SDValue Extract1 =
   6317             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
   6318                         VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
   6319           DCI.AddToWorklist(Extract1.getNode());
   6320           DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
   6321           if (Chain)
   6322             DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
   6323           SDValue Extract0 =
   6324             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
   6325                         VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
   6326           if (Chain)
   6327             return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
   6328                                N->getVTList(), Extract0, Chain);
   6329           return Extract0;
   6330         }
   6331       }
   6332     }
   6333   }
   6334   return SDValue();
   6335 }
   6336 
   6337 SDValue SystemZTargetLowering::combineINT_TO_FP(
   6338     SDNode *N, DAGCombinerInfo &DCI) const {
   6339   if (DCI.Level != BeforeLegalizeTypes)
   6340     return SDValue();
   6341   unsigned Opcode = N->getOpcode();
   6342   EVT OutVT = N->getValueType(0);
   6343   SelectionDAG &DAG = DCI.DAG;
   6344   SDValue Op = N->getOperand(0);
   6345   unsigned OutScalarBits = OutVT.getScalarSizeInBits();
   6346   unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
   6347 
   6348   // Insert an extension before type-legalization to avoid scalarization, e.g.:
   6349   // v2f64 = uint_to_fp v2i16
   6350   // =>
   6351   // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
   6352   if (OutVT.isVector() && OutScalarBits > InScalarBits) {
   6353     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(OutVT.getScalarSizeInBits()),
   6354                                  OutVT.getVectorNumElements());
   6355     unsigned ExtOpcode =
   6356       (Opcode == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND);
   6357     SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
   6358     return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
   6359   }
   6360   return SDValue();
   6361 }
   6362 
   6363 SDValue SystemZTargetLowering::combineBSWAP(
   6364     SDNode *N, DAGCombinerInfo &DCI) const {
   6365   SelectionDAG &DAG = DCI.DAG;
   6366   // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
   6367   if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
   6368       N->getOperand(0).hasOneUse() &&
   6369       canLoadStoreByteSwapped(N->getValueType(0))) {
   6370       SDValue Load = N->getOperand(0);
   6371       LoadSDNode *LD = cast<LoadSDNode>(Load);
   6372 
   6373       // Create the byte-swapping load.
   6374       SDValue Ops[] = {
   6375         LD->getChain(),    // Chain
   6376         LD->getBasePtr()   // Ptr
   6377       };
   6378       EVT LoadVT = N->getValueType(0);
   6379       if (LoadVT == MVT::i16)
   6380         LoadVT = MVT::i32;
   6381       SDValue BSLoad =
   6382         DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
   6383                                 DAG.getVTList(LoadVT, MVT::Other),
   6384                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
   6385 
   6386       // If this is an i16 load, insert the truncate.
   6387       SDValue ResVal = BSLoad;
   6388       if (N->getValueType(0) == MVT::i16)
   6389         ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
   6390 
   6391       // First, combine the bswap away.  This makes the value produced by the
   6392       // load dead.
   6393       DCI.CombineTo(N, ResVal);
   6394 
   6395       // Next, combine the load away, we give it a bogus result value but a real
   6396       // chain result.  The result value is dead because the bswap is dead.
   6397       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
   6398 
   6399       // Return N so it doesn't get rechecked!
   6400       return SDValue(N, 0);
   6401     }
   6402 
   6403   // Look through bitcasts that retain the number of vector elements.
   6404   SDValue Op = N->getOperand(0);
   6405   if (Op.getOpcode() == ISD::BITCAST &&
   6406       Op.getValueType().isVector() &&
   6407       Op.getOperand(0).getValueType().isVector() &&
   6408       Op.getValueType().getVectorNumElements() ==
   6409       Op.getOperand(0).getValueType().getVectorNumElements())
   6410     Op = Op.getOperand(0);
   6411 
   6412   // Push BSWAP into a vector insertion if at least one side then simplifies.
   6413   if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
   6414     SDValue Vec = Op.getOperand(0);
   6415     SDValue Elt = Op.getOperand(1);
   6416     SDValue Idx = Op.getOperand(2);
   6417 
   6418     if (DAG.isConstantIntBuildVectorOrConstantInt(Vec) ||
   6419         Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
   6420         DAG.isConstantIntBuildVectorOrConstantInt(Elt) ||
   6421         Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
   6422         (canLoadStoreByteSwapped(N->getValueType(0)) &&
   6423          ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
   6424       EVT VecVT = N->getValueType(0);
   6425       EVT EltVT = N->getValueType(0).getVectorElementType();
   6426       if (VecVT != Vec.getValueType()) {
   6427         Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
   6428         DCI.AddToWorklist(Vec.getNode());
   6429       }
   6430       if (EltVT != Elt.getValueType()) {
   6431         Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
   6432         DCI.AddToWorklist(Elt.getNode());
   6433       }
   6434       Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
   6435       DCI.AddToWorklist(Vec.getNode());
   6436       Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
   6437       DCI.AddToWorklist(Elt.getNode());
   6438       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
   6439                          Vec, Elt, Idx);
   6440     }
   6441   }
   6442 
   6443   // Push BSWAP into a vector shuffle if at least one side then simplifies.
   6444   ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
   6445   if (SV && Op.hasOneUse()) {
   6446     SDValue Op0 = Op.getOperand(0);
   6447     SDValue Op1 = Op.getOperand(1);
   6448 
   6449     if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
   6450         Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
   6451         DAG.isConstantIntBuildVectorOrConstantInt(Op1) ||
   6452         Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
   6453       EVT VecVT = N->getValueType(0);
   6454       if (VecVT != Op0.getValueType()) {
   6455         Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
   6456         DCI.AddToWorklist(Op0.getNode());
   6457       }
   6458       if (VecVT != Op1.getValueType()) {
   6459         Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
   6460         DCI.AddToWorklist(Op1.getNode());
   6461       }
   6462       Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
   6463       DCI.AddToWorklist(Op0.getNode());
   6464       Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
   6465       DCI.AddToWorklist(Op1.getNode());
   6466       return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
   6467     }
   6468   }
   6469 
   6470   return SDValue();
   6471 }
   6472 
   6473 static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask) {
   6474   // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
   6475   // set by the CCReg instruction using the CCValid / CCMask masks,
   6476   // If the CCReg instruction is itself a ICMP testing the condition
   6477   // code set by some other instruction, see whether we can directly
   6478   // use that condition code.
   6479 
   6480   // Verify that we have an ICMP against some constant.
   6481   if (CCValid != SystemZ::CCMASK_ICMP)
   6482     return false;
   6483   auto *ICmp = CCReg.getNode();
   6484   if (ICmp->getOpcode() != SystemZISD::ICMP)
   6485     return false;
   6486   auto *CompareLHS = ICmp->getOperand(0).getNode();
   6487   auto *CompareRHS = dyn_cast<ConstantSDNode>(ICmp->getOperand(1));
   6488   if (!CompareRHS)
   6489     return false;
   6490 
   6491   // Optimize the case where CompareLHS is a SELECT_CCMASK.
   6492   if (CompareLHS->getOpcode() == SystemZISD::SELECT_CCMASK) {
   6493     // Verify that we have an appropriate mask for a EQ or NE comparison.
   6494     bool Invert = false;
   6495     if (CCMask == SystemZ::CCMASK_CMP_NE)
   6496       Invert = !Invert;
   6497     else if (CCMask != SystemZ::CCMASK_CMP_EQ)
   6498       return false;
   6499 
   6500     // Verify that the ICMP compares against one of select values.
   6501     auto *TrueVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(0));
   6502     if (!TrueVal)
   6503       return false;
   6504     auto *FalseVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1));
   6505     if (!FalseVal)
   6506       return false;
   6507     if (CompareRHS->getZExtValue() == FalseVal->getZExtValue())
   6508       Invert = !Invert;
   6509     else if (CompareRHS->getZExtValue() != TrueVal->getZExtValue())
   6510       return false;
   6511 
   6512     // Compute the effective CC mask for the new branch or select.
   6513     auto *NewCCValid = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(2));
   6514     auto *NewCCMask = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(3));
   6515     if (!NewCCValid || !NewCCMask)
   6516       return false;
   6517     CCValid = NewCCValid->getZExtValue();
   6518     CCMask = NewCCMask->getZExtValue();
   6519     if (Invert)
   6520       CCMask ^= CCValid;
   6521 
   6522     // Return the updated CCReg link.
   6523     CCReg = CompareLHS->getOperand(4);
   6524     return true;
   6525   }
   6526 
   6527   // Optimize the case where CompareRHS is (SRA (SHL (IPM))).
   6528   if (CompareLHS->getOpcode() == ISD::SRA) {
   6529     auto *SRACount = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1));
   6530     if (!SRACount || SRACount->getZExtValue() != 30)
   6531       return false;
   6532     auto *SHL = CompareLHS->getOperand(0).getNode();
   6533     if (SHL->getOpcode() != ISD::SHL)
   6534       return false;
   6535     auto *SHLCount = dyn_cast<ConstantSDNode>(SHL->getOperand(1));
   6536     if (!SHLCount || SHLCount->getZExtValue() != 30 - SystemZ::IPM_CC)
   6537       return false;
   6538     auto *IPM = SHL->getOperand(0).getNode();
   6539     if (IPM->getOpcode() != SystemZISD::IPM)
   6540       return false;
   6541 
   6542     // Avoid introducing CC spills (because SRA would clobber CC).
   6543     if (!CompareLHS->hasOneUse())
   6544       return false;
   6545     // Verify that the ICMP compares against zero.
   6546     if (CompareRHS->getZExtValue() != 0)
   6547       return false;
   6548 
   6549     // Compute the effective CC mask for the new branch or select.
   6550     CCMask = SystemZ::reverseCCMask(CCMask);
   6551 
   6552     // Return the updated CCReg link.
   6553     CCReg = IPM->getOperand(0);
   6554     return true;
   6555   }
   6556 
   6557   return false;
   6558 }
   6559 
   6560 SDValue SystemZTargetLowering::combineBR_CCMASK(
   6561     SDNode *N, DAGCombinerInfo &DCI) const {
   6562   SelectionDAG &DAG = DCI.DAG;
   6563 
   6564   // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
   6565   auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
   6566   auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
   6567   if (!CCValid || !CCMask)
   6568     return SDValue();
   6569 
   6570   int CCValidVal = CCValid->getZExtValue();
   6571   int CCMaskVal = CCMask->getZExtValue();
   6572   SDValue Chain = N->getOperand(0);
   6573   SDValue CCReg = N->getOperand(4);
   6574 
   6575   if (combineCCMask(CCReg, CCValidVal, CCMaskVal))
   6576     return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
   6577                        Chain,
   6578                        DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
   6579                        DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
   6580                        N->getOperand(3), CCReg);
   6581   return SDValue();
   6582 }
   6583 
   6584 SDValue SystemZTargetLowering::combineSELECT_CCMASK(
   6585     SDNode *N, DAGCombinerInfo &DCI) const {
   6586   SelectionDAG &DAG = DCI.DAG;
   6587 
   6588   // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
   6589   auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
   6590   auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
   6591   if (!CCValid || !CCMask)
   6592     return SDValue();
   6593 
   6594   int CCValidVal = CCValid->getZExtValue();
   6595   int CCMaskVal = CCMask->getZExtValue();
   6596   SDValue CCReg = N->getOperand(4);
   6597 
   6598   if (combineCCMask(CCReg, CCValidVal, CCMaskVal))
   6599     return DAG.getNode(SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0),
   6600                        N->getOperand(0), N->getOperand(1),
   6601                        DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
   6602                        DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
   6603                        CCReg);
   6604   return SDValue();
   6605 }
   6606 
   6607 
   6608 SDValue SystemZTargetLowering::combineGET_CCMASK(
   6609     SDNode *N, DAGCombinerInfo &DCI) const {
   6610 
   6611   // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
   6612   auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
   6613   auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
   6614   if (!CCValid || !CCMask)
   6615     return SDValue();
   6616   int CCValidVal = CCValid->getZExtValue();
   6617   int CCMaskVal = CCMask->getZExtValue();
   6618 
   6619   SDValue Select = N->getOperand(0);
   6620   if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
   6621     return SDValue();
   6622 
   6623   auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
   6624   auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
   6625   if (!SelectCCValid || !SelectCCMask)
   6626     return SDValue();
   6627   int SelectCCValidVal = SelectCCValid->getZExtValue();
   6628   int SelectCCMaskVal = SelectCCMask->getZExtValue();
   6629 
   6630   auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
   6631   auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
   6632   if (!TrueVal || !FalseVal)
   6633     return SDValue();
   6634   if (TrueVal->getZExtValue() != 0 && FalseVal->getZExtValue() == 0)
   6635     ;
   6636   else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() != 0)
   6637     SelectCCMaskVal ^= SelectCCValidVal;
   6638   else
   6639     return SDValue();
   6640 
   6641   if (SelectCCValidVal & ~CCValidVal)
   6642     return SDValue();
   6643   if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
   6644     return SDValue();
   6645 
   6646   return Select->getOperand(4);
   6647 }
   6648 
   6649 SDValue SystemZTargetLowering::combineIntDIVREM(
   6650     SDNode *N, DAGCombinerInfo &DCI) const {
   6651   SelectionDAG &DAG = DCI.DAG;
   6652   EVT VT = N->getValueType(0);
   6653   // In the case where the divisor is a vector of constants a cheaper
   6654   // sequence of instructions can replace the divide. BuildSDIV is called to
   6655   // do this during DAG combining, but it only succeeds when it can build a
   6656   // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
   6657   // since it is not Legal but Custom it can only happen before
   6658   // legalization. Therefore we must scalarize this early before Combine
   6659   // 1. For widened vectors, this is already the result of type legalization.
   6660   if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
   6661       DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
   6662     return DAG.UnrollVectorOp(N);
   6663   return SDValue();
   6664 }
   6665 
   6666 SDValue SystemZTargetLowering::combineINTRINSIC(
   6667     SDNode *N, DAGCombinerInfo &DCI) const {
   6668   SelectionDAG &DAG = DCI.DAG;
   6669 
   6670   unsigned Id = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
   6671   switch (Id) {
   6672   // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
   6673   // or larger is simply a vector load.
   6674   case Intrinsic::s390_vll:
   6675   case Intrinsic::s390_vlrl:
   6676     if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
   6677       if (C->getZExtValue() >= 15)
   6678         return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
   6679                            N->getOperand(3), MachinePointerInfo());
   6680     break;
   6681   // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
   6682   case Intrinsic::s390_vstl:
   6683   case Intrinsic::s390_vstrl:
   6684     if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
   6685       if (C->getZExtValue() >= 15)
   6686         return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
   6687                             N->getOperand(4), MachinePointerInfo());
   6688     break;
   6689   }
   6690 
   6691   return SDValue();
   6692 }
   6693 
   6694 SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
   6695   if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
   6696     return N->getOperand(0);
   6697   return N;
   6698 }
   6699 
   6700 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
   6701                                                  DAGCombinerInfo &DCI) const {
   6702   switch(N->getOpcode()) {
   6703   default: break;
   6704   case ISD::ZERO_EXTEND:        return combineZERO_EXTEND(N, DCI);
   6705   case ISD::SIGN_EXTEND:        return combineSIGN_EXTEND(N, DCI);
   6706   case ISD::SIGN_EXTEND_INREG:  return combineSIGN_EXTEND_INREG(N, DCI);
   6707   case SystemZISD::MERGE_HIGH:
   6708   case SystemZISD::MERGE_LOW:   return combineMERGE(N, DCI);
   6709   case ISD::LOAD:               return combineLOAD(N, DCI);
   6710   case ISD::STORE:              return combineSTORE(N, DCI);
   6711   case ISD::VECTOR_SHUFFLE:     return combineVECTOR_SHUFFLE(N, DCI);
   6712   case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
   6713   case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
   6714   case ISD::STRICT_FP_ROUND:
   6715   case ISD::FP_ROUND:           return combineFP_ROUND(N, DCI);
   6716   case ISD::STRICT_FP_EXTEND:
   6717   case ISD::FP_EXTEND:          return combineFP_EXTEND(N, DCI);
   6718   case ISD::SINT_TO_FP:
   6719   case ISD::UINT_TO_FP:         return combineINT_TO_FP(N, DCI);
   6720   case ISD::BSWAP:              return combineBSWAP(N, DCI);
   6721   case SystemZISD::BR_CCMASK:   return combineBR_CCMASK(N, DCI);
   6722   case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
   6723   case SystemZISD::GET_CCMASK:  return combineGET_CCMASK(N, DCI);
   6724   case ISD::SDIV:
   6725   case ISD::UDIV:
   6726   case ISD::SREM:
   6727   case ISD::UREM:               return combineIntDIVREM(N, DCI);
   6728   case ISD::INTRINSIC_W_CHAIN:
   6729   case ISD::INTRINSIC_VOID:     return combineINTRINSIC(N, DCI);
   6730   }
   6731 
   6732   return SDValue();
   6733 }
   6734 
   6735 // Return the demanded elements for the OpNo source operand of Op. DemandedElts
   6736 // are for Op.
   6737 static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
   6738                                     unsigned OpNo) {
   6739   EVT VT = Op.getValueType();
   6740   unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
   6741   APInt SrcDemE;
   6742   unsigned Opcode = Op.getOpcode();
   6743   if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
   6744     unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   6745     switch (Id) {
   6746     case Intrinsic::s390_vpksh:   // PACKS
   6747     case Intrinsic::s390_vpksf:
   6748     case Intrinsic::s390_vpksg:
   6749     case Intrinsic::s390_vpkshs:  // PACKS_CC
   6750     case Intrinsic::s390_vpksfs:
   6751     case Intrinsic::s390_vpksgs:
   6752     case Intrinsic::s390_vpklsh:  // PACKLS
   6753     case Intrinsic::s390_vpklsf:
   6754     case Intrinsic::s390_vpklsg:
   6755     case Intrinsic::s390_vpklshs: // PACKLS_CC
   6756     case Intrinsic::s390_vpklsfs:
   6757     case Intrinsic::s390_vpklsgs:
   6758       // VECTOR PACK truncates the elements of two source vectors into one.
   6759       SrcDemE = DemandedElts;
   6760       if (OpNo == 2)
   6761         SrcDemE.lshrInPlace(NumElts / 2);
   6762       SrcDemE = SrcDemE.trunc(NumElts / 2);
   6763       break;
   6764       // VECTOR UNPACK extends half the elements of the source vector.
   6765     case Intrinsic::s390_vuphb:  // VECTOR UNPACK HIGH
   6766     case Intrinsic::s390_vuphh:
   6767     case Intrinsic::s390_vuphf:
   6768     case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
   6769     case Intrinsic::s390_vuplhh:
   6770     case Intrinsic::s390_vuplhf:
   6771       SrcDemE = APInt(NumElts * 2, 0);
   6772       SrcDemE.insertBits(DemandedElts, 0);
   6773       break;
   6774     case Intrinsic::s390_vuplb:  // VECTOR UNPACK LOW
   6775     case Intrinsic::s390_vuplhw:
   6776     case Intrinsic::s390_vuplf:
   6777     case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
   6778     case Intrinsic::s390_vupllh:
   6779     case Intrinsic::s390_vupllf:
   6780       SrcDemE = APInt(NumElts * 2, 0);
   6781       SrcDemE.insertBits(DemandedElts, NumElts);
   6782       break;
   6783     case Intrinsic::s390_vpdi: {
   6784       // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
   6785       SrcDemE = APInt(NumElts, 0);
   6786       if (!DemandedElts[OpNo - 1])
   6787         break;
   6788       unsigned Mask = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
   6789       unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
   6790       // Demand input element 0 or 1, given by the mask bit value.
   6791       SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
   6792       break;
   6793     }
   6794     case Intrinsic::s390_vsldb: {
   6795       // VECTOR SHIFT LEFT DOUBLE BY BYTE
   6796       assert(VT == MVT::v16i8 && "Unexpected type.");
   6797       unsigned FirstIdx = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
   6798       assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
   6799       unsigned NumSrc0Els = 16 - FirstIdx;
   6800       SrcDemE = APInt(NumElts, 0);
   6801       if (OpNo == 1) {
   6802         APInt DemEls = DemandedElts.trunc(NumSrc0Els);
   6803         SrcDemE.insertBits(DemEls, FirstIdx);
   6804       } else {
   6805         APInt DemEls = DemandedElts.lshr(NumSrc0Els);
   6806         SrcDemE.insertBits(DemEls, 0);
   6807       }
   6808       break;
   6809     }
   6810     case Intrinsic::s390_vperm:
   6811       SrcDemE = APInt(NumElts, 1);
   6812       break;
   6813     default:
   6814       llvm_unreachable("Unhandled intrinsic.");
   6815       break;
   6816     }
   6817   } else {
   6818     switch (Opcode) {
   6819     case SystemZISD::JOIN_DWORDS:
   6820       // Scalar operand.
   6821       SrcDemE = APInt(1, 1);
   6822       break;
   6823     case SystemZISD::SELECT_CCMASK:
   6824       SrcDemE = DemandedElts;
   6825       break;
   6826     default:
   6827       llvm_unreachable("Unhandled opcode.");
   6828       break;
   6829     }
   6830   }
   6831   return SrcDemE;
   6832 }
   6833 
   6834 static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known,
   6835                                   const APInt &DemandedElts,
   6836                                   const SelectionDAG &DAG, unsigned Depth,
   6837                                   unsigned OpNo) {
   6838   APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
   6839   APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
   6840   KnownBits LHSKnown =
   6841       DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
   6842   KnownBits RHSKnown =
   6843       DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
   6844   Known = KnownBits::commonBits(LHSKnown, RHSKnown);
   6845 }
   6846 
   6847 void
   6848 SystemZTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
   6849                                                      KnownBits &Known,
   6850                                                      const APInt &DemandedElts,
   6851                                                      const SelectionDAG &DAG,
   6852                                                      unsigned Depth) const {
   6853   Known.resetAll();
   6854 
   6855   // Intrinsic CC result is returned in the two low bits.
   6856   unsigned tmp0, tmp1; // not used
   6857   if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, tmp0, tmp1)) {
   6858     Known.Zero.setBitsFrom(2);
   6859     return;
   6860   }
   6861   EVT VT = Op.getValueType();
   6862   if (Op.getResNo() != 0 || VT == MVT::Untyped)
   6863     return;
   6864   assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
   6865           "KnownBits does not match VT in bitwidth");
   6866   assert ((!VT.isVector() ||
   6867            (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
   6868           "DemandedElts does not match VT number of elements");
   6869   unsigned BitWidth = Known.getBitWidth();
   6870   unsigned Opcode = Op.getOpcode();
   6871   if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
   6872     bool IsLogical = false;
   6873     unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   6874     switch (Id) {
   6875     case Intrinsic::s390_vpksh:   // PACKS
   6876     case Intrinsic::s390_vpksf:
   6877     case Intrinsic::s390_vpksg:
   6878     case Intrinsic::s390_vpkshs:  // PACKS_CC
   6879     case Intrinsic::s390_vpksfs:
   6880     case Intrinsic::s390_vpksgs:
   6881     case Intrinsic::s390_vpklsh:  // PACKLS
   6882     case Intrinsic::s390_vpklsf:
   6883     case Intrinsic::s390_vpklsg:
   6884     case Intrinsic::s390_vpklshs: // PACKLS_CC
   6885     case Intrinsic::s390_vpklsfs:
   6886     case Intrinsic::s390_vpklsgs:
   6887     case Intrinsic::s390_vpdi:
   6888     case Intrinsic::s390_vsldb:
   6889     case Intrinsic::s390_vperm:
   6890       computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
   6891       break;
   6892     case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
   6893     case Intrinsic::s390_vuplhh:
   6894     case Intrinsic::s390_vuplhf:
   6895     case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
   6896     case Intrinsic::s390_vupllh:
   6897     case Intrinsic::s390_vupllf:
   6898       IsLogical = true;
   6899       LLVM_FALLTHROUGH;
   6900     case Intrinsic::s390_vuphb:  // VECTOR UNPACK HIGH
   6901     case Intrinsic::s390_vuphh:
   6902     case Intrinsic::s390_vuphf:
   6903     case Intrinsic::s390_vuplb:  // VECTOR UNPACK LOW
   6904     case Intrinsic::s390_vuplhw:
   6905     case Intrinsic::s390_vuplf: {
   6906       SDValue SrcOp = Op.getOperand(1);
   6907       APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
   6908       Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
   6909       if (IsLogical) {
   6910         Known = Known.zext(BitWidth);
   6911       } else
   6912         Known = Known.sext(BitWidth);
   6913       break;
   6914     }
   6915     default:
   6916       break;
   6917     }
   6918   } else {
   6919     switch (Opcode) {
   6920     case SystemZISD::JOIN_DWORDS:
   6921     case SystemZISD::SELECT_CCMASK:
   6922       computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
   6923       break;
   6924     case SystemZISD::REPLICATE: {
   6925       SDValue SrcOp = Op.getOperand(0);
   6926       Known = DAG.computeKnownBits(SrcOp, Depth + 1);
   6927       if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
   6928         Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
   6929       break;
   6930     }
   6931     default:
   6932       break;
   6933     }
   6934   }
   6935 
   6936   // Known has the width of the source operand(s). Adjust if needed to match
   6937   // the passed bitwidth.
   6938   if (Known.getBitWidth() != BitWidth)
   6939     Known = Known.anyextOrTrunc(BitWidth);
   6940 }
   6941 
   6942 static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
   6943                                         const SelectionDAG &DAG, unsigned Depth,
   6944                                         unsigned OpNo) {
   6945   APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
   6946   unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
   6947   if (LHS == 1) return 1; // Early out.
   6948   APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
   6949   unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
   6950   if (RHS == 1) return 1; // Early out.
   6951   unsigned Common = std::min(LHS, RHS);
   6952   unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
   6953   EVT VT = Op.getValueType();
   6954   unsigned VTBits = VT.getScalarSizeInBits();
   6955   if (SrcBitWidth > VTBits) { // PACK
   6956     unsigned SrcExtraBits = SrcBitWidth - VTBits;
   6957     if (Common > SrcExtraBits)
   6958       return (Common - SrcExtraBits);
   6959     return 1;
   6960   }
   6961   assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
   6962   return Common;
   6963 }
   6964 
   6965 unsigned
   6966 SystemZTargetLowering::ComputeNumSignBitsForTargetNode(
   6967     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
   6968     unsigned Depth) const {
   6969   if (Op.getResNo() != 0)
   6970     return 1;
   6971   unsigned Opcode = Op.getOpcode();
   6972   if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
   6973     unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   6974     switch (Id) {
   6975     case Intrinsic::s390_vpksh:   // PACKS
   6976     case Intrinsic::s390_vpksf:
   6977     case Intrinsic::s390_vpksg:
   6978     case Intrinsic::s390_vpkshs:  // PACKS_CC
   6979     case Intrinsic::s390_vpksfs:
   6980     case Intrinsic::s390_vpksgs:
   6981     case Intrinsic::s390_vpklsh:  // PACKLS
   6982     case Intrinsic::s390_vpklsf:
   6983     case Intrinsic::s390_vpklsg:
   6984     case Intrinsic::s390_vpklshs: // PACKLS_CC
   6985     case Intrinsic::s390_vpklsfs:
   6986     case Intrinsic::s390_vpklsgs:
   6987     case Intrinsic::s390_vpdi:
   6988     case Intrinsic::s390_vsldb:
   6989     case Intrinsic::s390_vperm:
   6990       return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
   6991     case Intrinsic::s390_vuphb:  // VECTOR UNPACK HIGH
   6992     case Intrinsic::s390_vuphh:
   6993     case Intrinsic::s390_vuphf:
   6994     case Intrinsic::s390_vuplb:  // VECTOR UNPACK LOW
   6995     case Intrinsic::s390_vuplhw:
   6996     case Intrinsic::s390_vuplf: {
   6997       SDValue PackedOp = Op.getOperand(1);
   6998       APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
   6999       unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
   7000       EVT VT = Op.getValueType();
   7001       unsigned VTBits = VT.getScalarSizeInBits();
   7002       Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
   7003       return Tmp;
   7004     }
   7005     default:
   7006       break;
   7007     }
   7008   } else {
   7009     switch (Opcode) {
   7010     case SystemZISD::SELECT_CCMASK:
   7011       return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
   7012     default:
   7013       break;
   7014     }
   7015   }
   7016 
   7017   return 1;
   7018 }
   7019 
   7020 unsigned
   7021 SystemZTargetLowering::getStackProbeSize(MachineFunction &MF) const {
   7022   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
   7023   unsigned StackAlign = TFI->getStackAlignment();
   7024   assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
   7025          "Unexpected stack alignment");
   7026   // The default stack probe size is 4096 if the function has no
   7027   // stack-probe-size attribute.
   7028   unsigned StackProbeSize = 4096;
   7029   const Function &Fn = MF.getFunction();
   7030   if (Fn.hasFnAttribute("stack-probe-size"))
   7031     Fn.getFnAttribute("stack-probe-size")
   7032         .getValueAsString()
   7033         .getAsInteger(0, StackProbeSize);
   7034   // Round down to the stack alignment.
   7035   StackProbeSize &= ~(StackAlign - 1);
   7036   return StackProbeSize ? StackProbeSize : StackAlign;
   7037 }
   7038 
   7039 //===----------------------------------------------------------------------===//
   7040 // Custom insertion
   7041 //===----------------------------------------------------------------------===//
   7042 
   7043 // Force base value Base into a register before MI.  Return the register.
   7044 static Register forceReg(MachineInstr &MI, MachineOperand &Base,
   7045                          const SystemZInstrInfo *TII) {
   7046   if (Base.isReg())
   7047     return Base.getReg();
   7048 
   7049   MachineBasicBlock *MBB = MI.getParent();
   7050   MachineFunction &MF = *MBB->getParent();
   7051   MachineRegisterInfo &MRI = MF.getRegInfo();
   7052 
   7053   Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
   7054   BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
   7055       .add(Base)
   7056       .addImm(0)
   7057       .addReg(0);
   7058   return Reg;
   7059 }
   7060 
   7061 // The CC operand of MI might be missing a kill marker because there
   7062 // were multiple uses of CC, and ISel didn't know which to mark.
   7063 // Figure out whether MI should have had a kill marker.
   7064 static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB) {
   7065   // Scan forward through BB for a use/def of CC.
   7066   MachineBasicBlock::iterator miI(std::next(MachineBasicBlock::iterator(MI)));
   7067   for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
   7068     const MachineInstr& mi = *miI;
   7069     if (mi.readsRegister(SystemZ::CC))
   7070       return false;
   7071     if (mi.definesRegister(SystemZ::CC))
   7072       break; // Should have kill-flag - update below.
   7073   }
   7074 
   7075   // If we hit the end of the block, check whether CC is live into a
   7076   // successor.
   7077   if (miI == MBB->end()) {
   7078     for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)
   7079       if ((*SI)->isLiveIn(SystemZ::CC))
   7080         return false;
   7081   }
   7082 
   7083   return true;
   7084 }
   7085 
   7086 // Return true if it is OK for this Select pseudo-opcode to be cascaded
   7087 // together with other Select pseudo-opcodes into a single basic-block with
   7088 // a conditional jump around it.
   7089 static bool isSelectPseudo(MachineInstr &MI) {
   7090   switch (MI.getOpcode()) {
   7091   case SystemZ::Select32:
   7092   case SystemZ::Select64:
   7093   case SystemZ::SelectF32:
   7094   case SystemZ::SelectF64:
   7095   case SystemZ::SelectF128:
   7096   case SystemZ::SelectVR32:
   7097   case SystemZ::SelectVR64:
   7098   case SystemZ::SelectVR128:
   7099     return true;
   7100 
   7101   default:
   7102     return false;
   7103   }
   7104 }
   7105 
   7106 // Helper function, which inserts PHI functions into SinkMBB:
   7107 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
   7108 // where %FalseValue(i) and %TrueValue(i) are taken from Selects.
   7109 static void createPHIsForSelects(SmallVector<MachineInstr*, 8> &Selects,
   7110                                  MachineBasicBlock *TrueMBB,
   7111                                  MachineBasicBlock *FalseMBB,
   7112                                  MachineBasicBlock *SinkMBB) {
   7113   MachineFunction *MF = TrueMBB->getParent();
   7114   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
   7115 
   7116   MachineInstr *FirstMI = Selects.front();
   7117   unsigned CCValid = FirstMI->getOperand(3).getImm();
   7118   unsigned CCMask = FirstMI->getOperand(4).getImm();
   7119 
   7120   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
   7121 
   7122   // As we are creating the PHIs, we have to be careful if there is more than
   7123   // one.  Later Selects may reference the results of earlier Selects, but later
   7124   // PHIs have to reference the individual true/false inputs from earlier PHIs.
   7125   // That also means that PHI construction must work forward from earlier to
   7126   // later, and that the code must maintain a mapping from earlier PHI's
   7127   // destination registers, and the registers that went into the PHI.
   7128   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
   7129 
   7130   for (auto MI : Selects) {
   7131     Register DestReg = MI->getOperand(0).getReg();
   7132     Register TrueReg = MI->getOperand(1).getReg();
   7133     Register FalseReg = MI->getOperand(2).getReg();
   7134 
   7135     // If this Select we are generating is the opposite condition from
   7136     // the jump we generated, then we have to swap the operands for the
   7137     // PHI that is going to be generated.
   7138     if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
   7139       std::swap(TrueReg, FalseReg);
   7140 
   7141     if (RegRewriteTable.find(TrueReg) != RegRewriteTable.end())
   7142       TrueReg = RegRewriteTable[TrueReg].first;
   7143 
   7144     if (RegRewriteTable.find(FalseReg) != RegRewriteTable.end())
   7145       FalseReg = RegRewriteTable[FalseReg].second;
   7146 
   7147     DebugLoc DL = MI->getDebugLoc();
   7148     BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
   7149       .addReg(TrueReg).addMBB(TrueMBB)
   7150       .addReg(FalseReg).addMBB(FalseMBB);
   7151 
   7152     // Add this PHI to the rewrite table.
   7153     RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
   7154   }
   7155 
   7156   MF->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
   7157 }
   7158 
   7159 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
   7160 MachineBasicBlock *
   7161 SystemZTargetLowering::emitSelect(MachineInstr &MI,
   7162                                   MachineBasicBlock *MBB) const {
   7163   assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
   7164   const SystemZInstrInfo *TII =
   7165       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7166 
   7167   unsigned CCValid = MI.getOperand(3).getImm();
   7168   unsigned CCMask = MI.getOperand(4).getImm();
   7169 
   7170   // If we have a sequence of Select* pseudo instructions using the
   7171   // same condition code value, we want to expand all of them into
   7172   // a single pair of basic blocks using the same condition.
   7173   SmallVector<MachineInstr*, 8> Selects;
   7174   SmallVector<MachineInstr*, 8> DbgValues;
   7175   Selects.push_back(&MI);
   7176   unsigned Count = 0;
   7177   for (MachineBasicBlock::iterator NextMIIt =
   7178          std::next(MachineBasicBlock::iterator(MI));
   7179        NextMIIt != MBB->end(); ++NextMIIt) {
   7180     if (isSelectPseudo(*NextMIIt)) {
   7181       assert(NextMIIt->getOperand(3).getImm() == CCValid &&
   7182              "Bad CCValid operands since CC was not redefined.");
   7183       if (NextMIIt->getOperand(4).getImm() == CCMask ||
   7184           NextMIIt->getOperand(4).getImm() == (CCValid ^ CCMask)) {
   7185         Selects.push_back(&*NextMIIt);
   7186         continue;
   7187       }
   7188       break;
   7189     }
   7190     if (NextMIIt->definesRegister(SystemZ::CC) ||
   7191         NextMIIt->usesCustomInsertionHook())
   7192       break;
   7193     bool User = false;
   7194     for (auto SelMI : Selects)
   7195       if (NextMIIt->readsVirtualRegister(SelMI->getOperand(0).getReg())) {
   7196         User = true;
   7197         break;
   7198       }
   7199     if (NextMIIt->isDebugInstr()) {
   7200       if (User) {
   7201         assert(NextMIIt->isDebugValue() && "Unhandled debug opcode.");
   7202         DbgValues.push_back(&*NextMIIt);
   7203       }
   7204     }
   7205     else if (User || ++Count > 20)
   7206       break;
   7207   }
   7208 
   7209   MachineInstr *LastMI = Selects.back();
   7210   bool CCKilled =
   7211       (LastMI->killsRegister(SystemZ::CC) || checkCCKill(*LastMI, MBB));
   7212   MachineBasicBlock *StartMBB = MBB;
   7213   MachineBasicBlock *JoinMBB  = SystemZ::splitBlockAfter(LastMI, MBB);
   7214   MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
   7215 
   7216   // Unless CC was killed in the last Select instruction, mark it as
   7217   // live-in to both FalseMBB and JoinMBB.
   7218   if (!CCKilled) {
   7219     FalseMBB->addLiveIn(SystemZ::CC);
   7220     JoinMBB->addLiveIn(SystemZ::CC);
   7221   }
   7222 
   7223   //  StartMBB:
   7224   //   BRC CCMask, JoinMBB
   7225   //   # fallthrough to FalseMBB
   7226   MBB = StartMBB;
   7227   BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
   7228     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
   7229   MBB->addSuccessor(JoinMBB);
   7230   MBB->addSuccessor(FalseMBB);
   7231 
   7232   //  FalseMBB:
   7233   //   # fallthrough to JoinMBB
   7234   MBB = FalseMBB;
   7235   MBB->addSuccessor(JoinMBB);
   7236 
   7237   //  JoinMBB:
   7238   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
   7239   //  ...
   7240   MBB = JoinMBB;
   7241   createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
   7242   for (auto SelMI : Selects)
   7243     SelMI->eraseFromParent();
   7244 
   7245   MachineBasicBlock::iterator InsertPos = MBB->getFirstNonPHI();
   7246   for (auto DbgMI : DbgValues)
   7247     MBB->splice(InsertPos, StartMBB, DbgMI);
   7248 
   7249   return JoinMBB;
   7250 }
   7251 
   7252 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
   7253 // StoreOpcode is the store to use and Invert says whether the store should
   7254 // happen when the condition is false rather than true.  If a STORE ON
   7255 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
   7256 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
   7257                                                         MachineBasicBlock *MBB,
   7258                                                         unsigned StoreOpcode,
   7259                                                         unsigned STOCOpcode,
   7260                                                         bool Invert) const {
   7261   const SystemZInstrInfo *TII =
   7262       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7263 
   7264   Register SrcReg = MI.getOperand(0).getReg();
   7265   MachineOperand Base = MI.getOperand(1);
   7266   int64_t Disp = MI.getOperand(2).getImm();
   7267   Register IndexReg = MI.getOperand(3).getReg();
   7268   unsigned CCValid = MI.getOperand(4).getImm();
   7269   unsigned CCMask = MI.getOperand(5).getImm();
   7270   DebugLoc DL = MI.getDebugLoc();
   7271 
   7272   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
   7273 
   7274   // ISel pattern matching also adds a load memory operand of the same
   7275   // address, so take special care to find the storing memory operand.
   7276   MachineMemOperand *MMO = nullptr;
   7277   for (auto *I : MI.memoperands())
   7278     if (I->isStore()) {
   7279       MMO = I;
   7280       break;
   7281     }
   7282 
   7283   // Use STOCOpcode if possible.  We could use different store patterns in
   7284   // order to avoid matching the index register, but the performance trade-offs
   7285   // might be more complicated in that case.
   7286   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
   7287     if (Invert)
   7288       CCMask ^= CCValid;
   7289 
   7290     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
   7291       .addReg(SrcReg)
   7292       .add(Base)
   7293       .addImm(Disp)
   7294       .addImm(CCValid)
   7295       .addImm(CCMask)
   7296       .addMemOperand(MMO);
   7297 
   7298     MI.eraseFromParent();
   7299     return MBB;
   7300   }
   7301 
   7302   // Get the condition needed to branch around the store.
   7303   if (!Invert)
   7304     CCMask ^= CCValid;
   7305 
   7306   MachineBasicBlock *StartMBB = MBB;
   7307   MachineBasicBlock *JoinMBB  = SystemZ::splitBlockBefore(MI, MBB);
   7308   MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
   7309 
   7310   // Unless CC was killed in the CondStore instruction, mark it as
   7311   // live-in to both FalseMBB and JoinMBB.
   7312   if (!MI.killsRegister(SystemZ::CC) && !checkCCKill(MI, JoinMBB)) {
   7313     FalseMBB->addLiveIn(SystemZ::CC);
   7314     JoinMBB->addLiveIn(SystemZ::CC);
   7315   }
   7316 
   7317   //  StartMBB:
   7318   //   BRC CCMask, JoinMBB
   7319   //   # fallthrough to FalseMBB
   7320   MBB = StartMBB;
   7321   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7322     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
   7323   MBB->addSuccessor(JoinMBB);
   7324   MBB->addSuccessor(FalseMBB);
   7325 
   7326   //  FalseMBB:
   7327   //   store %SrcReg, %Disp(%Index,%Base)
   7328   //   # fallthrough to JoinMBB
   7329   MBB = FalseMBB;
   7330   BuildMI(MBB, DL, TII->get(StoreOpcode))
   7331       .addReg(SrcReg)
   7332       .add(Base)
   7333       .addImm(Disp)
   7334       .addReg(IndexReg)
   7335       .addMemOperand(MMO);
   7336   MBB->addSuccessor(JoinMBB);
   7337 
   7338   MI.eraseFromParent();
   7339   return JoinMBB;
   7340 }
   7341 
   7342 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
   7343 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
   7344 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
   7345 // BitSize is the width of the field in bits, or 0 if this is a partword
   7346 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
   7347 // is one of the operands.  Invert says whether the field should be
   7348 // inverted after performing BinOpcode (e.g. for NAND).
   7349 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
   7350     MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
   7351     unsigned BitSize, bool Invert) const {
   7352   MachineFunction &MF = *MBB->getParent();
   7353   const SystemZInstrInfo *TII =
   7354       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7355   MachineRegisterInfo &MRI = MF.getRegInfo();
   7356   bool IsSubWord = (BitSize < 32);
   7357 
   7358   // Extract the operands.  Base can be a register or a frame index.
   7359   // Src2 can be a register or immediate.
   7360   Register Dest = MI.getOperand(0).getReg();
   7361   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
   7362   int64_t Disp = MI.getOperand(2).getImm();
   7363   MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
   7364   Register BitShift = IsSubWord ? MI.getOperand(4).getReg() : Register();
   7365   Register NegBitShift = IsSubWord ? MI.getOperand(5).getReg() : Register();
   7366   DebugLoc DL = MI.getDebugLoc();
   7367   if (IsSubWord)
   7368     BitSize = MI.getOperand(6).getImm();
   7369 
   7370   // Subword operations use 32-bit registers.
   7371   const TargetRegisterClass *RC = (BitSize <= 32 ?
   7372                                    &SystemZ::GR32BitRegClass :
   7373                                    &SystemZ::GR64BitRegClass);
   7374   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
   7375   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
   7376 
   7377   // Get the right opcodes for the displacement.
   7378   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
   7379   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
   7380   assert(LOpcode && CSOpcode && "Displacement out of range");
   7381 
   7382   // Create virtual registers for temporary results.
   7383   Register OrigVal       = MRI.createVirtualRegister(RC);
   7384   Register OldVal        = MRI.createVirtualRegister(RC);
   7385   Register NewVal        = (BinOpcode || IsSubWord ?
   7386                             MRI.createVirtualRegister(RC) : Src2.getReg());
   7387   Register RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
   7388   Register RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
   7389 
   7390   // Insert a basic block for the main loop.
   7391   MachineBasicBlock *StartMBB = MBB;
   7392   MachineBasicBlock *DoneMBB  = SystemZ::splitBlockBefore(MI, MBB);
   7393   MachineBasicBlock *LoopMBB  = SystemZ::emitBlockAfter(StartMBB);
   7394 
   7395   //  StartMBB:
   7396   //   ...
   7397   //   %OrigVal = L Disp(%Base)
   7398   //   # fall through to LoopMMB
   7399   MBB = StartMBB;
   7400   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
   7401   MBB->addSuccessor(LoopMBB);
   7402 
   7403   //  LoopMBB:
   7404   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
   7405   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
   7406   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
   7407   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
   7408   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
   7409   //   JNE LoopMBB
   7410   //   # fall through to DoneMMB
   7411   MBB = LoopMBB;
   7412   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
   7413     .addReg(OrigVal).addMBB(StartMBB)
   7414     .addReg(Dest).addMBB(LoopMBB);
   7415   if (IsSubWord)
   7416     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
   7417       .addReg(OldVal).addReg(BitShift).addImm(0);
   7418   if (Invert) {
   7419     // Perform the operation normally and then invert every bit of the field.
   7420     Register Tmp = MRI.createVirtualRegister(RC);
   7421     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2);
   7422     if (BitSize <= 32)
   7423       // XILF with the upper BitSize bits set.
   7424       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
   7425         .addReg(Tmp).addImm(-1U << (32 - BitSize));
   7426     else {
   7427       // Use LCGR and add -1 to the result, which is more compact than
   7428       // an XILF, XILH pair.
   7429       Register Tmp2 = MRI.createVirtualRegister(RC);
   7430       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
   7431       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
   7432         .addReg(Tmp2).addImm(-1);
   7433     }
   7434   } else if (BinOpcode)
   7435     // A simply binary operation.
   7436     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
   7437         .addReg(RotatedOldVal)
   7438         .add(Src2);
   7439   else if (IsSubWord)
   7440     // Use RISBG to rotate Src2 into position and use it to replace the
   7441     // field in RotatedOldVal.
   7442     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
   7443       .addReg(RotatedOldVal).addReg(Src2.getReg())
   7444       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
   7445   if (IsSubWord)
   7446     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
   7447       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
   7448   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
   7449       .addReg(OldVal)
   7450       .addReg(NewVal)
   7451       .add(Base)
   7452       .addImm(Disp);
   7453   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7454     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
   7455   MBB->addSuccessor(LoopMBB);
   7456   MBB->addSuccessor(DoneMBB);
   7457 
   7458   MI.eraseFromParent();
   7459   return DoneMBB;
   7460 }
   7461 
   7462 // Implement EmitInstrWithCustomInserter for pseudo
   7463 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
   7464 // instruction that should be used to compare the current field with the
   7465 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
   7466 // for when the current field should be kept.  BitSize is the width of
   7467 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
   7468 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
   7469     MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
   7470     unsigned KeepOldMask, unsigned BitSize) const {
   7471   MachineFunction &MF = *MBB->getParent();
   7472   const SystemZInstrInfo *TII =
   7473       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7474   MachineRegisterInfo &MRI = MF.getRegInfo();
   7475   bool IsSubWord = (BitSize < 32);
   7476 
   7477   // Extract the operands.  Base can be a register or a frame index.
   7478   Register Dest = MI.getOperand(0).getReg();
   7479   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
   7480   int64_t Disp = MI.getOperand(2).getImm();
   7481   Register Src2 = MI.getOperand(3).getReg();
   7482   Register BitShift = (IsSubWord ? MI.getOperand(4).getReg() : Register());
   7483   Register NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : Register());
   7484   DebugLoc DL = MI.getDebugLoc();
   7485   if (IsSubWord)
   7486     BitSize = MI.getOperand(6).getImm();
   7487 
   7488   // Subword operations use 32-bit registers.
   7489   const TargetRegisterClass *RC = (BitSize <= 32 ?
   7490                                    &SystemZ::GR32BitRegClass :
   7491                                    &SystemZ::GR64BitRegClass);
   7492   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
   7493   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
   7494 
   7495   // Get the right opcodes for the displacement.
   7496   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
   7497   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
   7498   assert(LOpcode && CSOpcode && "Displacement out of range");
   7499 
   7500   // Create virtual registers for temporary results.
   7501   Register OrigVal       = MRI.createVirtualRegister(RC);
   7502   Register OldVal        = MRI.createVirtualRegister(RC);
   7503   Register NewVal        = MRI.createVirtualRegister(RC);
   7504   Register RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
   7505   Register RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
   7506   Register RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
   7507 
   7508   // Insert 3 basic blocks for the loop.
   7509   MachineBasicBlock *StartMBB  = MBB;
   7510   MachineBasicBlock *DoneMBB   = SystemZ::splitBlockBefore(MI, MBB);
   7511   MachineBasicBlock *LoopMBB   = SystemZ::emitBlockAfter(StartMBB);
   7512   MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
   7513   MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
   7514 
   7515   //  StartMBB:
   7516   //   ...
   7517   //   %OrigVal     = L Disp(%Base)
   7518   //   # fall through to LoopMMB
   7519   MBB = StartMBB;
   7520   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
   7521   MBB->addSuccessor(LoopMBB);
   7522 
   7523   //  LoopMBB:
   7524   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
   7525   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
   7526   //   CompareOpcode %RotatedOldVal, %Src2
   7527   //   BRC KeepOldMask, UpdateMBB
   7528   MBB = LoopMBB;
   7529   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
   7530     .addReg(OrigVal).addMBB(StartMBB)
   7531     .addReg(Dest).addMBB(UpdateMBB);
   7532   if (IsSubWord)
   7533     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
   7534       .addReg(OldVal).addReg(BitShift).addImm(0);
   7535   BuildMI(MBB, DL, TII->get(CompareOpcode))
   7536     .addReg(RotatedOldVal).addReg(Src2);
   7537   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7538     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
   7539   MBB->addSuccessor(UpdateMBB);
   7540   MBB->addSuccessor(UseAltMBB);
   7541 
   7542   //  UseAltMBB:
   7543   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
   7544   //   # fall through to UpdateMMB
   7545   MBB = UseAltMBB;
   7546   if (IsSubWord)
   7547     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
   7548       .addReg(RotatedOldVal).addReg(Src2)
   7549       .addImm(32).addImm(31 + BitSize).addImm(0);
   7550   MBB->addSuccessor(UpdateMBB);
   7551 
   7552   //  UpdateMBB:
   7553   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
   7554   //                        [ %RotatedAltVal, UseAltMBB ]
   7555   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
   7556   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
   7557   //   JNE LoopMBB
   7558   //   # fall through to DoneMMB
   7559   MBB = UpdateMBB;
   7560   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
   7561     .addReg(RotatedOldVal).addMBB(LoopMBB)
   7562     .addReg(RotatedAltVal).addMBB(UseAltMBB);
   7563   if (IsSubWord)
   7564     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
   7565       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
   7566   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
   7567       .addReg(OldVal)
   7568       .addReg(NewVal)
   7569       .add(Base)
   7570       .addImm(Disp);
   7571   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7572     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
   7573   MBB->addSuccessor(LoopMBB);
   7574   MBB->addSuccessor(DoneMBB);
   7575 
   7576   MI.eraseFromParent();
   7577   return DoneMBB;
   7578 }
   7579 
   7580 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
   7581 // instruction MI.
   7582 MachineBasicBlock *
   7583 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
   7584                                           MachineBasicBlock *MBB) const {
   7585   MachineFunction &MF = *MBB->getParent();
   7586   const SystemZInstrInfo *TII =
   7587       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7588   MachineRegisterInfo &MRI = MF.getRegInfo();
   7589 
   7590   // Extract the operands.  Base can be a register or a frame index.
   7591   Register Dest = MI.getOperand(0).getReg();
   7592   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
   7593   int64_t Disp = MI.getOperand(2).getImm();
   7594   Register CmpVal = MI.getOperand(3).getReg();
   7595   Register OrigSwapVal = MI.getOperand(4).getReg();
   7596   Register BitShift = MI.getOperand(5).getReg();
   7597   Register NegBitShift = MI.getOperand(6).getReg();
   7598   int64_t BitSize = MI.getOperand(7).getImm();
   7599   DebugLoc DL = MI.getDebugLoc();
   7600 
   7601   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
   7602 
   7603   // Get the right opcodes for the displacement and zero-extension.
   7604   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
   7605   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
   7606   unsigned ZExtOpcode  = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
   7607   assert(LOpcode && CSOpcode && "Displacement out of range");
   7608 
   7609   // Create virtual registers for temporary results.
   7610   Register OrigOldVal = MRI.createVirtualRegister(RC);
   7611   Register OldVal = MRI.createVirtualRegister(RC);
   7612   Register SwapVal = MRI.createVirtualRegister(RC);
   7613   Register StoreVal = MRI.createVirtualRegister(RC);
   7614   Register OldValRot = MRI.createVirtualRegister(RC);
   7615   Register RetryOldVal = MRI.createVirtualRegister(RC);
   7616   Register RetrySwapVal = MRI.createVirtualRegister(RC);
   7617 
   7618   // Insert 2 basic blocks for the loop.
   7619   MachineBasicBlock *StartMBB = MBB;
   7620   MachineBasicBlock *DoneMBB  = SystemZ::splitBlockBefore(MI, MBB);
   7621   MachineBasicBlock *LoopMBB  = SystemZ::emitBlockAfter(StartMBB);
   7622   MachineBasicBlock *SetMBB   = SystemZ::emitBlockAfter(LoopMBB);
   7623 
   7624   //  StartMBB:
   7625   //   ...
   7626   //   %OrigOldVal     = L Disp(%Base)
   7627   //   # fall through to LoopMMB
   7628   MBB = StartMBB;
   7629   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
   7630       .add(Base)
   7631       .addImm(Disp)
   7632       .addReg(0);
   7633   MBB->addSuccessor(LoopMBB);
   7634 
   7635   //  LoopMBB:
   7636   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
   7637   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
   7638   //   %OldValRot     = RLL %OldVal, BitSize(%BitShift)
   7639   //                      ^^ The low BitSize bits contain the field
   7640   //                         of interest.
   7641   //   %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
   7642   //                      ^^ Replace the upper 32-BitSize bits of the
   7643   //                         swap value with those that we loaded and rotated.
   7644   //   %Dest = LL[CH] %OldValRot
   7645   //   CR %Dest, %CmpVal
   7646   //   JNE DoneMBB
   7647   //   # Fall through to SetMBB
   7648   MBB = LoopMBB;
   7649   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
   7650     .addReg(OrigOldVal).addMBB(StartMBB)
   7651     .addReg(RetryOldVal).addMBB(SetMBB);
   7652   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
   7653     .addReg(OrigSwapVal).addMBB(StartMBB)
   7654     .addReg(RetrySwapVal).addMBB(SetMBB);
   7655   BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
   7656     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
   7657   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
   7658     .addReg(SwapVal).addReg(OldValRot).addImm(32).addImm(63 - BitSize).addImm(0);
   7659   BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
   7660     .addReg(OldValRot);
   7661   BuildMI(MBB, DL, TII->get(SystemZ::CR))
   7662     .addReg(Dest).addReg(CmpVal);
   7663   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7664     .addImm(SystemZ::CCMASK_ICMP)
   7665     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
   7666   MBB->addSuccessor(DoneMBB);
   7667   MBB->addSuccessor(SetMBB);
   7668 
   7669   //  SetMBB:
   7670   //   %StoreVal     = RLL %RetrySwapVal, -BitSize(%NegBitShift)
   7671   //                      ^^ Rotate the new field to its proper position.
   7672   //   %RetryOldVal  = CS %OldVal, %StoreVal, Disp(%Base)
   7673   //   JNE LoopMBB
   7674   //   # fall through to ExitMMB
   7675   MBB = SetMBB;
   7676   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
   7677     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
   7678   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
   7679       .addReg(OldVal)
   7680       .addReg(StoreVal)
   7681       .add(Base)
   7682       .addImm(Disp);
   7683   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7684     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
   7685   MBB->addSuccessor(LoopMBB);
   7686   MBB->addSuccessor(DoneMBB);
   7687 
   7688   // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
   7689   // to the block after the loop.  At this point, CC may have been defined
   7690   // either by the CR in LoopMBB or by the CS in SetMBB.
   7691   if (!MI.registerDefIsDead(SystemZ::CC))
   7692     DoneMBB->addLiveIn(SystemZ::CC);
   7693 
   7694   MI.eraseFromParent();
   7695   return DoneMBB;
   7696 }
   7697 
   7698 // Emit a move from two GR64s to a GR128.
   7699 MachineBasicBlock *
   7700 SystemZTargetLowering::emitPair128(MachineInstr &MI,
   7701                                    MachineBasicBlock *MBB) const {
   7702   MachineFunction &MF = *MBB->getParent();
   7703   const SystemZInstrInfo *TII =
   7704       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7705   MachineRegisterInfo &MRI = MF.getRegInfo();
   7706   DebugLoc DL = MI.getDebugLoc();
   7707 
   7708   Register Dest = MI.getOperand(0).getReg();
   7709   Register Hi = MI.getOperand(1).getReg();
   7710   Register Lo = MI.getOperand(2).getReg();
   7711   Register Tmp1 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
   7712   Register Tmp2 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
   7713 
   7714   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Tmp1);
   7715   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Tmp2)
   7716     .addReg(Tmp1).addReg(Hi).addImm(SystemZ::subreg_h64);
   7717   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
   7718     .addReg(Tmp2).addReg(Lo).addImm(SystemZ::subreg_l64);
   7719 
   7720   MI.eraseFromParent();
   7721   return MBB;
   7722 }
   7723 
   7724 // Emit an extension from a GR64 to a GR128.  ClearEven is true
   7725 // if the high register of the GR128 value must be cleared or false if
   7726 // it's "don't care".
   7727 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
   7728                                                      MachineBasicBlock *MBB,
   7729                                                      bool ClearEven) const {
   7730   MachineFunction &MF = *MBB->getParent();
   7731   const SystemZInstrInfo *TII =
   7732       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7733   MachineRegisterInfo &MRI = MF.getRegInfo();
   7734   DebugLoc DL = MI.getDebugLoc();
   7735 
   7736   Register Dest = MI.getOperand(0).getReg();
   7737   Register Src = MI.getOperand(1).getReg();
   7738   Register In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
   7739 
   7740   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
   7741   if (ClearEven) {
   7742     Register NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
   7743     Register Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
   7744 
   7745     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
   7746       .addImm(0);
   7747     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
   7748       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
   7749     In128 = NewIn128;
   7750   }
   7751   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
   7752     .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64);
   7753 
   7754   MI.eraseFromParent();
   7755   return MBB;
   7756 }
   7757 
   7758 MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper(
   7759     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
   7760   MachineFunction &MF = *MBB->getParent();
   7761   const SystemZInstrInfo *TII =
   7762       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7763   MachineRegisterInfo &MRI = MF.getRegInfo();
   7764   DebugLoc DL = MI.getDebugLoc();
   7765 
   7766   MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
   7767   uint64_t DestDisp = MI.getOperand(1).getImm();
   7768   MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2));
   7769   uint64_t SrcDisp = MI.getOperand(3).getImm();
   7770   uint64_t Length = MI.getOperand(4).getImm();
   7771 
   7772   // When generating more than one CLC, all but the last will need to
   7773   // branch to the end when a difference is found.
   7774   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
   7775                                SystemZ::splitBlockAfter(MI, MBB) : nullptr);
   7776 
   7777   // Check for the loop form, in which operand 5 is the trip count.
   7778   if (MI.getNumExplicitOperands() > 5) {
   7779     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
   7780 
   7781     Register StartCountReg = MI.getOperand(5).getReg();
   7782     Register StartSrcReg   = forceReg(MI, SrcBase, TII);
   7783     Register StartDestReg  = (HaveSingleBase ? StartSrcReg :
   7784                               forceReg(MI, DestBase, TII));
   7785 
   7786     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
   7787     Register ThisSrcReg  = MRI.createVirtualRegister(RC);
   7788     Register ThisDestReg = (HaveSingleBase ? ThisSrcReg :
   7789                             MRI.createVirtualRegister(RC));
   7790     Register NextSrcReg  = MRI.createVirtualRegister(RC);
   7791     Register NextDestReg = (HaveSingleBase ? NextSrcReg :
   7792                             MRI.createVirtualRegister(RC));
   7793 
   7794     RC = &SystemZ::GR64BitRegClass;
   7795     Register ThisCountReg = MRI.createVirtualRegister(RC);
   7796     Register NextCountReg = MRI.createVirtualRegister(RC);
   7797 
   7798     MachineBasicBlock *StartMBB = MBB;
   7799     MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
   7800     MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
   7801     MachineBasicBlock *NextMBB =
   7802         (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
   7803 
   7804     //  StartMBB:
   7805     //   # fall through to LoopMMB
   7806     MBB->addSuccessor(LoopMBB);
   7807 
   7808     //  LoopMBB:
   7809     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
   7810     //                      [ %NextDestReg, NextMBB ]
   7811     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
   7812     //                     [ %NextSrcReg, NextMBB ]
   7813     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
   7814     //                       [ %NextCountReg, NextMBB ]
   7815     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
   7816     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
   7817     //   ( JLH EndMBB )
   7818     //
   7819     // The prefetch is used only for MVC.  The JLH is used only for CLC.
   7820     MBB = LoopMBB;
   7821 
   7822     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
   7823       .addReg(StartDestReg).addMBB(StartMBB)
   7824       .addReg(NextDestReg).addMBB(NextMBB);
   7825     if (!HaveSingleBase)
   7826       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
   7827         .addReg(StartSrcReg).addMBB(StartMBB)
   7828         .addReg(NextSrcReg).addMBB(NextMBB);
   7829     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
   7830       .addReg(StartCountReg).addMBB(StartMBB)
   7831       .addReg(NextCountReg).addMBB(NextMBB);
   7832     if (Opcode == SystemZ::MVC)
   7833       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
   7834         .addImm(SystemZ::PFD_WRITE)
   7835         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
   7836     BuildMI(MBB, DL, TII->get(Opcode))
   7837       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
   7838       .addReg(ThisSrcReg).addImm(SrcDisp);
   7839     if (EndMBB) {
   7840       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7841         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
   7842         .addMBB(EndMBB);
   7843       MBB->addSuccessor(EndMBB);
   7844       MBB->addSuccessor(NextMBB);
   7845     }
   7846 
   7847     // NextMBB:
   7848     //   %NextDestReg = LA 256(%ThisDestReg)
   7849     //   %NextSrcReg = LA 256(%ThisSrcReg)
   7850     //   %NextCountReg = AGHI %ThisCountReg, -1
   7851     //   CGHI %NextCountReg, 0
   7852     //   JLH LoopMBB
   7853     //   # fall through to DoneMMB
   7854     //
   7855     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
   7856     MBB = NextMBB;
   7857 
   7858     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
   7859       .addReg(ThisDestReg).addImm(256).addReg(0);
   7860     if (!HaveSingleBase)
   7861       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
   7862         .addReg(ThisSrcReg).addImm(256).addReg(0);
   7863     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
   7864       .addReg(ThisCountReg).addImm(-1);
   7865     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
   7866       .addReg(NextCountReg).addImm(0);
   7867     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7868       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
   7869       .addMBB(LoopMBB);
   7870     MBB->addSuccessor(LoopMBB);
   7871     MBB->addSuccessor(DoneMBB);
   7872 
   7873     DestBase = MachineOperand::CreateReg(NextDestReg, false);
   7874     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
   7875     Length &= 255;
   7876     if (EndMBB && !Length)
   7877       // If the loop handled the whole CLC range, DoneMBB will be empty with
   7878       // CC live-through into EndMBB, so add it as live-in.
   7879       DoneMBB->addLiveIn(SystemZ::CC);
   7880     MBB = DoneMBB;
   7881   }
   7882   // Handle any remaining bytes with straight-line code.
   7883   while (Length > 0) {
   7884     uint64_t ThisLength = std::min(Length, uint64_t(256));
   7885     // The previous iteration might have created out-of-range displacements.
   7886     // Apply them using LAY if so.
   7887     if (!isUInt<12>(DestDisp)) {
   7888       Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
   7889       BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
   7890           .add(DestBase)
   7891           .addImm(DestDisp)
   7892           .addReg(0);
   7893       DestBase = MachineOperand::CreateReg(Reg, false);
   7894       DestDisp = 0;
   7895     }
   7896     if (!isUInt<12>(SrcDisp)) {
   7897       Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
   7898       BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
   7899           .add(SrcBase)
   7900           .addImm(SrcDisp)
   7901           .addReg(0);
   7902       SrcBase = MachineOperand::CreateReg(Reg, false);
   7903       SrcDisp = 0;
   7904     }
   7905     BuildMI(*MBB, MI, DL, TII->get(Opcode))
   7906         .add(DestBase)
   7907         .addImm(DestDisp)
   7908         .addImm(ThisLength)
   7909         .add(SrcBase)
   7910         .addImm(SrcDisp)
   7911         .setMemRefs(MI.memoperands());
   7912     DestDisp += ThisLength;
   7913     SrcDisp += ThisLength;
   7914     Length -= ThisLength;
   7915     // If there's another CLC to go, branch to the end if a difference
   7916     // was found.
   7917     if (EndMBB && Length > 0) {
   7918       MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
   7919       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7920         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
   7921         .addMBB(EndMBB);
   7922       MBB->addSuccessor(EndMBB);
   7923       MBB->addSuccessor(NextMBB);
   7924       MBB = NextMBB;
   7925     }
   7926   }
   7927   if (EndMBB) {
   7928     MBB->addSuccessor(EndMBB);
   7929     MBB = EndMBB;
   7930     MBB->addLiveIn(SystemZ::CC);
   7931   }
   7932 
   7933   MI.eraseFromParent();
   7934   return MBB;
   7935 }
   7936 
   7937 // Decompose string pseudo-instruction MI into a loop that continually performs
   7938 // Opcode until CC != 3.
   7939 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
   7940     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
   7941   MachineFunction &MF = *MBB->getParent();
   7942   const SystemZInstrInfo *TII =
   7943       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   7944   MachineRegisterInfo &MRI = MF.getRegInfo();
   7945   DebugLoc DL = MI.getDebugLoc();
   7946 
   7947   uint64_t End1Reg = MI.getOperand(0).getReg();
   7948   uint64_t Start1Reg = MI.getOperand(1).getReg();
   7949   uint64_t Start2Reg = MI.getOperand(2).getReg();
   7950   uint64_t CharReg = MI.getOperand(3).getReg();
   7951 
   7952   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
   7953   uint64_t This1Reg = MRI.createVirtualRegister(RC);
   7954   uint64_t This2Reg = MRI.createVirtualRegister(RC);
   7955   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
   7956 
   7957   MachineBasicBlock *StartMBB = MBB;
   7958   MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
   7959   MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
   7960 
   7961   //  StartMBB:
   7962   //   # fall through to LoopMMB
   7963   MBB->addSuccessor(LoopMBB);
   7964 
   7965   //  LoopMBB:
   7966   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
   7967   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
   7968   //   R0L = %CharReg
   7969   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
   7970   //   JO LoopMBB
   7971   //   # fall through to DoneMMB
   7972   //
   7973   // The load of R0L can be hoisted by post-RA LICM.
   7974   MBB = LoopMBB;
   7975 
   7976   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
   7977     .addReg(Start1Reg).addMBB(StartMBB)
   7978     .addReg(End1Reg).addMBB(LoopMBB);
   7979   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
   7980     .addReg(Start2Reg).addMBB(StartMBB)
   7981     .addReg(End2Reg).addMBB(LoopMBB);
   7982   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
   7983   BuildMI(MBB, DL, TII->get(Opcode))
   7984     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
   7985     .addReg(This1Reg).addReg(This2Reg);
   7986   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   7987     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
   7988   MBB->addSuccessor(LoopMBB);
   7989   MBB->addSuccessor(DoneMBB);
   7990 
   7991   DoneMBB->addLiveIn(SystemZ::CC);
   7992 
   7993   MI.eraseFromParent();
   7994   return DoneMBB;
   7995 }
   7996 
   7997 // Update TBEGIN instruction with final opcode and register clobbers.
   7998 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
   7999     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
   8000     bool NoFloat) const {
   8001   MachineFunction &MF = *MBB->getParent();
   8002   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
   8003   const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
   8004 
   8005   // Update opcode.
   8006   MI.setDesc(TII->get(Opcode));
   8007 
   8008   // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
   8009   // Make sure to add the corresponding GRSM bits if they are missing.
   8010   uint64_t Control = MI.getOperand(2).getImm();
   8011   static const unsigned GPRControlBit[16] = {
   8012     0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
   8013     0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
   8014   };
   8015   Control |= GPRControlBit[15];
   8016   if (TFI->hasFP(MF))
   8017     Control |= GPRControlBit[11];
   8018   MI.getOperand(2).setImm(Control);
   8019 
   8020   // Add GPR clobbers.
   8021   for (int I = 0; I < 16; I++) {
   8022     if ((Control & GPRControlBit[I]) == 0) {
   8023       unsigned Reg = SystemZMC::GR64Regs[I];
   8024       MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
   8025     }
   8026   }
   8027 
   8028   // Add FPR/VR clobbers.
   8029   if (!NoFloat && (Control & 4) != 0) {
   8030     if (Subtarget.hasVector()) {
   8031       for (int I = 0; I < 32; I++) {
   8032         unsigned Reg = SystemZMC::VR128Regs[I];
   8033         MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
   8034       }
   8035     } else {
   8036       for (int I = 0; I < 16; I++) {
   8037         unsigned Reg = SystemZMC::FP64Regs[I];
   8038         MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
   8039       }
   8040     }
   8041   }
   8042 
   8043   return MBB;
   8044 }
   8045 
   8046 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
   8047     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
   8048   MachineFunction &MF = *MBB->getParent();
   8049   MachineRegisterInfo *MRI = &MF.getRegInfo();
   8050   const SystemZInstrInfo *TII =
   8051       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   8052   DebugLoc DL = MI.getDebugLoc();
   8053 
   8054   Register SrcReg = MI.getOperand(0).getReg();
   8055 
   8056   // Create new virtual register of the same class as source.
   8057   const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
   8058   Register DstReg = MRI->createVirtualRegister(RC);
   8059 
   8060   // Replace pseudo with a normal load-and-test that models the def as
   8061   // well.
   8062   BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
   8063     .addReg(SrcReg)
   8064     .setMIFlags(MI.getFlags());
   8065   MI.eraseFromParent();
   8066 
   8067   return MBB;
   8068 }
   8069 
   8070 MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
   8071     MachineInstr &MI, MachineBasicBlock *MBB) const {
   8072   MachineFunction &MF = *MBB->getParent();
   8073   MachineRegisterInfo *MRI = &MF.getRegInfo();
   8074   const SystemZInstrInfo *TII =
   8075       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
   8076   DebugLoc DL = MI.getDebugLoc();
   8077   const unsigned ProbeSize = getStackProbeSize(MF);
   8078   Register DstReg = MI.getOperand(0).getReg();
   8079   Register SizeReg = MI.getOperand(2).getReg();
   8080 
   8081   MachineBasicBlock *StartMBB = MBB;
   8082   MachineBasicBlock *DoneMBB  = SystemZ::splitBlockAfter(MI, MBB);
   8083   MachineBasicBlock *LoopTestMBB  = SystemZ::emitBlockAfter(StartMBB);
   8084   MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
   8085   MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
   8086   MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
   8087 
   8088   MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
   8089     MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad, 8, Align(1));
   8090 
   8091   Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
   8092   Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
   8093 
   8094   //  LoopTestMBB
   8095   //  BRC TailTestMBB
   8096   //  # fallthrough to LoopBodyMBB
   8097   StartMBB->addSuccessor(LoopTestMBB);
   8098   MBB = LoopTestMBB;
   8099   BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
   8100     .addReg(SizeReg)
   8101     .addMBB(StartMBB)
   8102     .addReg(IncReg)
   8103     .addMBB(LoopBodyMBB);
   8104   BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
   8105     .addReg(PHIReg)
   8106     .addImm(ProbeSize);
   8107   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   8108     .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_LT)
   8109     .addMBB(TailTestMBB);
   8110   MBB->addSuccessor(LoopBodyMBB);
   8111   MBB->addSuccessor(TailTestMBB);
   8112 
   8113   //  LoopBodyMBB: Allocate and probe by means of a volatile compare.
   8114   //  J LoopTestMBB
   8115   MBB = LoopBodyMBB;
   8116   BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
   8117     .addReg(PHIReg)
   8118     .addImm(ProbeSize);
   8119   BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
   8120     .addReg(SystemZ::R15D)
   8121     .addImm(ProbeSize);
   8122   BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D)
   8123     .addReg(SystemZ::R15D).addImm(ProbeSize - 8).addReg(0)
   8124     .setMemRefs(VolLdMMO);
   8125   BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
   8126   MBB->addSuccessor(LoopTestMBB);
   8127 
   8128   //  TailTestMBB
   8129   //  BRC DoneMBB
   8130   //  # fallthrough to TailMBB
   8131   MBB = TailTestMBB;
   8132   BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
   8133     .addReg(PHIReg)
   8134     .addImm(0);
   8135   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
   8136     .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_EQ)
   8137     .addMBB(DoneMBB);
   8138   MBB->addSuccessor(TailMBB);
   8139   MBB->addSuccessor(DoneMBB);
   8140 
   8141   //  TailMBB
   8142   //  # fallthrough to DoneMBB
   8143   MBB = TailMBB;
   8144   BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
   8145     .addReg(SystemZ::R15D)
   8146     .addReg(PHIReg);
   8147   BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D)
   8148     .addReg(SystemZ::R15D).addImm(-8).addReg(PHIReg)
   8149     .setMemRefs(VolLdMMO);
   8150   MBB->addSuccessor(DoneMBB);
   8151 
   8152   //  DoneMBB
   8153   MBB = DoneMBB;
   8154   BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
   8155     .addReg(SystemZ::R15D);
   8156 
   8157   MI.eraseFromParent();
   8158   return DoneMBB;
   8159 }
   8160 
   8161 SDValue SystemZTargetLowering::
   8162 getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
   8163   MachineFunction &MF = DAG.getMachineFunction();
   8164   auto *TFL =
   8165       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
   8166   SDLoc DL(SP);
   8167   return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
   8168                      DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
   8169 }
   8170 
   8171 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter(
   8172     MachineInstr &MI, MachineBasicBlock *MBB) const {
   8173   switch (MI.getOpcode()) {
   8174   case SystemZ::Select32:
   8175   case SystemZ::Select64:
   8176   case SystemZ::SelectF32:
   8177   case SystemZ::SelectF64:
   8178   case SystemZ::SelectF128:
   8179   case SystemZ::SelectVR32:
   8180   case SystemZ::SelectVR64:
   8181   case SystemZ::SelectVR128:
   8182     return emitSelect(MI, MBB);
   8183 
   8184   case SystemZ::CondStore8Mux:
   8185     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
   8186   case SystemZ::CondStore8MuxInv:
   8187     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
   8188   case SystemZ::CondStore16Mux:
   8189     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
   8190   case SystemZ::CondStore16MuxInv:
   8191     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
   8192   case SystemZ::CondStore32Mux:
   8193     return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
   8194   case SystemZ::CondStore32MuxInv:
   8195     return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
   8196   case SystemZ::CondStore8:
   8197     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
   8198   case SystemZ::CondStore8Inv:
   8199     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
   8200   case SystemZ::CondStore16:
   8201     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
   8202   case SystemZ::CondStore16Inv:
   8203     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
   8204   case SystemZ::CondStore32:
   8205     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
   8206   case SystemZ::CondStore32Inv:
   8207     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
   8208   case SystemZ::CondStore64:
   8209     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
   8210   case SystemZ::CondStore64Inv:
   8211     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
   8212   case SystemZ::CondStoreF32:
   8213     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
   8214   case SystemZ::CondStoreF32Inv:
   8215     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
   8216   case SystemZ::CondStoreF64:
   8217     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
   8218   case SystemZ::CondStoreF64Inv:
   8219     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
   8220 
   8221   case SystemZ::PAIR128:
   8222     return emitPair128(MI, MBB);
   8223   case SystemZ::AEXT128:
   8224     return emitExt128(MI, MBB, false);
   8225   case SystemZ::ZEXT128:
   8226     return emitExt128(MI, MBB, true);
   8227 
   8228   case SystemZ::ATOMIC_SWAPW:
   8229     return emitAtomicLoadBinary(MI, MBB, 0, 0);
   8230   case SystemZ::ATOMIC_SWAP_32:
   8231     return emitAtomicLoadBinary(MI, MBB, 0, 32);
   8232   case SystemZ::ATOMIC_SWAP_64:
   8233     return emitAtomicLoadBinary(MI, MBB, 0, 64);
   8234 
   8235   case SystemZ::ATOMIC_LOADW_AR:
   8236     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
   8237   case SystemZ::ATOMIC_LOADW_AFI:
   8238     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
   8239   case SystemZ::ATOMIC_LOAD_AR:
   8240     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
   8241   case SystemZ::ATOMIC_LOAD_AHI:
   8242     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
   8243   case SystemZ::ATOMIC_LOAD_AFI:
   8244     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
   8245   case SystemZ::ATOMIC_LOAD_AGR:
   8246     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
   8247   case SystemZ::ATOMIC_LOAD_AGHI:
   8248     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
   8249   case SystemZ::ATOMIC_LOAD_AGFI:
   8250     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
   8251 
   8252   case SystemZ::ATOMIC_LOADW_SR:
   8253     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
   8254   case SystemZ::ATOMIC_LOAD_SR:
   8255     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
   8256   case SystemZ::ATOMIC_LOAD_SGR:
   8257     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
   8258 
   8259   case SystemZ::ATOMIC_LOADW_NR:
   8260     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
   8261   case SystemZ::ATOMIC_LOADW_NILH:
   8262     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
   8263   case SystemZ::ATOMIC_LOAD_NR:
   8264     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
   8265   case SystemZ::ATOMIC_LOAD_NILL:
   8266     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
   8267   case SystemZ::ATOMIC_LOAD_NILH:
   8268     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
   8269   case SystemZ::ATOMIC_LOAD_NILF:
   8270     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
   8271   case SystemZ::ATOMIC_LOAD_NGR:
   8272     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
   8273   case SystemZ::ATOMIC_LOAD_NILL64:
   8274     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
   8275   case SystemZ::ATOMIC_LOAD_NILH64:
   8276     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
   8277   case SystemZ::ATOMIC_LOAD_NIHL64:
   8278     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
   8279   case SystemZ::ATOMIC_LOAD_NIHH64:
   8280     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
   8281   case SystemZ::ATOMIC_LOAD_NILF64:
   8282     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
   8283   case SystemZ::ATOMIC_LOAD_NIHF64:
   8284     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
   8285 
   8286   case SystemZ::ATOMIC_LOADW_OR:
   8287     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
   8288   case SystemZ::ATOMIC_LOADW_OILH:
   8289     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
   8290   case SystemZ::ATOMIC_LOAD_OR:
   8291     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
   8292   case SystemZ::ATOMIC_LOAD_OILL:
   8293     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
   8294   case SystemZ::ATOMIC_LOAD_OILH:
   8295     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
   8296   case SystemZ::ATOMIC_LOAD_OILF:
   8297     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
   8298   case SystemZ::ATOMIC_LOAD_OGR:
   8299     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
   8300   case SystemZ::ATOMIC_LOAD_OILL64:
   8301     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
   8302   case SystemZ::ATOMIC_LOAD_OILH64:
   8303     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
   8304   case SystemZ::ATOMIC_LOAD_OIHL64:
   8305     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
   8306   case SystemZ::ATOMIC_LOAD_OIHH64:
   8307     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
   8308   case SystemZ::ATOMIC_LOAD_OILF64:
   8309     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
   8310   case SystemZ::ATOMIC_LOAD_OIHF64:
   8311     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
   8312 
   8313   case SystemZ::ATOMIC_LOADW_XR:
   8314     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
   8315   case SystemZ::ATOMIC_LOADW_XILF:
   8316     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
   8317   case SystemZ::ATOMIC_LOAD_XR:
   8318     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
   8319   case SystemZ::ATOMIC_LOAD_XILF:
   8320     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
   8321   case SystemZ::ATOMIC_LOAD_XGR:
   8322     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
   8323   case SystemZ::ATOMIC_LOAD_XILF64:
   8324     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
   8325   case SystemZ::ATOMIC_LOAD_XIHF64:
   8326     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
   8327 
   8328   case SystemZ::ATOMIC_LOADW_NRi:
   8329     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
   8330   case SystemZ::ATOMIC_LOADW_NILHi:
   8331     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
   8332   case SystemZ::ATOMIC_LOAD_NRi:
   8333     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
   8334   case SystemZ::ATOMIC_LOAD_NILLi:
   8335     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
   8336   case SystemZ::ATOMIC_LOAD_NILHi:
   8337     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
   8338   case SystemZ::ATOMIC_LOAD_NILFi:
   8339     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
   8340   case SystemZ::ATOMIC_LOAD_NGRi:
   8341     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
   8342   case SystemZ::ATOMIC_LOAD_NILL64i:
   8343     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
   8344   case SystemZ::ATOMIC_LOAD_NILH64i:
   8345     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
   8346   case SystemZ::ATOMIC_LOAD_NIHL64i:
   8347     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
   8348   case SystemZ::ATOMIC_LOAD_NIHH64i:
   8349     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
   8350   case SystemZ::ATOMIC_LOAD_NILF64i:
   8351     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
   8352   case SystemZ::ATOMIC_LOAD_NIHF64i:
   8353     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
   8354 
   8355   case SystemZ::ATOMIC_LOADW_MIN:
   8356     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
   8357                                 SystemZ::CCMASK_CMP_LE, 0);
   8358   case SystemZ::ATOMIC_LOAD_MIN_32:
   8359     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
   8360                                 SystemZ::CCMASK_CMP_LE, 32);
   8361   case SystemZ::ATOMIC_LOAD_MIN_64:
   8362     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
   8363                                 SystemZ::CCMASK_CMP_LE, 64);
   8364 
   8365   case SystemZ::ATOMIC_LOADW_MAX:
   8366     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
   8367                                 SystemZ::CCMASK_CMP_GE, 0);
   8368   case SystemZ::ATOMIC_LOAD_MAX_32:
   8369     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
   8370                                 SystemZ::CCMASK_CMP_GE, 32);
   8371   case SystemZ::ATOMIC_LOAD_MAX_64:
   8372     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
   8373                                 SystemZ::CCMASK_CMP_GE, 64);
   8374 
   8375   case SystemZ::ATOMIC_LOADW_UMIN:
   8376     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
   8377                                 SystemZ::CCMASK_CMP_LE, 0);
   8378   case SystemZ::ATOMIC_LOAD_UMIN_32:
   8379     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
   8380                                 SystemZ::CCMASK_CMP_LE, 32);
   8381   case SystemZ::ATOMIC_LOAD_UMIN_64:
   8382     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
   8383                                 SystemZ::CCMASK_CMP_LE, 64);
   8384 
   8385   case SystemZ::ATOMIC_LOADW_UMAX:
   8386     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
   8387                                 SystemZ::CCMASK_CMP_GE, 0);
   8388   case SystemZ::ATOMIC_LOAD_UMAX_32:
   8389     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
   8390                                 SystemZ::CCMASK_CMP_GE, 32);
   8391   case SystemZ::ATOMIC_LOAD_UMAX_64:
   8392     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
   8393                                 SystemZ::CCMASK_CMP_GE, 64);
   8394 
   8395   case SystemZ::ATOMIC_CMP_SWAPW:
   8396     return emitAtomicCmpSwapW(MI, MBB);
   8397   case SystemZ::MVCSequence:
   8398   case SystemZ::MVCLoop:
   8399     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
   8400   case SystemZ::NCSequence:
   8401   case SystemZ::NCLoop:
   8402     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
   8403   case SystemZ::OCSequence:
   8404   case SystemZ::OCLoop:
   8405     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
   8406   case SystemZ::XCSequence:
   8407   case SystemZ::XCLoop:
   8408     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
   8409   case SystemZ::CLCSequence:
   8410   case SystemZ::CLCLoop:
   8411     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
   8412   case SystemZ::CLSTLoop:
   8413     return emitStringWrapper(MI, MBB, SystemZ::CLST);
   8414   case SystemZ::MVSTLoop:
   8415     return emitStringWrapper(MI, MBB, SystemZ::MVST);
   8416   case SystemZ::SRSTLoop:
   8417     return emitStringWrapper(MI, MBB, SystemZ::SRST);
   8418   case SystemZ::TBEGIN:
   8419     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
   8420   case SystemZ::TBEGIN_nofloat:
   8421     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
   8422   case SystemZ::TBEGINC:
   8423     return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
   8424   case SystemZ::LTEBRCompare_VecPseudo:
   8425     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
   8426   case SystemZ::LTDBRCompare_VecPseudo:
   8427     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
   8428   case SystemZ::LTXBRCompare_VecPseudo:
   8429     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
   8430 
   8431   case SystemZ::PROBED_ALLOCA:
   8432     return emitProbedAlloca(MI, MBB);
   8433 
   8434   case TargetOpcode::STACKMAP:
   8435   case TargetOpcode::PATCHPOINT:
   8436     return emitPatchPoint(MI, MBB);
   8437 
   8438   default:
   8439     llvm_unreachable("Unexpected instr type to insert");
   8440   }
   8441 }
   8442 
   8443 // This is only used by the isel schedulers, and is needed only to prevent
   8444 // compiler from crashing when list-ilp is used.
   8445 const TargetRegisterClass *
   8446 SystemZTargetLowering::getRepRegClassFor(MVT VT) const {
   8447   if (VT == MVT::Untyped)
   8448     return &SystemZ::ADDR128BitRegClass;
   8449   return TargetLowering::getRepRegClassFor(VT);
   8450 }
   8451