LLVM API Documentation

SystemZISelLowering.cpp
Go to the documentation of this file.
00001 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the SystemZTargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "SystemZISelLowering.h"
00015 #include "SystemZCallingConv.h"
00016 #include "SystemZConstantPoolValue.h"
00017 #include "SystemZMachineFunctionInfo.h"
00018 #include "SystemZTargetMachine.h"
00019 #include "llvm/CodeGen/CallingConvLower.h"
00020 #include "llvm/CodeGen/MachineInstrBuilder.h"
00021 #include "llvm/CodeGen/MachineRegisterInfo.h"
00022 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
00023 #include <cctype>
00024 
00025 using namespace llvm;
00026 
00027 #define DEBUG_TYPE "systemz-lower"
00028 
00029 namespace {
00030 // Represents a sequence for extracting a 0/1 value from an IPM result:
00031 // (((X ^ XORValue) + AddValue) >> Bit)
00032 struct IPMConversion {
00033   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
00034     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
00035 
00036   int64_t XORValue;
00037   int64_t AddValue;
00038   unsigned Bit;
00039 };
00040 
00041 // Represents information about a comparison.
00042 struct Comparison {
00043   Comparison(SDValue Op0In, SDValue Op1In)
00044     : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
00045 
00046   // The operands to the comparison.
00047   SDValue Op0, Op1;
00048 
00049   // The opcode that should be used to compare Op0 and Op1.
00050   unsigned Opcode;
00051 
00052   // A SystemZICMP value.  Only used for integer comparisons.
00053   unsigned ICmpType;
00054 
00055   // The mask of CC values that Opcode can produce.
00056   unsigned CCValid;
00057 
00058   // The mask of CC values for which the original condition is true.
00059   unsigned CCMask;
00060 };
00061 } // end anonymous namespace
00062 
00063 // Classify VT as either 32 or 64 bit.
00064 static bool is32Bit(EVT VT) {
00065   switch (VT.getSimpleVT().SimpleTy) {
00066   case MVT::i32:
00067     return true;
00068   case MVT::i64:
00069     return false;
00070   default:
00071     llvm_unreachable("Unsupported type");
00072   }
00073 }
00074 
00075 // Return a version of MachineOperand that can be safely used before the
00076 // final use.
00077 static MachineOperand earlyUseOperand(MachineOperand Op) {
00078   if (Op.isReg())
00079     Op.setIsKill(false);
00080   return Op;
00081 }
00082 
00083 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &tm,
00084                                              const SystemZSubtarget &STI)
00085     : TargetLowering(tm), Subtarget(STI) {
00086   MVT PtrVT = getPointerTy();
00087 
00088   // Set up the register classes.
00089   if (Subtarget.hasHighWord())
00090     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
00091   else
00092     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
00093   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
00094   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
00095   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
00096   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
00097 
00098   // Compute derived properties from the register classes
00099   computeRegisterProperties(Subtarget.getRegisterInfo());
00100 
00101   // Set up special registers.
00102   setExceptionPointerRegister(SystemZ::R6D);
00103   setExceptionSelectorRegister(SystemZ::R7D);
00104   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
00105 
00106   // TODO: It may be better to default to latency-oriented scheduling, however
00107   // LLVM's current latency-oriented scheduler can't handle physreg definitions
00108   // such as SystemZ has with CC, so set this to the register-pressure
00109   // scheduler, because it can.
00110   setSchedulingPreference(Sched::RegPressure);
00111 
00112   setBooleanContents(ZeroOrOneBooleanContent);
00113   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
00114 
00115   // Instructions are strings of 2-byte aligned 2-byte values.
00116   setMinFunctionAlignment(2);
00117 
00118   // Handle operations that are handled in a similar way for all types.
00119   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
00120        I <= MVT::LAST_FP_VALUETYPE;
00121        ++I) {
00122     MVT VT = MVT::SimpleValueType(I);
00123     if (isTypeLegal(VT)) {
00124       // Lower SET_CC into an IPM-based sequence.
00125       setOperationAction(ISD::SETCC, VT, Custom);
00126 
00127       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
00128       setOperationAction(ISD::SELECT, VT, Expand);
00129 
00130       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
00131       setOperationAction(ISD::SELECT_CC, VT, Custom);
00132       setOperationAction(ISD::BR_CC,     VT, Custom);
00133     }
00134   }
00135 
00136   // Expand jump table branches as address arithmetic followed by an
00137   // indirect jump.
00138   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
00139 
00140   // Expand BRCOND into a BR_CC (see above).
00141   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
00142 
00143   // Handle integer types.
00144   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
00145        I <= MVT::LAST_INTEGER_VALUETYPE;
00146        ++I) {
00147     MVT VT = MVT::SimpleValueType(I);
00148     if (isTypeLegal(VT)) {
00149       // Expand individual DIV and REMs into DIVREMs.
00150       setOperationAction(ISD::SDIV, VT, Expand);
00151       setOperationAction(ISD::UDIV, VT, Expand);
00152       setOperationAction(ISD::SREM, VT, Expand);
00153       setOperationAction(ISD::UREM, VT, Expand);
00154       setOperationAction(ISD::SDIVREM, VT, Custom);
00155       setOperationAction(ISD::UDIVREM, VT, Custom);
00156 
00157       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
00158       // stores, putting a serialization instruction after the stores.
00159       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
00160       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
00161 
00162       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
00163       // available, or if the operand is constant.
00164       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
00165 
00166       // No special instructions for these.
00167       setOperationAction(ISD::CTPOP,           VT, Expand);
00168       setOperationAction(ISD::CTTZ,            VT, Expand);
00169       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
00170       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
00171       setOperationAction(ISD::ROTR,            VT, Expand);
00172 
00173       // Use *MUL_LOHI where possible instead of MULH*.
00174       setOperationAction(ISD::MULHS, VT, Expand);
00175       setOperationAction(ISD::MULHU, VT, Expand);
00176       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
00177       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
00178 
00179       // Only z196 and above have native support for conversions to unsigned.
00180       if (!Subtarget.hasFPExtension())
00181         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
00182     }
00183   }
00184 
00185   // Type legalization will convert 8- and 16-bit atomic operations into
00186   // forms that operate on i32s (but still keeping the original memory VT).
00187   // Lower them into full i32 operations.
00188   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
00189   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
00190   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
00191   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
00192   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
00193   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
00194   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
00195   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
00196   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
00197   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
00198   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
00199   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
00200 
00201   // z10 has instructions for signed but not unsigned FP conversion.
00202   // Handle unsigned 32-bit types as signed 64-bit types.
00203   if (!Subtarget.hasFPExtension()) {
00204     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
00205     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
00206   }
00207 
00208   // We have native support for a 64-bit CTLZ, via FLOGR.
00209   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
00210   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
00211 
00212   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
00213   setOperationAction(ISD::OR, MVT::i64, Custom);
00214 
00215   // FIXME: Can we support these natively?
00216   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
00217   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
00218   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
00219 
00220   // We have native instructions for i8, i16 and i32 extensions, but not i1.
00221   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00222   for (MVT VT : MVT::integer_valuetypes()) {
00223     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
00224     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
00225     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
00226   }
00227 
00228   // Handle the various types of symbolic address.
00229   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
00230   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
00231   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
00232   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
00233   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
00234 
00235   // We need to handle dynamic allocations specially because of the
00236   // 160-byte area at the bottom of the stack.
00237   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
00238 
00239   // Use custom expanders so that we can force the function to use
00240   // a frame pointer.
00241   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
00242   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
00243 
00244   // Handle prefetches with PFD or PFDRL.
00245   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
00246 
00247   // Handle floating-point types.
00248   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
00249        I <= MVT::LAST_FP_VALUETYPE;
00250        ++I) {
00251     MVT VT = MVT::SimpleValueType(I);
00252     if (isTypeLegal(VT)) {
00253       // We can use FI for FRINT.
00254       setOperationAction(ISD::FRINT, VT, Legal);
00255 
00256       // We can use the extended form of FI for other rounding operations.
00257       if (Subtarget.hasFPExtension()) {
00258         setOperationAction(ISD::FNEARBYINT, VT, Legal);
00259         setOperationAction(ISD::FFLOOR, VT, Legal);
00260         setOperationAction(ISD::FCEIL, VT, Legal);
00261         setOperationAction(ISD::FTRUNC, VT, Legal);
00262         setOperationAction(ISD::FROUND, VT, Legal);
00263       }
00264 
00265       // No special instructions for these.
00266       setOperationAction(ISD::FSIN, VT, Expand);
00267       setOperationAction(ISD::FCOS, VT, Expand);
00268       setOperationAction(ISD::FREM, VT, Expand);
00269     }
00270   }
00271 
00272   // We have fused multiply-addition for f32 and f64 but not f128.
00273   setOperationAction(ISD::FMA, MVT::f32,  Legal);
00274   setOperationAction(ISD::FMA, MVT::f64,  Legal);
00275   setOperationAction(ISD::FMA, MVT::f128, Expand);
00276 
00277   // Needed so that we don't try to implement f128 constant loads using
00278   // a load-and-extend of a f80 constant (in cases where the constant
00279   // would fit in an f80).
00280   for (MVT VT : MVT::fp_valuetypes())
00281     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
00282 
00283   // Floating-point truncation and stores need to be done separately.
00284   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
00285   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
00286   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
00287 
00288   // We have 64-bit FPR<->GPR moves, but need special handling for
00289   // 32-bit forms.
00290   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
00291   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
00292 
00293   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
00294   // structure, but VAEND is a no-op.
00295   setOperationAction(ISD::VASTART, MVT::Other, Custom);
00296   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
00297   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
00298 
00299   // Codes for which we want to perform some z-specific combinations.
00300   setTargetDAGCombine(ISD::SIGN_EXTEND);
00301 
00302   // We want to use MVC in preference to even a single load/store pair.
00303   MaxStoresPerMemcpy = 0;
00304   MaxStoresPerMemcpyOptSize = 0;
00305 
00306   // The main memset sequence is a byte store followed by an MVC.
00307   // Two STC or MV..I stores win over that, but the kind of fused stores
00308   // generated by target-independent code don't when the byte value is
00309   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
00310   // than "STC;MVC".  Handle the choice in target-specific code instead.
00311   MaxStoresPerMemset = 0;
00312   MaxStoresPerMemsetOptSize = 0;
00313 }
00314 
00315 EVT SystemZTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
00316   if (!VT.isVector())
00317     return MVT::i32;
00318   return VT.changeVectorElementTypeToInteger();
00319 }
00320 
00321 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
00322   VT = VT.getScalarType();
00323 
00324   if (!VT.isSimple())
00325     return false;
00326 
00327   switch (VT.getSimpleVT().SimpleTy) {
00328   case MVT::f32:
00329   case MVT::f64:
00330     return true;
00331   case MVT::f128:
00332     return false;
00333   default:
00334     break;
00335   }
00336 
00337   return false;
00338 }
00339 
00340 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
00341   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
00342   return Imm.isZero() || Imm.isNegZero();
00343 }
00344 
00345 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
00346                                                            unsigned,
00347                                                            unsigned,
00348                                                            bool *Fast) const {
00349   // Unaligned accesses should never be slower than the expanded version.
00350   // We check specifically for aligned accesses in the few cases where
00351   // they are required.
00352   if (Fast)
00353     *Fast = true;
00354   return true;
00355 }
00356   
00357 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
00358                                                   Type *Ty) const {
00359   // Punt on globals for now, although they can be used in limited
00360   // RELATIVE LONG cases.
00361   if (AM.BaseGV)
00362     return false;
00363 
00364   // Require a 20-bit signed offset.
00365   if (!isInt<20>(AM.BaseOffs))
00366     return false;
00367 
00368   // Indexing is OK but no scale factor can be applied.
00369   return AM.Scale == 0 || AM.Scale == 1;
00370 }
00371 
00372 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
00373   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
00374     return false;
00375   unsigned FromBits = FromType->getPrimitiveSizeInBits();
00376   unsigned ToBits = ToType->getPrimitiveSizeInBits();
00377   return FromBits > ToBits;
00378 }
00379 
00380 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
00381   if (!FromVT.isInteger() || !ToVT.isInteger())
00382     return false;
00383   unsigned FromBits = FromVT.getSizeInBits();
00384   unsigned ToBits = ToVT.getSizeInBits();
00385   return FromBits > ToBits;
00386 }
00387 
00388 //===----------------------------------------------------------------------===//
00389 // Inline asm support
00390 //===----------------------------------------------------------------------===//
00391 
00392 TargetLowering::ConstraintType
00393 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
00394   if (Constraint.size() == 1) {
00395     switch (Constraint[0]) {
00396     case 'a': // Address register
00397     case 'd': // Data register (equivalent to 'r')
00398     case 'f': // Floating-point register
00399     case 'h': // High-part register
00400     case 'r': // General-purpose register
00401       return C_RegisterClass;
00402 
00403     case 'Q': // Memory with base and unsigned 12-bit displacement
00404     case 'R': // Likewise, plus an index
00405     case 'S': // Memory with base and signed 20-bit displacement
00406     case 'T': // Likewise, plus an index
00407     case 'm': // Equivalent to 'T'.
00408       return C_Memory;
00409 
00410     case 'I': // Unsigned 8-bit constant
00411     case 'J': // Unsigned 12-bit constant
00412     case 'K': // Signed 16-bit constant
00413     case 'L': // Signed 20-bit displacement (on all targets we support)
00414     case 'M': // 0x7fffffff
00415       return C_Other;
00416 
00417     default:
00418       break;
00419     }
00420   }
00421   return TargetLowering::getConstraintType(Constraint);
00422 }
00423 
00424 TargetLowering::ConstraintWeight SystemZTargetLowering::
00425 getSingleConstraintMatchWeight(AsmOperandInfo &info,
00426                                const char *constraint) const {
00427   ConstraintWeight weight = CW_Invalid;
00428   Value *CallOperandVal = info.CallOperandVal;
00429   // If we don't have a value, we can't do a match,
00430   // but allow it at the lowest weight.
00431   if (!CallOperandVal)
00432     return CW_Default;
00433   Type *type = CallOperandVal->getType();
00434   // Look at the constraint type.
00435   switch (*constraint) {
00436   default:
00437     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
00438     break;
00439 
00440   case 'a': // Address register
00441   case 'd': // Data register (equivalent to 'r')
00442   case 'h': // High-part register
00443   case 'r': // General-purpose register
00444     if (CallOperandVal->getType()->isIntegerTy())
00445       weight = CW_Register;
00446     break;
00447 
00448   case 'f': // Floating-point register
00449     if (type->isFloatingPointTy())
00450       weight = CW_Register;
00451     break;
00452 
00453   case 'I': // Unsigned 8-bit constant
00454     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00455       if (isUInt<8>(C->getZExtValue()))
00456         weight = CW_Constant;
00457     break;
00458 
00459   case 'J': // Unsigned 12-bit constant
00460     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00461       if (isUInt<12>(C->getZExtValue()))
00462         weight = CW_Constant;
00463     break;
00464 
00465   case 'K': // Signed 16-bit constant
00466     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00467       if (isInt<16>(C->getSExtValue()))
00468         weight = CW_Constant;
00469     break;
00470 
00471   case 'L': // Signed 20-bit displacement (on all targets we support)
00472     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00473       if (isInt<20>(C->getSExtValue()))
00474         weight = CW_Constant;
00475     break;
00476 
00477   case 'M': // 0x7fffffff
00478     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00479       if (C->getZExtValue() == 0x7fffffff)
00480         weight = CW_Constant;
00481     break;
00482   }
00483   return weight;
00484 }
00485 
00486 // Parse a "{tNNN}" register constraint for which the register type "t"
00487 // has already been verified.  MC is the class associated with "t" and
00488 // Map maps 0-based register numbers to LLVM register numbers.
00489 static std::pair<unsigned, const TargetRegisterClass *>
00490 parseRegisterNumber(const std::string &Constraint,
00491                     const TargetRegisterClass *RC, const unsigned *Map) {
00492   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
00493   if (isdigit(Constraint[2])) {
00494     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
00495     unsigned Index = atoi(Suffix.c_str());
00496     if (Index < 16 && Map[Index])
00497       return std::make_pair(Map[Index], RC);
00498   }
00499   return std::make_pair(0U, nullptr);
00500 }
00501 
00502 std::pair<unsigned, const TargetRegisterClass *>
00503 SystemZTargetLowering::getRegForInlineAsmConstraint(
00504     const TargetRegisterInfo *TRI, const std::string &Constraint,
00505     MVT VT) const {
00506   if (Constraint.size() == 1) {
00507     // GCC Constraint Letters
00508     switch (Constraint[0]) {
00509     default: break;
00510     case 'd': // Data register (equivalent to 'r')
00511     case 'r': // General-purpose register
00512       if (VT == MVT::i64)
00513         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
00514       else if (VT == MVT::i128)
00515         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
00516       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
00517 
00518     case 'a': // Address register
00519       if (VT == MVT::i64)
00520         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
00521       else if (VT == MVT::i128)
00522         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
00523       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
00524 
00525     case 'h': // High-part register (an LLVM extension)
00526       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
00527 
00528     case 'f': // Floating-point register
00529       if (VT == MVT::f64)
00530         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
00531       else if (VT == MVT::f128)
00532         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
00533       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
00534     }
00535   }
00536   if (Constraint[0] == '{') {
00537     // We need to override the default register parsing for GPRs and FPRs
00538     // because the interpretation depends on VT.  The internal names of
00539     // the registers are also different from the external names
00540     // (F0D and F0S instead of F0, etc.).
00541     if (Constraint[1] == 'r') {
00542       if (VT == MVT::i32)
00543         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
00544                                    SystemZMC::GR32Regs);
00545       if (VT == MVT::i128)
00546         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
00547                                    SystemZMC::GR128Regs);
00548       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
00549                                  SystemZMC::GR64Regs);
00550     }
00551     if (Constraint[1] == 'f') {
00552       if (VT == MVT::f32)
00553         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
00554                                    SystemZMC::FP32Regs);
00555       if (VT == MVT::f128)
00556         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
00557                                    SystemZMC::FP128Regs);
00558       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
00559                                  SystemZMC::FP64Regs);
00560     }
00561   }
00562   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
00563 }
00564 
00565 void SystemZTargetLowering::
00566 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
00567                              std::vector<SDValue> &Ops,
00568                              SelectionDAG &DAG) const {
00569   // Only support length 1 constraints for now.
00570   if (Constraint.length() == 1) {
00571     switch (Constraint[0]) {
00572     case 'I': // Unsigned 8-bit constant
00573       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00574         if (isUInt<8>(C->getZExtValue()))
00575           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
00576                                               Op.getValueType()));
00577       return;
00578 
00579     case 'J': // Unsigned 12-bit constant
00580       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00581         if (isUInt<12>(C->getZExtValue()))
00582           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
00583                                               Op.getValueType()));
00584       return;
00585 
00586     case 'K': // Signed 16-bit constant
00587       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00588         if (isInt<16>(C->getSExtValue()))
00589           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
00590                                               Op.getValueType()));
00591       return;
00592 
00593     case 'L': // Signed 20-bit displacement (on all targets we support)
00594       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00595         if (isInt<20>(C->getSExtValue()))
00596           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
00597                                               Op.getValueType()));
00598       return;
00599 
00600     case 'M': // 0x7fffffff
00601       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00602         if (C->getZExtValue() == 0x7fffffff)
00603           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
00604                                               Op.getValueType()));
00605       return;
00606     }
00607   }
00608   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
00609 }
00610 
00611 //===----------------------------------------------------------------------===//
00612 // Calling conventions
00613 //===----------------------------------------------------------------------===//
00614 
00615 #include "SystemZGenCallingConv.inc"
00616 
00617 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
00618                                                      Type *ToType) const {
00619   return isTruncateFree(FromType, ToType);
00620 }
00621 
00622 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
00623   if (!CI->isTailCall())
00624     return false;
00625   return true;
00626 }
00627 
00628 // Value is a value that has been passed to us in the location described by VA
00629 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
00630 // any loads onto Chain.
00631 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
00632                                    CCValAssign &VA, SDValue Chain,
00633                                    SDValue Value) {
00634   // If the argument has been promoted from a smaller type, insert an
00635   // assertion to capture this.
00636   if (VA.getLocInfo() == CCValAssign::SExt)
00637     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
00638                         DAG.getValueType(VA.getValVT()));
00639   else if (VA.getLocInfo() == CCValAssign::ZExt)
00640     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
00641                         DAG.getValueType(VA.getValVT()));
00642 
00643   if (VA.isExtInLoc())
00644     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
00645   else if (VA.getLocInfo() == CCValAssign::Indirect)
00646     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
00647                         MachinePointerInfo(), false, false, false, 0);
00648   else
00649     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
00650   return Value;
00651 }
00652 
00653 // Value is a value of type VA.getValVT() that we need to copy into
00654 // the location described by VA.  Return a copy of Value converted to
00655 // VA.getValVT().  The caller is responsible for handling indirect values.
00656 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
00657                                    CCValAssign &VA, SDValue Value) {
00658   switch (VA.getLocInfo()) {
00659   case CCValAssign::SExt:
00660     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
00661   case CCValAssign::ZExt:
00662     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
00663   case CCValAssign::AExt:
00664     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
00665   case CCValAssign::Full:
00666     return Value;
00667   default:
00668     llvm_unreachable("Unhandled getLocInfo()");
00669   }
00670 }
00671 
00672 SDValue SystemZTargetLowering::
00673 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
00674                      const SmallVectorImpl<ISD::InputArg> &Ins,
00675                      SDLoc DL, SelectionDAG &DAG,
00676                      SmallVectorImpl<SDValue> &InVals) const {
00677   MachineFunction &MF = DAG.getMachineFunction();
00678   MachineFrameInfo *MFI = MF.getFrameInfo();
00679   MachineRegisterInfo &MRI = MF.getRegInfo();
00680   SystemZMachineFunctionInfo *FuncInfo =
00681       MF.getInfo<SystemZMachineFunctionInfo>();
00682   auto *TFL =
00683       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
00684 
00685   // Assign locations to all of the incoming arguments.
00686   SmallVector<CCValAssign, 16> ArgLocs;
00687   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
00688   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
00689 
00690   unsigned NumFixedGPRs = 0;
00691   unsigned NumFixedFPRs = 0;
00692   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
00693     SDValue ArgValue;
00694     CCValAssign &VA = ArgLocs[I];
00695     EVT LocVT = VA.getLocVT();
00696     if (VA.isRegLoc()) {
00697       // Arguments passed in registers
00698       const TargetRegisterClass *RC;
00699       switch (LocVT.getSimpleVT().SimpleTy) {
00700       default:
00701         // Integers smaller than i64 should be promoted to i64.
00702         llvm_unreachable("Unexpected argument type");
00703       case MVT::i32:
00704         NumFixedGPRs += 1;
00705         RC = &SystemZ::GR32BitRegClass;
00706         break;
00707       case MVT::i64:
00708         NumFixedGPRs += 1;
00709         RC = &SystemZ::GR64BitRegClass;
00710         break;
00711       case MVT::f32:
00712         NumFixedFPRs += 1;
00713         RC = &SystemZ::FP32BitRegClass;
00714         break;
00715       case MVT::f64:
00716         NumFixedFPRs += 1;
00717         RC = &SystemZ::FP64BitRegClass;
00718         break;
00719       }
00720 
00721       unsigned VReg = MRI.createVirtualRegister(RC);
00722       MRI.addLiveIn(VA.getLocReg(), VReg);
00723       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
00724     } else {
00725       assert(VA.isMemLoc() && "Argument not register or memory");
00726 
00727       // Create the frame index object for this incoming parameter.
00728       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
00729                                       VA.getLocMemOffset(), true);
00730 
00731       // Create the SelectionDAG nodes corresponding to a load
00732       // from this parameter.  Unpromoted ints and floats are
00733       // passed as right-justified 8-byte values.
00734       EVT PtrVT = getPointerTy();
00735       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
00736       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
00737         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
00738       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
00739                              MachinePointerInfo::getFixedStack(FI),
00740                              false, false, false, 0);
00741     }
00742 
00743     // Convert the value of the argument register into the value that's
00744     // being passed.
00745     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
00746   }
00747 
00748   if (IsVarArg) {
00749     // Save the number of non-varargs registers for later use by va_start, etc.
00750     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
00751     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
00752 
00753     // Likewise the address (in the form of a frame index) of where the
00754     // first stack vararg would be.  The 1-byte size here is arbitrary.
00755     int64_t StackSize = CCInfo.getNextStackOffset();
00756     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
00757 
00758     // ...and a similar frame index for the caller-allocated save area
00759     // that will be used to store the incoming registers.
00760     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
00761     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
00762     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
00763 
00764     // Store the FPR varargs in the reserved frame slots.  (We store the
00765     // GPRs as part of the prologue.)
00766     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
00767       SDValue MemOps[SystemZ::NumArgFPRs];
00768       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
00769         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
00770         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
00771         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
00772         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
00773                                      &SystemZ::FP64BitRegClass);
00774         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
00775         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
00776                                  MachinePointerInfo::getFixedStack(FI),
00777                                  false, false, 0);
00778 
00779       }
00780       // Join the stores, which are independent of one another.
00781       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
00782                           makeArrayRef(&MemOps[NumFixedFPRs],
00783                                        SystemZ::NumArgFPRs-NumFixedFPRs));
00784     }
00785   }
00786 
00787   return Chain;
00788 }
00789 
00790 static bool canUseSiblingCall(const CCState &ArgCCInfo,
00791                               SmallVectorImpl<CCValAssign> &ArgLocs) {
00792   // Punt if there are any indirect or stack arguments, or if the call
00793   // needs the call-saved argument register R6.
00794   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
00795     CCValAssign &VA = ArgLocs[I];
00796     if (VA.getLocInfo() == CCValAssign::Indirect)
00797       return false;
00798     if (!VA.isRegLoc())
00799       return false;
00800     unsigned Reg = VA.getLocReg();
00801     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
00802       return false;
00803   }
00804   return true;
00805 }
00806 
00807 SDValue
00808 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
00809                                  SmallVectorImpl<SDValue> &InVals) const {
00810   SelectionDAG &DAG = CLI.DAG;
00811   SDLoc &DL = CLI.DL;
00812   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
00813   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
00814   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
00815   SDValue Chain = CLI.Chain;
00816   SDValue Callee = CLI.Callee;
00817   bool &IsTailCall = CLI.IsTailCall;
00818   CallingConv::ID CallConv = CLI.CallConv;
00819   bool IsVarArg = CLI.IsVarArg;
00820   MachineFunction &MF = DAG.getMachineFunction();
00821   EVT PtrVT = getPointerTy();
00822 
00823   // Analyze the operands of the call, assigning locations to each operand.
00824   SmallVector<CCValAssign, 16> ArgLocs;
00825   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
00826   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
00827 
00828   // We don't support GuaranteedTailCallOpt, only automatically-detected
00829   // sibling calls.
00830   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
00831     IsTailCall = false;
00832 
00833   // Get a count of how many bytes are to be pushed on the stack.
00834   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
00835 
00836   // Mark the start of the call.
00837   if (!IsTailCall)
00838     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
00839                                  DL);
00840 
00841   // Copy argument values to their designated locations.
00842   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
00843   SmallVector<SDValue, 8> MemOpChains;
00844   SDValue StackPtr;
00845   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
00846     CCValAssign &VA = ArgLocs[I];
00847     SDValue ArgValue = OutVals[I];
00848 
00849     if (VA.getLocInfo() == CCValAssign::Indirect) {
00850       // Store the argument in a stack slot and pass its address.
00851       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
00852       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
00853       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
00854                                          MachinePointerInfo::getFixedStack(FI),
00855                                          false, false, 0));
00856       ArgValue = SpillSlot;
00857     } else
00858       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
00859 
00860     if (VA.isRegLoc())
00861       // Queue up the argument copies and emit them at the end.
00862       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
00863     else {
00864       assert(VA.isMemLoc() && "Argument not register or memory");
00865 
00866       // Work out the address of the stack slot.  Unpromoted ints and
00867       // floats are passed as right-justified 8-byte values.
00868       if (!StackPtr.getNode())
00869         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
00870       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
00871       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
00872         Offset += 4;
00873       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
00874                                     DAG.getIntPtrConstant(Offset));
00875 
00876       // Emit the store.
00877       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
00878                                          MachinePointerInfo(),
00879                                          false, false, 0));
00880     }
00881   }
00882 
00883   // Join the stores, which are independent of one another.
00884   if (!MemOpChains.empty())
00885     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
00886 
00887   // Accept direct calls by converting symbolic call addresses to the
00888   // associated Target* opcodes.  Force %r1 to be used for indirect
00889   // tail calls.
00890   SDValue Glue;
00891   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
00892     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
00893     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
00894   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
00895     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
00896     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
00897   } else if (IsTailCall) {
00898     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
00899     Glue = Chain.getValue(1);
00900     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
00901   }
00902 
00903   // Build a sequence of copy-to-reg nodes, chained and glued together.
00904   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
00905     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
00906                              RegsToPass[I].second, Glue);
00907     Glue = Chain.getValue(1);
00908   }
00909 
00910   // The first call operand is the chain and the second is the target address.
00911   SmallVector<SDValue, 8> Ops;
00912   Ops.push_back(Chain);
00913   Ops.push_back(Callee);
00914 
00915   // Add argument registers to the end of the list so that they are
00916   // known live into the call.
00917   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
00918     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
00919                                   RegsToPass[I].second.getValueType()));
00920 
00921   // Add a register mask operand representing the call-preserved registers.
00922   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
00923   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
00924   assert(Mask && "Missing call preserved mask for calling convention");
00925   Ops.push_back(DAG.getRegisterMask(Mask));
00926 
00927   // Glue the call to the argument copies, if any.
00928   if (Glue.getNode())
00929     Ops.push_back(Glue);
00930 
00931   // Emit the call.
00932   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
00933   if (IsTailCall)
00934     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
00935   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
00936   Glue = Chain.getValue(1);
00937 
00938   // Mark the end of the call, which is glued to the call itself.
00939   Chain = DAG.getCALLSEQ_END(Chain,
00940                              DAG.getConstant(NumBytes, PtrVT, true),
00941                              DAG.getConstant(0, PtrVT, true),
00942                              Glue, DL);
00943   Glue = Chain.getValue(1);
00944 
00945   // Assign locations to each value returned by this call.
00946   SmallVector<CCValAssign, 16> RetLocs;
00947   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
00948   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
00949 
00950   // Copy all of the result registers out of their specified physreg.
00951   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
00952     CCValAssign &VA = RetLocs[I];
00953 
00954     // Copy the value out, gluing the copy to the end of the call sequence.
00955     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
00956                                           VA.getLocVT(), Glue);
00957     Chain = RetValue.getValue(1);
00958     Glue = RetValue.getValue(2);
00959 
00960     // Convert the value of the return register into the value that's
00961     // being returned.
00962     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
00963   }
00964 
00965   return Chain;
00966 }
00967 
00968 SDValue
00969 SystemZTargetLowering::LowerReturn(SDValue Chain,
00970                                    CallingConv::ID CallConv, bool IsVarArg,
00971                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
00972                                    const SmallVectorImpl<SDValue> &OutVals,
00973                                    SDLoc DL, SelectionDAG &DAG) const {
00974   MachineFunction &MF = DAG.getMachineFunction();
00975 
00976   // Assign locations to each returned value.
00977   SmallVector<CCValAssign, 16> RetLocs;
00978   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
00979   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
00980 
00981   // Quick exit for void returns
00982   if (RetLocs.empty())
00983     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
00984 
00985   // Copy the result values into the output registers.
00986   SDValue Glue;
00987   SmallVector<SDValue, 4> RetOps;
00988   RetOps.push_back(Chain);
00989   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
00990     CCValAssign &VA = RetLocs[I];
00991     SDValue RetValue = OutVals[I];
00992 
00993     // Make the return register live on exit.
00994     assert(VA.isRegLoc() && "Can only return in registers!");
00995 
00996     // Promote the value as required.
00997     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
00998 
00999     // Chain and glue the copies together.
01000     unsigned Reg = VA.getLocReg();
01001     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
01002     Glue = Chain.getValue(1);
01003     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
01004   }
01005 
01006   // Update chain and glue.
01007   RetOps[0] = Chain;
01008   if (Glue.getNode())
01009     RetOps.push_back(Glue);
01010 
01011   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
01012 }
01013 
01014 SDValue SystemZTargetLowering::
01015 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
01016   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
01017 }
01018 
01019 // CC is a comparison that will be implemented using an integer or
01020 // floating-point comparison.  Return the condition code mask for
01021 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
01022 // unsigned comparisons and clear for signed ones.  In the floating-point
01023 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
01024 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
01025 #define CONV(X) \
01026   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
01027   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
01028   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
01029 
01030   switch (CC) {
01031   default:
01032     llvm_unreachable("Invalid integer condition!");
01033 
01034   CONV(EQ);
01035   CONV(NE);
01036   CONV(GT);
01037   CONV(GE);
01038   CONV(LT);
01039   CONV(LE);
01040 
01041   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
01042   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
01043   }
01044 #undef CONV
01045 }
01046 
01047 // Return a sequence for getting a 1 from an IPM result when CC has a
01048 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
01049 // The handling of CC values outside CCValid doesn't matter.
01050 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
01051   // Deal with cases where the result can be taken directly from a bit
01052   // of the IPM result.
01053   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
01054     return IPMConversion(0, 0, SystemZ::IPM_CC);
01055   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
01056     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
01057 
01058   // Deal with cases where we can add a value to force the sign bit
01059   // to contain the right value.  Putting the bit in 31 means we can
01060   // use SRL rather than RISBG(L), and also makes it easier to get a
01061   // 0/-1 value, so it has priority over the other tests below.
01062   //
01063   // These sequences rely on the fact that the upper two bits of the
01064   // IPM result are zero.
01065   uint64_t TopBit = uint64_t(1) << 31;
01066   if (CCMask == (CCValid & SystemZ::CCMASK_0))
01067     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
01068   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
01069     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
01070   if (CCMask == (CCValid & (SystemZ::CCMASK_0
01071                             | SystemZ::CCMASK_1
01072                             | SystemZ::CCMASK_2)))
01073     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
01074   if (CCMask == (CCValid & SystemZ::CCMASK_3))
01075     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
01076   if (CCMask == (CCValid & (SystemZ::CCMASK_1
01077                             | SystemZ::CCMASK_2
01078                             | SystemZ::CCMASK_3)))
01079     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
01080 
01081   // Next try inverting the value and testing a bit.  0/1 could be
01082   // handled this way too, but we dealt with that case above.
01083   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
01084     return IPMConversion(-1, 0, SystemZ::IPM_CC);
01085 
01086   // Handle cases where adding a value forces a non-sign bit to contain
01087   // the right value.
01088   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
01089     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
01090   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
01091     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
01092 
01093   // The remaining cases are 1, 2, 0/1/3 and 0/2/3.  All these are
01094   // can be done by inverting the low CC bit and applying one of the
01095   // sign-based extractions above.
01096   if (CCMask == (CCValid & SystemZ::CCMASK_1))
01097     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
01098   if (CCMask == (CCValid & SystemZ::CCMASK_2))
01099     return IPMConversion(1 << SystemZ::IPM_CC,
01100                          TopBit - (3 << SystemZ::IPM_CC), 31);
01101   if (CCMask == (CCValid & (SystemZ::CCMASK_0
01102                             | SystemZ::CCMASK_1
01103                             | SystemZ::CCMASK_3)))
01104     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
01105   if (CCMask == (CCValid & (SystemZ::CCMASK_0
01106                             | SystemZ::CCMASK_2
01107                             | SystemZ::CCMASK_3)))
01108     return IPMConversion(1 << SystemZ::IPM_CC,
01109                          TopBit - (1 << SystemZ::IPM_CC), 31);
01110 
01111   llvm_unreachable("Unexpected CC combination");
01112 }
01113 
01114 // If C can be converted to a comparison against zero, adjust the operands
01115 // as necessary.
01116 static void adjustZeroCmp(SelectionDAG &DAG, Comparison &C) {
01117   if (C.ICmpType == SystemZICMP::UnsignedOnly)
01118     return;
01119 
01120   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
01121   if (!ConstOp1)
01122     return;
01123 
01124   int64_t Value = ConstOp1->getSExtValue();
01125   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
01126       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
01127       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
01128       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
01129     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
01130     C.Op1 = DAG.getConstant(0, C.Op1.getValueType());
01131   }
01132 }
01133 
01134 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
01135 // adjust the operands as necessary.
01136 static void adjustSubwordCmp(SelectionDAG &DAG, Comparison &C) {
01137   // For us to make any changes, it must a comparison between a single-use
01138   // load and a constant.
01139   if (!C.Op0.hasOneUse() ||
01140       C.Op0.getOpcode() != ISD::LOAD ||
01141       C.Op1.getOpcode() != ISD::Constant)
01142     return;
01143 
01144   // We must have an 8- or 16-bit load.
01145   auto *Load = cast<LoadSDNode>(C.Op0);
01146   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
01147   if (NumBits != 8 && NumBits != 16)
01148     return;
01149 
01150   // The load must be an extending one and the constant must be within the
01151   // range of the unextended value.
01152   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
01153   uint64_t Value = ConstOp1->getZExtValue();
01154   uint64_t Mask = (1 << NumBits) - 1;
01155   if (Load->getExtensionType() == ISD::SEXTLOAD) {
01156     // Make sure that ConstOp1 is in range of C.Op0.
01157     int64_t SignedValue = ConstOp1->getSExtValue();
01158     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
01159       return;
01160     if (C.ICmpType != SystemZICMP::SignedOnly) {
01161       // Unsigned comparison between two sign-extended values is equivalent
01162       // to unsigned comparison between two zero-extended values.
01163       Value &= Mask;
01164     } else if (NumBits == 8) {
01165       // Try to treat the comparison as unsigned, so that we can use CLI.
01166       // Adjust CCMask and Value as necessary.
01167       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
01168         // Test whether the high bit of the byte is set.
01169         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
01170       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
01171         // Test whether the high bit of the byte is clear.
01172         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
01173       else
01174         // No instruction exists for this combination.
01175         return;
01176       C.ICmpType = SystemZICMP::UnsignedOnly;
01177     }
01178   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
01179     if (Value > Mask)
01180       return;
01181     assert(C.ICmpType == SystemZICMP::Any &&
01182            "Signedness shouldn't matter here.");
01183   } else
01184     return;
01185 
01186   // Make sure that the first operand is an i32 of the right extension type.
01187   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
01188                               ISD::SEXTLOAD :
01189                               ISD::ZEXTLOAD);
01190   if (C.Op0.getValueType() != MVT::i32 ||
01191       Load->getExtensionType() != ExtType)
01192     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
01193                            Load->getChain(), Load->getBasePtr(),
01194                            Load->getPointerInfo(), Load->getMemoryVT(),
01195                            Load->isVolatile(), Load->isNonTemporal(),
01196                            Load->isInvariant(), Load->getAlignment());
01197 
01198   // Make sure that the second operand is an i32 with the right value.
01199   if (C.Op1.getValueType() != MVT::i32 ||
01200       Value != ConstOp1->getZExtValue())
01201     C.Op1 = DAG.getConstant(Value, MVT::i32);
01202 }
01203 
01204 // Return true if Op is either an unextended load, or a load suitable
01205 // for integer register-memory comparisons of type ICmpType.
01206 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
01207   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
01208   if (Load) {
01209     // There are no instructions to compare a register with a memory byte.
01210     if (Load->getMemoryVT() == MVT::i8)
01211       return false;
01212     // Otherwise decide on extension type.
01213     switch (Load->getExtensionType()) {
01214     case ISD::NON_EXTLOAD:
01215       return true;
01216     case ISD::SEXTLOAD:
01217       return ICmpType != SystemZICMP::UnsignedOnly;
01218     case ISD::ZEXTLOAD:
01219       return ICmpType != SystemZICMP::SignedOnly;
01220     default:
01221       break;
01222     }
01223   }
01224   return false;
01225 }
01226 
01227 // Return true if it is better to swap the operands of C.
01228 static bool shouldSwapCmpOperands(const Comparison &C) {
01229   // Leave f128 comparisons alone, since they have no memory forms.
01230   if (C.Op0.getValueType() == MVT::f128)
01231     return false;
01232 
01233   // Always keep a floating-point constant second, since comparisons with
01234   // zero can use LOAD TEST and comparisons with other constants make a
01235   // natural memory operand.
01236   if (isa<ConstantFPSDNode>(C.Op1))
01237     return false;
01238 
01239   // Never swap comparisons with zero since there are many ways to optimize
01240   // those later.
01241   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
01242   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
01243     return false;
01244 
01245   // Also keep natural memory operands second if the loaded value is
01246   // only used here.  Several comparisons have memory forms.
01247   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
01248     return false;
01249 
01250   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
01251   // In that case we generally prefer the memory to be second.
01252   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
01253     // The only exceptions are when the second operand is a constant and
01254     // we can use things like CHHSI.
01255     if (!ConstOp1)
01256       return true;
01257     // The unsigned memory-immediate instructions can handle 16-bit
01258     // unsigned integers.
01259     if (C.ICmpType != SystemZICMP::SignedOnly &&
01260         isUInt<16>(ConstOp1->getZExtValue()))
01261       return false;
01262     // The signed memory-immediate instructions can handle 16-bit
01263     // signed integers.
01264     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
01265         isInt<16>(ConstOp1->getSExtValue()))
01266       return false;
01267     return true;
01268   }
01269 
01270   // Try to promote the use of CGFR and CLGFR.
01271   unsigned Opcode0 = C.Op0.getOpcode();
01272   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
01273     return true;
01274   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
01275     return true;
01276   if (C.ICmpType != SystemZICMP::SignedOnly &&
01277       Opcode0 == ISD::AND &&
01278       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
01279       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
01280     return true;
01281 
01282   return false;
01283 }
01284 
01285 // Return a version of comparison CC mask CCMask in which the LT and GT
01286 // actions are swapped.
01287 static unsigned reverseCCMask(unsigned CCMask) {
01288   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
01289           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
01290           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
01291           (CCMask & SystemZ::CCMASK_CMP_UO));
01292 }
01293 
01294 // Check whether C tests for equality between X and Y and whether X - Y
01295 // or Y - X is also computed.  In that case it's better to compare the
01296 // result of the subtraction against zero.
01297 static void adjustForSubtraction(SelectionDAG &DAG, Comparison &C) {
01298   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
01299       C.CCMask == SystemZ::CCMASK_CMP_NE) {
01300     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
01301       SDNode *N = *I;
01302       if (N->getOpcode() == ISD::SUB &&
01303           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
01304            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
01305         C.Op0 = SDValue(N, 0);
01306         C.Op1 = DAG.getConstant(0, N->getValueType(0));
01307         return;
01308       }
01309     }
01310   }
01311 }
01312 
01313 // Check whether C compares a floating-point value with zero and if that
01314 // floating-point value is also negated.  In this case we can use the
01315 // negation to set CC, so avoiding separate LOAD AND TEST and
01316 // LOAD (NEGATIVE/COMPLEMENT) instructions.
01317 static void adjustForFNeg(Comparison &C) {
01318   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
01319   if (C1 && C1->isZero()) {
01320     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
01321       SDNode *N = *I;
01322       if (N->getOpcode() == ISD::FNEG) {
01323         C.Op0 = SDValue(N, 0);
01324         C.CCMask = reverseCCMask(C.CCMask);
01325         return;
01326       }
01327     }
01328   }
01329 }
01330 
01331 // Check whether C compares (shl X, 32) with 0 and whether X is
01332 // also sign-extended.  In that case it is better to test the result
01333 // of the sign extension using LTGFR.
01334 //
01335 // This case is important because InstCombine transforms a comparison
01336 // with (sext (trunc X)) into a comparison with (shl X, 32).
01337 static void adjustForLTGFR(Comparison &C) {
01338   // Check for a comparison between (shl X, 32) and 0.
01339   if (C.Op0.getOpcode() == ISD::SHL &&
01340       C.Op0.getValueType() == MVT::i64 &&
01341       C.Op1.getOpcode() == ISD::Constant &&
01342       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
01343     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
01344     if (C1 && C1->getZExtValue() == 32) {
01345       SDValue ShlOp0 = C.Op0.getOperand(0);
01346       // See whether X has any SIGN_EXTEND_INREG uses.
01347       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
01348         SDNode *N = *I;
01349         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
01350             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
01351           C.Op0 = SDValue(N, 0);
01352           return;
01353         }
01354       }
01355     }
01356   }
01357 }
01358 
01359 // If C compares the truncation of an extending load, try to compare
01360 // the untruncated value instead.  This exposes more opportunities to
01361 // reuse CC.
01362 static void adjustICmpTruncate(SelectionDAG &DAG, Comparison &C) {
01363   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
01364       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
01365       C.Op1.getOpcode() == ISD::Constant &&
01366       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
01367     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
01368     if (L->getMemoryVT().getStoreSizeInBits()
01369         <= C.Op0.getValueType().getSizeInBits()) {
01370       unsigned Type = L->getExtensionType();
01371       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
01372           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
01373         C.Op0 = C.Op0.getOperand(0);
01374         C.Op1 = DAG.getConstant(0, C.Op0.getValueType());
01375       }
01376     }
01377   }
01378 }
01379 
01380 // Return true if shift operation N has an in-range constant shift value.
01381 // Store it in ShiftVal if so.
01382 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
01383   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
01384   if (!Shift)
01385     return false;
01386 
01387   uint64_t Amount = Shift->getZExtValue();
01388   if (Amount >= N.getValueType().getSizeInBits())
01389     return false;
01390 
01391   ShiftVal = Amount;
01392   return true;
01393 }
01394 
01395 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
01396 // instruction and whether the CC value is descriptive enough to handle
01397 // a comparison of type Opcode between the AND result and CmpVal.
01398 // CCMask says which comparison result is being tested and BitSize is
01399 // the number of bits in the operands.  If TEST UNDER MASK can be used,
01400 // return the corresponding CC mask, otherwise return 0.
01401 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
01402                                      uint64_t Mask, uint64_t CmpVal,
01403                                      unsigned ICmpType) {
01404   assert(Mask != 0 && "ANDs with zero should have been removed by now");
01405 
01406   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
01407   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
01408       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
01409     return 0;
01410 
01411   // Work out the masks for the lowest and highest bits.
01412   unsigned HighShift = 63 - countLeadingZeros(Mask);
01413   uint64_t High = uint64_t(1) << HighShift;
01414   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
01415 
01416   // Signed ordered comparisons are effectively unsigned if the sign
01417   // bit is dropped.
01418   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
01419 
01420   // Check for equality comparisons with 0, or the equivalent.
01421   if (CmpVal == 0) {
01422     if (CCMask == SystemZ::CCMASK_CMP_EQ)
01423       return SystemZ::CCMASK_TM_ALL_0;
01424     if (CCMask == SystemZ::CCMASK_CMP_NE)
01425       return SystemZ::CCMASK_TM_SOME_1;
01426   }
01427   if (EffectivelyUnsigned && CmpVal <= Low) {
01428     if (CCMask == SystemZ::CCMASK_CMP_LT)
01429       return SystemZ::CCMASK_TM_ALL_0;
01430     if (CCMask == SystemZ::CCMASK_CMP_GE)
01431       return SystemZ::CCMASK_TM_SOME_1;
01432   }
01433   if (EffectivelyUnsigned && CmpVal < Low) {
01434     if (CCMask == SystemZ::CCMASK_CMP_LE)
01435       return SystemZ::CCMASK_TM_ALL_0;
01436     if (CCMask == SystemZ::CCMASK_CMP_GT)
01437       return SystemZ::CCMASK_TM_SOME_1;
01438   }
01439 
01440   // Check for equality comparisons with the mask, or the equivalent.
01441   if (CmpVal == Mask) {
01442     if (CCMask == SystemZ::CCMASK_CMP_EQ)
01443       return SystemZ::CCMASK_TM_ALL_1;
01444     if (CCMask == SystemZ::CCMASK_CMP_NE)
01445       return SystemZ::CCMASK_TM_SOME_0;
01446   }
01447   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
01448     if (CCMask == SystemZ::CCMASK_CMP_GT)
01449       return SystemZ::CCMASK_TM_ALL_1;
01450     if (CCMask == SystemZ::CCMASK_CMP_LE)
01451       return SystemZ::CCMASK_TM_SOME_0;
01452   }
01453   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
01454     if (CCMask == SystemZ::CCMASK_CMP_GE)
01455       return SystemZ::CCMASK_TM_ALL_1;
01456     if (CCMask == SystemZ::CCMASK_CMP_LT)
01457       return SystemZ::CCMASK_TM_SOME_0;
01458   }
01459 
01460   // Check for ordered comparisons with the top bit.
01461   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
01462     if (CCMask == SystemZ::CCMASK_CMP_LE)
01463       return SystemZ::CCMASK_TM_MSB_0;
01464     if (CCMask == SystemZ::CCMASK_CMP_GT)
01465       return SystemZ::CCMASK_TM_MSB_1;
01466   }
01467   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
01468     if (CCMask == SystemZ::CCMASK_CMP_LT)
01469       return SystemZ::CCMASK_TM_MSB_0;
01470     if (CCMask == SystemZ::CCMASK_CMP_GE)
01471       return SystemZ::CCMASK_TM_MSB_1;
01472   }
01473 
01474   // If there are just two bits, we can do equality checks for Low and High
01475   // as well.
01476   if (Mask == Low + High) {
01477     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
01478       return SystemZ::CCMASK_TM_MIXED_MSB_0;
01479     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
01480       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
01481     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
01482       return SystemZ::CCMASK_TM_MIXED_MSB_1;
01483     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
01484       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
01485   }
01486 
01487   // Looks like we've exhausted our options.
01488   return 0;
01489 }
01490 
01491 // See whether C can be implemented as a TEST UNDER MASK instruction.
01492 // Update the arguments with the TM version if so.
01493 static void adjustForTestUnderMask(SelectionDAG &DAG, Comparison &C) {
01494   // Check that we have a comparison with a constant.
01495   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
01496   if (!ConstOp1)
01497     return;
01498   uint64_t CmpVal = ConstOp1->getZExtValue();
01499 
01500   // Check whether the nonconstant input is an AND with a constant mask.
01501   Comparison NewC(C);
01502   uint64_t MaskVal;
01503   ConstantSDNode *Mask = nullptr;
01504   if (C.Op0.getOpcode() == ISD::AND) {
01505     NewC.Op0 = C.Op0.getOperand(0);
01506     NewC.Op1 = C.Op0.getOperand(1);
01507     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
01508     if (!Mask)
01509       return;
01510     MaskVal = Mask->getZExtValue();
01511   } else {
01512     // There is no instruction to compare with a 64-bit immediate
01513     // so use TMHH instead if possible.  We need an unsigned ordered
01514     // comparison with an i64 immediate.
01515     if (NewC.Op0.getValueType() != MVT::i64 ||
01516         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
01517         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
01518         NewC.ICmpType == SystemZICMP::SignedOnly)
01519       return;
01520     // Convert LE and GT comparisons into LT and GE.
01521     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
01522         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
01523       if (CmpVal == uint64_t(-1))
01524         return;
01525       CmpVal += 1;
01526       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
01527     }
01528     // If the low N bits of Op1 are zero than the low N bits of Op0 can
01529     // be masked off without changing the result.
01530     MaskVal = -(CmpVal & -CmpVal);
01531     NewC.ICmpType = SystemZICMP::UnsignedOnly;
01532   }
01533 
01534   // Check whether the combination of mask, comparison value and comparison
01535   // type are suitable.
01536   unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
01537   unsigned NewCCMask, ShiftVal;
01538   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
01539       NewC.Op0.getOpcode() == ISD::SHL &&
01540       isSimpleShift(NewC.Op0, ShiftVal) &&
01541       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
01542                                         MaskVal >> ShiftVal,
01543                                         CmpVal >> ShiftVal,
01544                                         SystemZICMP::Any))) {
01545     NewC.Op0 = NewC.Op0.getOperand(0);
01546     MaskVal >>= ShiftVal;
01547   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
01548              NewC.Op0.getOpcode() == ISD::SRL &&
01549              isSimpleShift(NewC.Op0, ShiftVal) &&
01550              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
01551                                                MaskVal << ShiftVal,
01552                                                CmpVal << ShiftVal,
01553                                                SystemZICMP::UnsignedOnly))) {
01554     NewC.Op0 = NewC.Op0.getOperand(0);
01555     MaskVal <<= ShiftVal;
01556   } else {
01557     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
01558                                      NewC.ICmpType);
01559     if (!NewCCMask)
01560       return;
01561   }
01562 
01563   // Go ahead and make the change.
01564   C.Opcode = SystemZISD::TM;
01565   C.Op0 = NewC.Op0;
01566   if (Mask && Mask->getZExtValue() == MaskVal)
01567     C.Op1 = SDValue(Mask, 0);
01568   else
01569     C.Op1 = DAG.getConstant(MaskVal, C.Op0.getValueType());
01570   C.CCValid = SystemZ::CCMASK_TM;
01571   C.CCMask = NewCCMask;
01572 }
01573 
01574 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
01575 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
01576                          ISD::CondCode Cond) {
01577   Comparison C(CmpOp0, CmpOp1);
01578   C.CCMask = CCMaskForCondCode(Cond);
01579   if (C.Op0.getValueType().isFloatingPoint()) {
01580     C.CCValid = SystemZ::CCMASK_FCMP;
01581     C.Opcode = SystemZISD::FCMP;
01582     adjustForFNeg(C);
01583   } else {
01584     C.CCValid = SystemZ::CCMASK_ICMP;
01585     C.Opcode = SystemZISD::ICMP;
01586     // Choose the type of comparison.  Equality and inequality tests can
01587     // use either signed or unsigned comparisons.  The choice also doesn't
01588     // matter if both sign bits are known to be clear.  In those cases we
01589     // want to give the main isel code the freedom to choose whichever
01590     // form fits best.
01591     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
01592         C.CCMask == SystemZ::CCMASK_CMP_NE ||
01593         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
01594       C.ICmpType = SystemZICMP::Any;
01595     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
01596       C.ICmpType = SystemZICMP::UnsignedOnly;
01597     else
01598       C.ICmpType = SystemZICMP::SignedOnly;
01599     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
01600     adjustZeroCmp(DAG, C);
01601     adjustSubwordCmp(DAG, C);
01602     adjustForSubtraction(DAG, C);
01603     adjustForLTGFR(C);
01604     adjustICmpTruncate(DAG, C);
01605   }
01606 
01607   if (shouldSwapCmpOperands(C)) {
01608     std::swap(C.Op0, C.Op1);
01609     C.CCMask = reverseCCMask(C.CCMask);
01610   }
01611 
01612   adjustForTestUnderMask(DAG, C);
01613   return C;
01614 }
01615 
01616 // Emit the comparison instruction described by C.
01617 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
01618   if (C.Opcode == SystemZISD::ICMP)
01619     return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
01620                        DAG.getConstant(C.ICmpType, MVT::i32));
01621   if (C.Opcode == SystemZISD::TM) {
01622     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
01623                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
01624     return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
01625                        DAG.getConstant(RegisterOnly, MVT::i32));
01626   }
01627   return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
01628 }
01629 
01630 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
01631 // 64 bits.  Extend is the extension type to use.  Store the high part
01632 // in Hi and the low part in Lo.
01633 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
01634                             unsigned Extend, SDValue Op0, SDValue Op1,
01635                             SDValue &Hi, SDValue &Lo) {
01636   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
01637   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
01638   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
01639   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, MVT::i64));
01640   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
01641   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
01642 }
01643 
01644 // Lower a binary operation that produces two VT results, one in each
01645 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
01646 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
01647 // on the extended Op0 and (unextended) Op1.  Store the even register result
01648 // in Even and the odd register result in Odd.
01649 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
01650                              unsigned Extend, unsigned Opcode,
01651                              SDValue Op0, SDValue Op1,
01652                              SDValue &Even, SDValue &Odd) {
01653   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
01654   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
01655                                SDValue(In128, 0), Op1);
01656   bool Is32Bit = is32Bit(VT);
01657   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
01658   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
01659 }
01660 
01661 // Return an i32 value that is 1 if the CC value produced by Glue is
01662 // in the mask CCMask and 0 otherwise.  CC is known to have a value
01663 // in CCValid, so other values can be ignored.
01664 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
01665                          unsigned CCValid, unsigned CCMask) {
01666   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
01667   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
01668 
01669   if (Conversion.XORValue)
01670     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
01671                          DAG.getConstant(Conversion.XORValue, MVT::i32));
01672 
01673   if (Conversion.AddValue)
01674     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
01675                          DAG.getConstant(Conversion.AddValue, MVT::i32));
01676 
01677   // The SHR/AND sequence should get optimized to an RISBG.
01678   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
01679                        DAG.getConstant(Conversion.Bit, MVT::i32));
01680   if (Conversion.Bit != 31)
01681     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
01682                          DAG.getConstant(1, MVT::i32));
01683   return Result;
01684 }
01685 
01686 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
01687                                           SelectionDAG &DAG) const {
01688   SDValue CmpOp0   = Op.getOperand(0);
01689   SDValue CmpOp1   = Op.getOperand(1);
01690   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
01691   SDLoc DL(Op);
01692 
01693   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
01694   SDValue Glue = emitCmp(DAG, DL, C);
01695   return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
01696 }
01697 
01698 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
01699   SDValue Chain    = Op.getOperand(0);
01700   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
01701   SDValue CmpOp0   = Op.getOperand(2);
01702   SDValue CmpOp1   = Op.getOperand(3);
01703   SDValue Dest     = Op.getOperand(4);
01704   SDLoc DL(Op);
01705 
01706   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
01707   SDValue Glue = emitCmp(DAG, DL, C);
01708   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
01709                      Chain, DAG.getConstant(C.CCValid, MVT::i32),
01710                      DAG.getConstant(C.CCMask, MVT::i32), Dest, Glue);
01711 }
01712 
01713 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
01714 // allowing Pos and Neg to be wider than CmpOp.
01715 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
01716   return (Neg.getOpcode() == ISD::SUB &&
01717           Neg.getOperand(0).getOpcode() == ISD::Constant &&
01718           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
01719           Neg.getOperand(1) == Pos &&
01720           (Pos == CmpOp ||
01721            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
01722             Pos.getOperand(0) == CmpOp)));
01723 }
01724 
01725 // Return the absolute or negative absolute of Op; IsNegative decides which.
01726 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
01727                            bool IsNegative) {
01728   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
01729   if (IsNegative)
01730     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
01731                      DAG.getConstant(0, Op.getValueType()), Op);
01732   return Op;
01733 }
01734 
01735 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
01736                                               SelectionDAG &DAG) const {
01737   SDValue CmpOp0   = Op.getOperand(0);
01738   SDValue CmpOp1   = Op.getOperand(1);
01739   SDValue TrueOp   = Op.getOperand(2);
01740   SDValue FalseOp  = Op.getOperand(3);
01741   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
01742   SDLoc DL(Op);
01743 
01744   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
01745 
01746   // Check for absolute and negative-absolute selections, including those
01747   // where the comparison value is sign-extended (for LPGFR and LNGFR).
01748   // This check supplements the one in DAGCombiner.
01749   if (C.Opcode == SystemZISD::ICMP &&
01750       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
01751       C.CCMask != SystemZ::CCMASK_CMP_NE &&
01752       C.Op1.getOpcode() == ISD::Constant &&
01753       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
01754     if (isAbsolute(C.Op0, TrueOp, FalseOp))
01755       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
01756     if (isAbsolute(C.Op0, FalseOp, TrueOp))
01757       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
01758   }
01759 
01760   SDValue Glue = emitCmp(DAG, DL, C);
01761 
01762   // Special case for handling -1/0 results.  The shifts we use here
01763   // should get optimized with the IPM conversion sequence.
01764   auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
01765   auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
01766   if (TrueC && FalseC) {
01767     int64_t TrueVal = TrueC->getSExtValue();
01768     int64_t FalseVal = FalseC->getSExtValue();
01769     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
01770       // Invert the condition if we want -1 on false.
01771       if (TrueVal == 0)
01772         C.CCMask ^= C.CCValid;
01773       SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
01774       EVT VT = Op.getValueType();
01775       // Extend the result to VT.  Upper bits are ignored.
01776       if (!is32Bit(VT))
01777         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
01778       // Sign-extend from the low bit.
01779       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, MVT::i32);
01780       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
01781       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
01782     }
01783   }
01784 
01785   SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, MVT::i32),
01786                    DAG.getConstant(C.CCMask, MVT::i32), Glue};
01787 
01788   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
01789   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
01790 }
01791 
01792 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
01793                                                   SelectionDAG &DAG) const {
01794   SDLoc DL(Node);
01795   const GlobalValue *GV = Node->getGlobal();
01796   int64_t Offset = Node->getOffset();
01797   EVT PtrVT = getPointerTy();
01798   Reloc::Model RM = DAG.getTarget().getRelocationModel();
01799   CodeModel::Model CM = DAG.getTarget().getCodeModel();
01800 
01801   SDValue Result;
01802   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
01803     // Assign anchors at 1<<12 byte boundaries.
01804     uint64_t Anchor = Offset & ~uint64_t(0xfff);
01805     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
01806     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01807 
01808     // The offset can be folded into the address if it is aligned to a halfword.
01809     Offset -= Anchor;
01810     if (Offset != 0 && (Offset & 1) == 0) {
01811       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
01812       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
01813       Offset = 0;
01814     }
01815   } else {
01816     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
01817     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01818     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
01819                          MachinePointerInfo::getGOT(), false, false, false, 0);
01820   }
01821 
01822   // If there was a non-zero offset that we didn't fold, create an explicit
01823   // addition for it.
01824   if (Offset != 0)
01825     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
01826                          DAG.getConstant(Offset, PtrVT));
01827 
01828   return Result;
01829 }
01830 
01831 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
01832                                                  SelectionDAG &DAG,
01833                                                  unsigned Opcode,
01834                                                  SDValue GOTOffset) const {
01835   SDLoc DL(Node);
01836   EVT PtrVT = getPointerTy();
01837   SDValue Chain = DAG.getEntryNode();
01838   SDValue Glue;
01839 
01840   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
01841   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
01842   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
01843   Glue = Chain.getValue(1);
01844   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
01845   Glue = Chain.getValue(1);
01846 
01847   // The first call operand is the chain and the second is the TLS symbol.
01848   SmallVector<SDValue, 8> Ops;
01849   Ops.push_back(Chain);
01850   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
01851                                            Node->getValueType(0),
01852                                            0, 0));
01853 
01854   // Add argument registers to the end of the list so that they are
01855   // known live into the call.
01856   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
01857   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
01858 
01859   // Add a register mask operand representing the call-preserved registers.
01860   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
01861   const uint32_t *Mask = TRI->getCallPreservedMask(CallingConv::C);
01862   assert(Mask && "Missing call preserved mask for calling convention");
01863   Ops.push_back(DAG.getRegisterMask(Mask));
01864 
01865   // Glue the call to the argument copies.
01866   Ops.push_back(Glue);
01867 
01868   // Emit the call.
01869   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
01870   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
01871   Glue = Chain.getValue(1);
01872 
01873   // Copy the return value from %r2.
01874   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
01875 }
01876 
01877 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
01878                  SelectionDAG &DAG) const {
01879   SDLoc DL(Node);
01880   const GlobalValue *GV = Node->getGlobal();
01881   EVT PtrVT = getPointerTy();
01882   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
01883 
01884   // The high part of the thread pointer is in access register 0.
01885   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
01886                              DAG.getConstant(0, MVT::i32));
01887   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
01888 
01889   // The low part of the thread pointer is in access register 1.
01890   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
01891                              DAG.getConstant(1, MVT::i32));
01892   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
01893 
01894   // Merge them into a single 64-bit address.
01895   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
01896             DAG.getConstant(32, PtrVT));
01897   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
01898 
01899   // Get the offset of GA from the thread pointer, based on the TLS model.
01900   SDValue Offset;
01901   switch (model) {
01902     case TLSModel::GeneralDynamic: {
01903       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
01904       SystemZConstantPoolValue *CPV =
01905         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
01906 
01907       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
01908       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
01909                            Offset, MachinePointerInfo::getConstantPool(),
01910                            false, false, false, 0);
01911 
01912       // Call __tls_get_offset to retrieve the offset.
01913       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
01914       break;
01915     }
01916 
01917     case TLSModel::LocalDynamic: {
01918       // Load the GOT offset of the module ID.
01919       SystemZConstantPoolValue *CPV =
01920         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
01921 
01922       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
01923       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
01924                            Offset, MachinePointerInfo::getConstantPool(),
01925                            false, false, false, 0);
01926 
01927       // Call __tls_get_offset to retrieve the module base offset.
01928       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
01929 
01930       // Note: The SystemZLDCleanupPass will remove redundant computations
01931       // of the module base offset.  Count total number of local-dynamic
01932       // accesses to trigger execution of that pass.
01933       SystemZMachineFunctionInfo* MFI =
01934         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
01935       MFI->incNumLocalDynamicTLSAccesses();
01936 
01937       // Add the per-symbol offset.
01938       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
01939 
01940       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
01941       DTPOffset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
01942                               DTPOffset, MachinePointerInfo::getConstantPool(),
01943                               false, false, false, 0);
01944 
01945       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
01946       break;
01947     }
01948 
01949     case TLSModel::InitialExec: {
01950       // Load the offset from the GOT.
01951       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01952                                           SystemZII::MO_INDNTPOFF);
01953       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
01954       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
01955                            Offset, MachinePointerInfo::getGOT(),
01956                            false, false, false, 0);
01957       break;
01958     }
01959 
01960     case TLSModel::LocalExec: {
01961       // Force the offset into the constant pool and load it from there.
01962       SystemZConstantPoolValue *CPV =
01963         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
01964 
01965       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
01966       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
01967                            Offset, MachinePointerInfo::getConstantPool(),
01968                            false, false, false, 0);
01969       break;
01970     }
01971   }
01972 
01973   // Add the base and offset together.
01974   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
01975 }
01976 
01977 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
01978                                                  SelectionDAG &DAG) const {
01979   SDLoc DL(Node);
01980   const BlockAddress *BA = Node->getBlockAddress();
01981   int64_t Offset = Node->getOffset();
01982   EVT PtrVT = getPointerTy();
01983 
01984   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
01985   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01986   return Result;
01987 }
01988 
01989 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
01990                                               SelectionDAG &DAG) const {
01991   SDLoc DL(JT);
01992   EVT PtrVT = getPointerTy();
01993   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
01994 
01995   // Use LARL to load the address of the table.
01996   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01997 }
01998 
01999 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
02000                                                  SelectionDAG &DAG) const {
02001   SDLoc DL(CP);
02002   EVT PtrVT = getPointerTy();
02003 
02004   SDValue Result;
02005   if (CP->isMachineConstantPoolEntry())
02006     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
02007                CP->getAlignment());
02008   else
02009     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
02010                CP->getAlignment(), CP->getOffset());
02011 
02012   // Use LARL to load the address of the constant pool entry.
02013   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
02014 }
02015 
02016 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
02017                                             SelectionDAG &DAG) const {
02018   SDLoc DL(Op);
02019   SDValue In = Op.getOperand(0);
02020   EVT InVT = In.getValueType();
02021   EVT ResVT = Op.getValueType();
02022 
02023   if (InVT == MVT::i32 && ResVT == MVT::f32) {
02024     SDValue In64;
02025     if (Subtarget.hasHighWord()) {
02026       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
02027                                        MVT::i64);
02028       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
02029                                        MVT::i64, SDValue(U64, 0), In);
02030     } else {
02031       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
02032       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
02033                          DAG.getConstant(32, MVT::i64));
02034     }
02035     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
02036     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
02037                                       DL, MVT::f32, Out64);
02038   }
02039   if (InVT == MVT::f32 && ResVT == MVT::i32) {
02040     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
02041     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
02042                                              MVT::f64, SDValue(U64, 0), In);
02043     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
02044     if (Subtarget.hasHighWord())
02045       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
02046                                         MVT::i32, Out64);
02047     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
02048                                 DAG.getConstant(32, MVT::i64));
02049     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
02050   }
02051   llvm_unreachable("Unexpected bitcast combination");
02052 }
02053 
02054 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
02055                                             SelectionDAG &DAG) const {
02056   MachineFunction &MF = DAG.getMachineFunction();
02057   SystemZMachineFunctionInfo *FuncInfo =
02058     MF.getInfo<SystemZMachineFunctionInfo>();
02059   EVT PtrVT = getPointerTy();
02060 
02061   SDValue Chain   = Op.getOperand(0);
02062   SDValue Addr    = Op.getOperand(1);
02063   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02064   SDLoc DL(Op);
02065 
02066   // The initial values of each field.
02067   const unsigned NumFields = 4;
02068   SDValue Fields[NumFields] = {
02069     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
02070     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
02071     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
02072     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
02073   };
02074 
02075   // Store each field into its respective slot.
02076   SDValue MemOps[NumFields];
02077   unsigned Offset = 0;
02078   for (unsigned I = 0; I < NumFields; ++I) {
02079     SDValue FieldAddr = Addr;
02080     if (Offset != 0)
02081       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
02082                               DAG.getIntPtrConstant(Offset));
02083     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
02084                              MachinePointerInfo(SV, Offset),
02085                              false, false, 0);
02086     Offset += 8;
02087   }
02088   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
02089 }
02090 
02091 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
02092                                            SelectionDAG &DAG) const {
02093   SDValue Chain      = Op.getOperand(0);
02094   SDValue DstPtr     = Op.getOperand(1);
02095   SDValue SrcPtr     = Op.getOperand(2);
02096   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
02097   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
02098   SDLoc DL(Op);
02099 
02100   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
02101                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
02102                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
02103 }
02104 
02105 SDValue SystemZTargetLowering::
02106 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
02107   SDValue Chain = Op.getOperand(0);
02108   SDValue Size  = Op.getOperand(1);
02109   SDLoc DL(Op);
02110 
02111   unsigned SPReg = getStackPointerRegisterToSaveRestore();
02112 
02113   // Get a reference to the stack pointer.
02114   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
02115 
02116   // Get the new stack pointer value.
02117   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
02118 
02119   // Copy the new stack pointer back.
02120   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
02121 
02122   // The allocated data lives above the 160 bytes allocated for the standard
02123   // frame, plus any outgoing stack arguments.  We don't know how much that
02124   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
02125   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
02126   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
02127 
02128   SDValue Ops[2] = { Result, Chain };
02129   return DAG.getMergeValues(Ops, DL);
02130 }
02131 
02132 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
02133                                               SelectionDAG &DAG) const {
02134   EVT VT = Op.getValueType();
02135   SDLoc DL(Op);
02136   SDValue Ops[2];
02137   if (is32Bit(VT))
02138     // Just do a normal 64-bit multiplication and extract the results.
02139     // We define this so that it can be used for constant division.
02140     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
02141                     Op.getOperand(1), Ops[1], Ops[0]);
02142   else {
02143     // Do a full 128-bit multiplication based on UMUL_LOHI64:
02144     //
02145     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
02146     //
02147     // but using the fact that the upper halves are either all zeros
02148     // or all ones:
02149     //
02150     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
02151     //
02152     // and grouping the right terms together since they are quicker than the
02153     // multiplication:
02154     //
02155     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
02156     SDValue C63 = DAG.getConstant(63, MVT::i64);
02157     SDValue LL = Op.getOperand(0);
02158     SDValue RL = Op.getOperand(1);
02159     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
02160     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
02161     // UMUL_LOHI64 returns the low result in the odd register and the high
02162     // result in the even register.  SMUL_LOHI is defined to return the
02163     // low half first, so the results are in reverse order.
02164     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
02165                      LL, RL, Ops[1], Ops[0]);
02166     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
02167     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
02168     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
02169     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
02170   }
02171   return DAG.getMergeValues(Ops, DL);
02172 }
02173 
02174 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
02175                                               SelectionDAG &DAG) const {
02176   EVT VT = Op.getValueType();
02177   SDLoc DL(Op);
02178   SDValue Ops[2];
02179   if (is32Bit(VT))
02180     // Just do a normal 64-bit multiplication and extract the results.
02181     // We define this so that it can be used for constant division.
02182     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
02183                     Op.getOperand(1), Ops[1], Ops[0]);
02184   else
02185     // UMUL_LOHI64 returns the low result in the odd register and the high
02186     // result in the even register.  UMUL_LOHI is defined to return the
02187     // low half first, so the results are in reverse order.
02188     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
02189                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
02190   return DAG.getMergeValues(Ops, DL);
02191 }
02192 
02193 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
02194                                             SelectionDAG &DAG) const {
02195   SDValue Op0 = Op.getOperand(0);
02196   SDValue Op1 = Op.getOperand(1);
02197   EVT VT = Op.getValueType();
02198   SDLoc DL(Op);
02199   unsigned Opcode;
02200 
02201   // We use DSGF for 32-bit division.
02202   if (is32Bit(VT)) {
02203     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
02204     Opcode = SystemZISD::SDIVREM32;
02205   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
02206     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
02207     Opcode = SystemZISD::SDIVREM32;
02208   } else    
02209     Opcode = SystemZISD::SDIVREM64;
02210 
02211   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
02212   // input is "don't care".  The instruction returns the remainder in
02213   // the even register and the quotient in the odd register.
02214   SDValue Ops[2];
02215   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
02216                    Op0, Op1, Ops[1], Ops[0]);
02217   return DAG.getMergeValues(Ops, DL);
02218 }
02219 
02220 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
02221                                             SelectionDAG &DAG) const {
02222   EVT VT = Op.getValueType();
02223   SDLoc DL(Op);
02224 
02225   // DL(G) uses a double-width dividend, so we need to clear the even
02226   // register in the GR128 input.  The instruction returns the remainder
02227   // in the even register and the quotient in the odd register.
02228   SDValue Ops[2];
02229   if (is32Bit(VT))
02230     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
02231                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
02232   else
02233     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
02234                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
02235   return DAG.getMergeValues(Ops, DL);
02236 }
02237 
02238 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
02239   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
02240 
02241   // Get the known-zero masks for each operand.
02242   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
02243   APInt KnownZero[2], KnownOne[2];
02244   DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
02245   DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
02246 
02247   // See if the upper 32 bits of one operand and the lower 32 bits of the
02248   // other are known zero.  They are the low and high operands respectively.
02249   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
02250                        KnownZero[1].getZExtValue() };
02251   unsigned High, Low;
02252   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
02253     High = 1, Low = 0;
02254   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
02255     High = 0, Low = 1;
02256   else
02257     return Op;
02258 
02259   SDValue LowOp = Ops[Low];
02260   SDValue HighOp = Ops[High];
02261 
02262   // If the high part is a constant, we're better off using IILH.
02263   if (HighOp.getOpcode() == ISD::Constant)
02264     return Op;
02265 
02266   // If the low part is a constant that is outside the range of LHI,
02267   // then we're better off using IILF.
02268   if (LowOp.getOpcode() == ISD::Constant) {
02269     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
02270     if (!isInt<16>(Value))
02271       return Op;
02272   }
02273 
02274   // Check whether the high part is an AND that doesn't change the
02275   // high 32 bits and just masks out low bits.  We can skip it if so.
02276   if (HighOp.getOpcode() == ISD::AND &&
02277       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
02278     SDValue HighOp0 = HighOp.getOperand(0);
02279     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
02280     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
02281       HighOp = HighOp0;
02282   }
02283 
02284   // Take advantage of the fact that all GR32 operations only change the
02285   // low 32 bits by truncating Low to an i32 and inserting it directly
02286   // using a subreg.  The interesting cases are those where the truncation
02287   // can be folded.
02288   SDLoc DL(Op);
02289   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
02290   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
02291                                    MVT::i64, HighOp, Low32);
02292 }
02293 
02294 // Op is an atomic load.  Lower it into a normal volatile load.
02295 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
02296                                                 SelectionDAG &DAG) const {
02297   auto *Node = cast<AtomicSDNode>(Op.getNode());
02298   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
02299                         Node->getChain(), Node->getBasePtr(),
02300                         Node->getMemoryVT(), Node->getMemOperand());
02301 }
02302 
02303 // Op is an atomic store.  Lower it into a normal volatile store followed
02304 // by a serialization.
02305 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
02306                                                  SelectionDAG &DAG) const {
02307   auto *Node = cast<AtomicSDNode>(Op.getNode());
02308   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
02309                                     Node->getBasePtr(), Node->getMemoryVT(),
02310                                     Node->getMemOperand());
02311   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
02312                                     Chain), 0);
02313 }
02314 
02315 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
02316 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
02317 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
02318                                                    SelectionDAG &DAG,
02319                                                    unsigned Opcode) const {
02320   auto *Node = cast<AtomicSDNode>(Op.getNode());
02321 
02322   // 32-bit operations need no code outside the main loop.
02323   EVT NarrowVT = Node->getMemoryVT();
02324   EVT WideVT = MVT::i32;
02325   if (NarrowVT == WideVT)
02326     return Op;
02327 
02328   int64_t BitSize = NarrowVT.getSizeInBits();
02329   SDValue ChainIn = Node->getChain();
02330   SDValue Addr = Node->getBasePtr();
02331   SDValue Src2 = Node->getVal();
02332   MachineMemOperand *MMO = Node->getMemOperand();
02333   SDLoc DL(Node);
02334   EVT PtrVT = Addr.getValueType();
02335 
02336   // Convert atomic subtracts of constants into additions.
02337   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
02338     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
02339       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
02340       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
02341     }
02342 
02343   // Get the address of the containing word.
02344   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
02345                                     DAG.getConstant(-4, PtrVT));
02346 
02347   // Get the number of bits that the word must be rotated left in order
02348   // to bring the field to the top bits of a GR32.
02349   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
02350                                  DAG.getConstant(3, PtrVT));
02351   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
02352 
02353   // Get the complementing shift amount, for rotating a field in the top
02354   // bits back to its proper position.
02355   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
02356                                     DAG.getConstant(0, WideVT), BitShift);
02357 
02358   // Extend the source operand to 32 bits and prepare it for the inner loop.
02359   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
02360   // operations require the source to be shifted in advance.  (This shift
02361   // can be folded if the source is constant.)  For AND and NAND, the lower
02362   // bits must be set, while for other opcodes they should be left clear.
02363   if (Opcode != SystemZISD::ATOMIC_SWAPW)
02364     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
02365                        DAG.getConstant(32 - BitSize, WideVT));
02366   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
02367       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
02368     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
02369                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
02370 
02371   // Construct the ATOMIC_LOADW_* node.
02372   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
02373   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
02374                     DAG.getConstant(BitSize, WideVT) };
02375   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
02376                                              NarrowVT, MMO);
02377 
02378   // Rotate the result of the final CS so that the field is in the lower
02379   // bits of a GR32, then truncate it.
02380   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
02381                                     DAG.getConstant(BitSize, WideVT));
02382   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
02383 
02384   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
02385   return DAG.getMergeValues(RetOps, DL);
02386 }
02387 
02388 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
02389 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
02390 // operations into additions.
02391 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
02392                                                     SelectionDAG &DAG) const {
02393   auto *Node = cast<AtomicSDNode>(Op.getNode());
02394   EVT MemVT = Node->getMemoryVT();
02395   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
02396     // A full-width operation.
02397     assert(Op.getValueType() == MemVT && "Mismatched VTs");
02398     SDValue Src2 = Node->getVal();
02399     SDValue NegSrc2;
02400     SDLoc DL(Src2);
02401 
02402     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
02403       // Use an addition if the operand is constant and either LAA(G) is
02404       // available or the negative value is in the range of A(G)FHI.
02405       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
02406       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
02407         NegSrc2 = DAG.getConstant(Value, MemVT);
02408     } else if (Subtarget.hasInterlockedAccess1())
02409       // Use LAA(G) if available.
02410       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, MemVT),
02411                             Src2);
02412 
02413     if (NegSrc2.getNode())
02414       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
02415                            Node->getChain(), Node->getBasePtr(), NegSrc2,
02416                            Node->getMemOperand(), Node->getOrdering(),
02417                            Node->getSynchScope());
02418 
02419     // Use the node as-is.
02420     return Op;
02421   }
02422 
02423   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
02424 }
02425 
02426 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
02427 // into a fullword ATOMIC_CMP_SWAPW operation.
02428 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
02429                                                     SelectionDAG &DAG) const {
02430   auto *Node = cast<AtomicSDNode>(Op.getNode());
02431 
02432   // We have native support for 32-bit compare and swap.
02433   EVT NarrowVT = Node->getMemoryVT();
02434   EVT WideVT = MVT::i32;
02435   if (NarrowVT == WideVT)
02436     return Op;
02437 
02438   int64_t BitSize = NarrowVT.getSizeInBits();
02439   SDValue ChainIn = Node->getOperand(0);
02440   SDValue Addr = Node->getOperand(1);
02441   SDValue CmpVal = Node->getOperand(2);
02442   SDValue SwapVal = Node->getOperand(3);
02443   MachineMemOperand *MMO = Node->getMemOperand();
02444   SDLoc DL(Node);
02445   EVT PtrVT = Addr.getValueType();
02446 
02447   // Get the address of the containing word.
02448   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
02449                                     DAG.getConstant(-4, PtrVT));
02450 
02451   // Get the number of bits that the word must be rotated left in order
02452   // to bring the field to the top bits of a GR32.
02453   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
02454                                  DAG.getConstant(3, PtrVT));
02455   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
02456 
02457   // Get the complementing shift amount, for rotating a field in the top
02458   // bits back to its proper position.
02459   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
02460                                     DAG.getConstant(0, WideVT), BitShift);
02461 
02462   // Construct the ATOMIC_CMP_SWAPW node.
02463   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
02464   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
02465                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
02466   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
02467                                              VTList, Ops, NarrowVT, MMO);
02468   return AtomicOp;
02469 }
02470 
02471 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
02472                                               SelectionDAG &DAG) const {
02473   MachineFunction &MF = DAG.getMachineFunction();
02474   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
02475   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
02476                             SystemZ::R15D, Op.getValueType());
02477 }
02478 
02479 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
02480                                                  SelectionDAG &DAG) const {
02481   MachineFunction &MF = DAG.getMachineFunction();
02482   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
02483   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
02484                           SystemZ::R15D, Op.getOperand(1));
02485 }
02486 
02487 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
02488                                              SelectionDAG &DAG) const {
02489   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
02490   if (!IsData)
02491     // Just preserve the chain.
02492     return Op.getOperand(0);
02493 
02494   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
02495   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
02496   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
02497   SDValue Ops[] = {
02498     Op.getOperand(0),
02499     DAG.getConstant(Code, MVT::i32),
02500     Op.getOperand(1)
02501   };
02502   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, SDLoc(Op),
02503                                  Node->getVTList(), Ops,
02504                                  Node->getMemoryVT(), Node->getMemOperand());
02505 }
02506 
02507 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
02508                                               SelectionDAG &DAG) const {
02509   switch (Op.getOpcode()) {
02510   case ISD::BR_CC:
02511     return lowerBR_CC(Op, DAG);
02512   case ISD::SELECT_CC:
02513     return lowerSELECT_CC(Op, DAG);
02514   case ISD::SETCC:
02515     return lowerSETCC(Op, DAG);
02516   case ISD::GlobalAddress:
02517     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
02518   case ISD::GlobalTLSAddress:
02519     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
02520   case ISD::BlockAddress:
02521     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
02522   case ISD::JumpTable:
02523     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
02524   case ISD::ConstantPool:
02525     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
02526   case ISD::BITCAST:
02527     return lowerBITCAST(Op, DAG);
02528   case ISD::VASTART:
02529     return lowerVASTART(Op, DAG);
02530   case ISD::VACOPY:
02531     return lowerVACOPY(Op, DAG);
02532   case ISD::DYNAMIC_STACKALLOC:
02533     return lowerDYNAMIC_STACKALLOC(Op, DAG);
02534   case ISD::SMUL_LOHI:
02535     return lowerSMUL_LOHI(Op, DAG);
02536   case ISD::UMUL_LOHI:
02537     return lowerUMUL_LOHI(Op, DAG);
02538   case ISD::SDIVREM:
02539     return lowerSDIVREM(Op, DAG);
02540   case ISD::UDIVREM:
02541     return lowerUDIVREM(Op, DAG);
02542   case ISD::OR:
02543     return lowerOR(Op, DAG);
02544   case ISD::ATOMIC_SWAP:
02545     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
02546   case ISD::ATOMIC_STORE:
02547     return lowerATOMIC_STORE(Op, DAG);
02548   case ISD::ATOMIC_LOAD:
02549     return lowerATOMIC_LOAD(Op, DAG);
02550   case ISD::ATOMIC_LOAD_ADD:
02551     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
02552   case ISD::ATOMIC_LOAD_SUB:
02553     return lowerATOMIC_LOAD_SUB(Op, DAG);
02554   case ISD::ATOMIC_LOAD_AND:
02555     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
02556   case ISD::ATOMIC_LOAD_OR:
02557     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
02558   case ISD::ATOMIC_LOAD_XOR:
02559     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
02560   case ISD::ATOMIC_LOAD_NAND:
02561     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
02562   case ISD::ATOMIC_LOAD_MIN:
02563     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
02564   case ISD::ATOMIC_LOAD_MAX:
02565     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
02566   case ISD::ATOMIC_LOAD_UMIN:
02567     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
02568   case ISD::ATOMIC_LOAD_UMAX:
02569     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
02570   case ISD::ATOMIC_CMP_SWAP:
02571     return lowerATOMIC_CMP_SWAP(Op, DAG);
02572   case ISD::STACKSAVE:
02573     return lowerSTACKSAVE(Op, DAG);
02574   case ISD::STACKRESTORE:
02575     return lowerSTACKRESTORE(Op, DAG);
02576   case ISD::PREFETCH:
02577     return lowerPREFETCH(Op, DAG);
02578   default:
02579     llvm_unreachable("Unexpected node to lower");
02580   }
02581 }
02582 
02583 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
02584 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
02585   switch (Opcode) {
02586     OPCODE(RET_FLAG);
02587     OPCODE(CALL);
02588     OPCODE(SIBCALL);
02589     OPCODE(PCREL_WRAPPER);
02590     OPCODE(PCREL_OFFSET);
02591     OPCODE(IABS);
02592     OPCODE(ICMP);
02593     OPCODE(FCMP);
02594     OPCODE(TM);
02595     OPCODE(BR_CCMASK);
02596     OPCODE(SELECT_CCMASK);
02597     OPCODE(ADJDYNALLOC);
02598     OPCODE(EXTRACT_ACCESS);
02599     OPCODE(UMUL_LOHI64);
02600     OPCODE(SDIVREM64);
02601     OPCODE(UDIVREM32);
02602     OPCODE(UDIVREM64);
02603     OPCODE(MVC);
02604     OPCODE(MVC_LOOP);
02605     OPCODE(NC);
02606     OPCODE(NC_LOOP);
02607     OPCODE(OC);
02608     OPCODE(OC_LOOP);
02609     OPCODE(XC);
02610     OPCODE(XC_LOOP);
02611     OPCODE(CLC);
02612     OPCODE(CLC_LOOP);
02613     OPCODE(STRCMP);
02614     OPCODE(STPCPY);
02615     OPCODE(SEARCH_STRING);
02616     OPCODE(IPM);
02617     OPCODE(SERIALIZE);
02618     OPCODE(ATOMIC_SWAPW);
02619     OPCODE(ATOMIC_LOADW_ADD);
02620     OPCODE(ATOMIC_LOADW_SUB);
02621     OPCODE(ATOMIC_LOADW_AND);
02622     OPCODE(ATOMIC_LOADW_OR);
02623     OPCODE(ATOMIC_LOADW_XOR);
02624     OPCODE(ATOMIC_LOADW_NAND);
02625     OPCODE(ATOMIC_LOADW_MIN);
02626     OPCODE(ATOMIC_LOADW_MAX);
02627     OPCODE(ATOMIC_LOADW_UMIN);
02628     OPCODE(ATOMIC_LOADW_UMAX);
02629     OPCODE(ATOMIC_CMP_SWAPW);
02630     OPCODE(PREFETCH);
02631   }
02632   return nullptr;
02633 #undef OPCODE
02634 }
02635 
02636 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
02637                                                  DAGCombinerInfo &DCI) const {
02638   SelectionDAG &DAG = DCI.DAG;
02639   unsigned Opcode = N->getOpcode();
02640   if (Opcode == ISD::SIGN_EXTEND) {
02641     // Convert (sext (ashr (shl X, C1), C2)) to
02642     // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
02643     // cheap as narrower ones.
02644     SDValue N0 = N->getOperand(0);
02645     EVT VT = N->getValueType(0);
02646     if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
02647       auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
02648       SDValue Inner = N0.getOperand(0);
02649       if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
02650         if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
02651           unsigned Extra = (VT.getSizeInBits() -
02652                             N0.getValueType().getSizeInBits());
02653           unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
02654           unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
02655           EVT ShiftVT = N0.getOperand(1).getValueType();
02656           SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
02657                                     Inner.getOperand(0));
02658           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
02659                                     DAG.getConstant(NewShlAmt, ShiftVT));
02660           return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
02661                              DAG.getConstant(NewSraAmt, ShiftVT));
02662         }
02663       }
02664     }
02665   }
02666   return SDValue();
02667 }
02668 
02669 //===----------------------------------------------------------------------===//
02670 // Custom insertion
02671 //===----------------------------------------------------------------------===//
02672 
02673 // Create a new basic block after MBB.
02674 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
02675   MachineFunction &MF = *MBB->getParent();
02676   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
02677   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
02678   return NewMBB;
02679 }
02680 
02681 // Split MBB after MI and return the new block (the one that contains
02682 // instructions after MI).
02683 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
02684                                           MachineBasicBlock *MBB) {
02685   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
02686   NewMBB->splice(NewMBB->begin(), MBB,
02687                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
02688   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
02689   return NewMBB;
02690 }
02691 
02692 // Split MBB before MI and return the new block (the one that contains MI).
02693 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
02694                                            MachineBasicBlock *MBB) {
02695   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
02696   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
02697   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
02698   return NewMBB;
02699 }
02700 
02701 // Force base value Base into a register before MI.  Return the register.
02702 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
02703                          const SystemZInstrInfo *TII) {
02704   if (Base.isReg())
02705     return Base.getReg();
02706 
02707   MachineBasicBlock *MBB = MI->getParent();
02708   MachineFunction &MF = *MBB->getParent();
02709   MachineRegisterInfo &MRI = MF.getRegInfo();
02710 
02711   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
02712   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
02713     .addOperand(Base).addImm(0).addReg(0);
02714   return Reg;
02715 }
02716 
02717 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
02718 MachineBasicBlock *
02719 SystemZTargetLowering::emitSelect(MachineInstr *MI,
02720                                   MachineBasicBlock *MBB) const {
02721   const SystemZInstrInfo *TII =
02722       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
02723 
02724   unsigned DestReg  = MI->getOperand(0).getReg();
02725   unsigned TrueReg  = MI->getOperand(1).getReg();
02726   unsigned FalseReg = MI->getOperand(2).getReg();
02727   unsigned CCValid  = MI->getOperand(3).getImm();
02728   unsigned CCMask   = MI->getOperand(4).getImm();
02729   DebugLoc DL       = MI->getDebugLoc();
02730 
02731   MachineBasicBlock *StartMBB = MBB;
02732   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
02733   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
02734 
02735   //  StartMBB:
02736   //   BRC CCMask, JoinMBB
02737   //   # fallthrough to FalseMBB
02738   MBB = StartMBB;
02739   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02740     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
02741   MBB->addSuccessor(JoinMBB);
02742   MBB->addSuccessor(FalseMBB);
02743 
02744   //  FalseMBB:
02745   //   # fallthrough to JoinMBB
02746   MBB = FalseMBB;
02747   MBB->addSuccessor(JoinMBB);
02748 
02749   //  JoinMBB:
02750   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
02751   //  ...
02752   MBB = JoinMBB;
02753   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
02754     .addReg(TrueReg).addMBB(StartMBB)
02755     .addReg(FalseReg).addMBB(FalseMBB);
02756 
02757   MI->eraseFromParent();
02758   return JoinMBB;
02759 }
02760 
02761 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
02762 // StoreOpcode is the store to use and Invert says whether the store should
02763 // happen when the condition is false rather than true.  If a STORE ON
02764 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
02765 MachineBasicBlock *
02766 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
02767                                      MachineBasicBlock *MBB,
02768                                      unsigned StoreOpcode, unsigned STOCOpcode,
02769                                      bool Invert) const {
02770   const SystemZInstrInfo *TII =
02771       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
02772 
02773   unsigned SrcReg     = MI->getOperand(0).getReg();
02774   MachineOperand Base = MI->getOperand(1);
02775   int64_t Disp        = MI->getOperand(2).getImm();
02776   unsigned IndexReg   = MI->getOperand(3).getReg();
02777   unsigned CCValid    = MI->getOperand(4).getImm();
02778   unsigned CCMask     = MI->getOperand(5).getImm();
02779   DebugLoc DL         = MI->getDebugLoc();
02780 
02781   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
02782 
02783   // Use STOCOpcode if possible.  We could use different store patterns in
02784   // order to avoid matching the index register, but the performance trade-offs
02785   // might be more complicated in that case.
02786   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
02787     if (Invert)
02788       CCMask ^= CCValid;
02789     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
02790       .addReg(SrcReg).addOperand(Base).addImm(Disp)
02791       .addImm(CCValid).addImm(CCMask);
02792     MI->eraseFromParent();
02793     return MBB;
02794   }
02795 
02796   // Get the condition needed to branch around the store.
02797   if (!Invert)
02798     CCMask ^= CCValid;
02799 
02800   MachineBasicBlock *StartMBB = MBB;
02801   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
02802   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
02803 
02804   //  StartMBB:
02805   //   BRC CCMask, JoinMBB
02806   //   # fallthrough to FalseMBB
02807   MBB = StartMBB;
02808   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02809     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
02810   MBB->addSuccessor(JoinMBB);
02811   MBB->addSuccessor(FalseMBB);
02812 
02813   //  FalseMBB:
02814   //   store %SrcReg, %Disp(%Index,%Base)
02815   //   # fallthrough to JoinMBB
02816   MBB = FalseMBB;
02817   BuildMI(MBB, DL, TII->get(StoreOpcode))
02818     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
02819   MBB->addSuccessor(JoinMBB);
02820 
02821   MI->eraseFromParent();
02822   return JoinMBB;
02823 }
02824 
02825 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
02826 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
02827 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
02828 // BitSize is the width of the field in bits, or 0 if this is a partword
02829 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
02830 // is one of the operands.  Invert says whether the field should be
02831 // inverted after performing BinOpcode (e.g. for NAND).
02832 MachineBasicBlock *
02833 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
02834                                             MachineBasicBlock *MBB,
02835                                             unsigned BinOpcode,
02836                                             unsigned BitSize,
02837                                             bool Invert) const {
02838   MachineFunction &MF = *MBB->getParent();
02839   const SystemZInstrInfo *TII =
02840       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
02841   MachineRegisterInfo &MRI = MF.getRegInfo();
02842   bool IsSubWord = (BitSize < 32);
02843 
02844   // Extract the operands.  Base can be a register or a frame index.
02845   // Src2 can be a register or immediate.
02846   unsigned Dest        = MI->getOperand(0).getReg();
02847   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
02848   int64_t Disp         = MI->getOperand(2).getImm();
02849   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
02850   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
02851   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
02852   DebugLoc DL          = MI->getDebugLoc();
02853   if (IsSubWord)
02854     BitSize = MI->getOperand(6).getImm();
02855 
02856   // Subword operations use 32-bit registers.
02857   const TargetRegisterClass *RC = (BitSize <= 32 ?
02858                                    &SystemZ::GR32BitRegClass :
02859                                    &SystemZ::GR64BitRegClass);
02860   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
02861   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
02862 
02863   // Get the right opcodes for the displacement.
02864   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
02865   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
02866   assert(LOpcode && CSOpcode && "Displacement out of range");
02867 
02868   // Create virtual registers for temporary results.
02869   unsigned OrigVal       = MRI.createVirtualRegister(RC);
02870   unsigned OldVal        = MRI.createVirtualRegister(RC);
02871   unsigned NewVal        = (BinOpcode || IsSubWord ?
02872                             MRI.createVirtualRegister(RC) : Src2.getReg());
02873   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
02874   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
02875 
02876   // Insert a basic block for the main loop.
02877   MachineBasicBlock *StartMBB = MBB;
02878   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
02879   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
02880 
02881   //  StartMBB:
02882   //   ...
02883   //   %OrigVal = L Disp(%Base)
02884   //   # fall through to LoopMMB
02885   MBB = StartMBB;
02886   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
02887     .addOperand(Base).addImm(Disp).addReg(0);
02888   MBB->addSuccessor(LoopMBB);
02889 
02890   //  LoopMBB:
02891   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
02892   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
02893   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
02894   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
02895   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
02896   //   JNE LoopMBB
02897   //   # fall through to DoneMMB
02898   MBB = LoopMBB;
02899   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
02900     .addReg(OrigVal).addMBB(StartMBB)
02901     .addReg(Dest).addMBB(LoopMBB);
02902   if (IsSubWord)
02903     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
02904       .addReg(OldVal).addReg(BitShift).addImm(0);
02905   if (Invert) {
02906     // Perform the operation normally and then invert every bit of the field.
02907     unsigned Tmp = MRI.createVirtualRegister(RC);
02908     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
02909       .addReg(RotatedOldVal).addOperand(Src2);
02910     if (BitSize <= 32)
02911       // XILF with the upper BitSize bits set.
02912       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
02913         .addReg(Tmp).addImm(-1U << (32 - BitSize));
02914     else {
02915       // Use LCGR and add -1 to the result, which is more compact than
02916       // an XILF, XILH pair.
02917       unsigned Tmp2 = MRI.createVirtualRegister(RC);
02918       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
02919       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
02920         .addReg(Tmp2).addImm(-1);
02921     }
02922   } else if (BinOpcode)
02923     // A simply binary operation.
02924     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
02925       .addReg(RotatedOldVal).addOperand(Src2);
02926   else if (IsSubWord)
02927     // Use RISBG to rotate Src2 into position and use it to replace the
02928     // field in RotatedOldVal.
02929     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
02930       .addReg(RotatedOldVal).addReg(Src2.getReg())
02931       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
02932   if (IsSubWord)
02933     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
02934       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
02935   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
02936     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
02937   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02938     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
02939   MBB->addSuccessor(LoopMBB);
02940   MBB->addSuccessor(DoneMBB);
02941 
02942   MI->eraseFromParent();
02943   return DoneMBB;
02944 }
02945 
02946 // Implement EmitInstrWithCustomInserter for pseudo
02947 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
02948 // instruction that should be used to compare the current field with the
02949 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
02950 // for when the current field should be kept.  BitSize is the width of
02951 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
02952 MachineBasicBlock *
02953 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
02954                                             MachineBasicBlock *MBB,
02955                                             unsigned CompareOpcode,
02956                                             unsigned KeepOldMask,
02957                                             unsigned BitSize) const {
02958   MachineFunction &MF = *MBB->getParent();
02959   const SystemZInstrInfo *TII =
02960       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
02961   MachineRegisterInfo &MRI = MF.getRegInfo();
02962   bool IsSubWord = (BitSize < 32);
02963 
02964   // Extract the operands.  Base can be a register or a frame index.
02965   unsigned Dest        = MI->getOperand(0).getReg();
02966   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
02967   int64_t  Disp        = MI->getOperand(2).getImm();
02968   unsigned Src2        = MI->getOperand(3).getReg();
02969   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
02970   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
02971   DebugLoc DL          = MI->getDebugLoc();
02972   if (IsSubWord)
02973     BitSize = MI->getOperand(6).getImm();
02974 
02975   // Subword operations use 32-bit registers.
02976   const TargetRegisterClass *RC = (BitSize <= 32 ?
02977                                    &SystemZ::GR32BitRegClass :
02978                                    &SystemZ::GR64BitRegClass);
02979   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
02980   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
02981 
02982   // Get the right opcodes for the displacement.
02983   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
02984   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
02985   assert(LOpcode && CSOpcode && "Displacement out of range");
02986 
02987   // Create virtual registers for temporary results.
02988   unsigned OrigVal       = MRI.createVirtualRegister(RC);
02989   unsigned OldVal        = MRI.createVirtualRegister(RC);
02990   unsigned NewVal        = MRI.createVirtualRegister(RC);
02991   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
02992   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
02993   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
02994 
02995   // Insert 3 basic blocks for the loop.
02996   MachineBasicBlock *StartMBB  = MBB;
02997   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
02998   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
02999   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
03000   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
03001 
03002   //  StartMBB:
03003   //   ...
03004   //   %OrigVal     = L Disp(%Base)
03005   //   # fall through to LoopMMB
03006   MBB = StartMBB;
03007   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
03008     .addOperand(Base).addImm(Disp).addReg(0);
03009   MBB->addSuccessor(LoopMBB);
03010 
03011   //  LoopMBB:
03012   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
03013   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
03014   //   CompareOpcode %RotatedOldVal, %Src2
03015   //   BRC KeepOldMask, UpdateMBB
03016   MBB = LoopMBB;
03017   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
03018     .addReg(OrigVal).addMBB(StartMBB)
03019     .addReg(Dest).addMBB(UpdateMBB);
03020   if (IsSubWord)
03021     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
03022       .addReg(OldVal).addReg(BitShift).addImm(0);
03023   BuildMI(MBB, DL, TII->get(CompareOpcode))
03024     .addReg(RotatedOldVal).addReg(Src2);
03025   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03026     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
03027   MBB->addSuccessor(UpdateMBB);
03028   MBB->addSuccessor(UseAltMBB);
03029 
03030   //  UseAltMBB:
03031   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
03032   //   # fall through to UpdateMMB
03033   MBB = UseAltMBB;
03034   if (IsSubWord)
03035     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
03036       .addReg(RotatedOldVal).addReg(Src2)
03037       .addImm(32).addImm(31 + BitSize).addImm(0);
03038   MBB->addSuccessor(UpdateMBB);
03039 
03040   //  UpdateMBB:
03041   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
03042   //                        [ %RotatedAltVal, UseAltMBB ]
03043   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
03044   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
03045   //   JNE LoopMBB
03046   //   # fall through to DoneMMB
03047   MBB = UpdateMBB;
03048   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
03049     .addReg(RotatedOldVal).addMBB(LoopMBB)
03050     .addReg(RotatedAltVal).addMBB(UseAltMBB);
03051   if (IsSubWord)
03052     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
03053       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
03054   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
03055     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
03056   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03057     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
03058   MBB->addSuccessor(LoopMBB);
03059   MBB->addSuccessor(DoneMBB);
03060 
03061   MI->eraseFromParent();
03062   return DoneMBB;
03063 }
03064 
03065 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
03066 // instruction MI.
03067 MachineBasicBlock *
03068 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
03069                                           MachineBasicBlock *MBB) const {
03070   MachineFunction &MF = *MBB->getParent();
03071   const SystemZInstrInfo *TII =
03072       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
03073   MachineRegisterInfo &MRI = MF.getRegInfo();
03074 
03075   // Extract the operands.  Base can be a register or a frame index.
03076   unsigned Dest        = MI->getOperand(0).getReg();
03077   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
03078   int64_t  Disp        = MI->getOperand(2).getImm();
03079   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
03080   unsigned OrigSwapVal = MI->getOperand(4).getReg();
03081   unsigned BitShift    = MI->getOperand(5).getReg();
03082   unsigned NegBitShift = MI->getOperand(6).getReg();
03083   int64_t  BitSize     = MI->getOperand(7).getImm();
03084   DebugLoc DL          = MI->getDebugLoc();
03085 
03086   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
03087 
03088   // Get the right opcodes for the displacement.
03089   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
03090   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
03091   assert(LOpcode && CSOpcode && "Displacement out of range");
03092 
03093   // Create virtual registers for temporary results.
03094   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
03095   unsigned OldVal       = MRI.createVirtualRegister(RC);
03096   unsigned CmpVal       = MRI.createVirtualRegister(RC);
03097   unsigned SwapVal      = MRI.createVirtualRegister(RC);
03098   unsigned StoreVal     = MRI.createVirtualRegister(RC);
03099   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
03100   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
03101   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
03102 
03103   // Insert 2 basic blocks for the loop.
03104   MachineBasicBlock *StartMBB = MBB;
03105   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
03106   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
03107   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
03108 
03109   //  StartMBB:
03110   //   ...
03111   //   %OrigOldVal     = L Disp(%Base)
03112   //   # fall through to LoopMMB
03113   MBB = StartMBB;
03114   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
03115     .addOperand(Base).addImm(Disp).addReg(0);
03116   MBB->addSuccessor(LoopMBB);
03117 
03118   //  LoopMBB:
03119   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
03120   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
03121   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
03122   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
03123   //                      ^^ The low BitSize bits contain the field
03124   //                         of interest.
03125   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
03126   //                      ^^ Replace the upper 32-BitSize bits of the
03127   //                         comparison value with those that we loaded,
03128   //                         so that we can use a full word comparison.
03129   //   CR %Dest, %RetryCmpVal
03130   //   JNE DoneMBB
03131   //   # Fall through to SetMBB
03132   MBB = LoopMBB;
03133   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
03134     .addReg(OrigOldVal).addMBB(StartMBB)
03135     .addReg(RetryOldVal).addMBB(SetMBB);
03136   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
03137     .addReg(OrigCmpVal).addMBB(StartMBB)
03138     .addReg(RetryCmpVal).addMBB(SetMBB);
03139   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
03140     .addReg(OrigSwapVal).addMBB(StartMBB)
03141     .addReg(RetrySwapVal).addMBB(SetMBB);
03142   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
03143     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
03144   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
03145     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
03146   BuildMI(MBB, DL, TII->get(SystemZ::CR))
03147     .addReg(Dest).addReg(RetryCmpVal);
03148   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03149     .addImm(SystemZ::CCMASK_ICMP)
03150     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
03151   MBB->addSuccessor(DoneMBB);
03152   MBB->addSuccessor(SetMBB);
03153 
03154   //  SetMBB:
03155   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
03156   //                      ^^ Replace the upper 32-BitSize bits of the new
03157   //                         value with those that we loaded.
03158   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
03159   //                      ^^ Rotate the new field to its proper position.
03160   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
03161   //   JNE LoopMBB
03162   //   # fall through to ExitMMB
03163   MBB = SetMBB;
03164   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
03165     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
03166   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
03167     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
03168   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
03169     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
03170   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03171     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
03172   MBB->addSuccessor(LoopMBB);
03173   MBB->addSuccessor(DoneMBB);
03174 
03175   MI->eraseFromParent();
03176   return DoneMBB;
03177 }
03178 
03179 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
03180 // if the high register of the GR128 value must be cleared or false if
03181 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
03182 // and subreg_l64 when extending a GR64.
03183 MachineBasicBlock *
03184 SystemZTargetLowering::emitExt128(MachineInstr *MI,
03185                                   MachineBasicBlock *MBB,
03186                                   bool ClearEven, unsigned SubReg) const {
03187   MachineFunction &MF = *MBB->getParent();
03188   const SystemZInstrInfo *TII =
03189       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
03190   MachineRegisterInfo &MRI = MF.getRegInfo();
03191   DebugLoc DL = MI->getDebugLoc();
03192 
03193   unsigned Dest  = MI->getOperand(0).getReg();
03194   unsigned Src   = MI->getOperand(1).getReg();
03195   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
03196 
03197   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
03198   if (ClearEven) {
03199     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
03200     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
03201 
03202     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
03203       .addImm(0);
03204     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
03205       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
03206     In128 = NewIn128;
03207   }
03208   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
03209     .addReg(In128).addReg(Src).addImm(SubReg);
03210 
03211   MI->eraseFromParent();
03212   return MBB;
03213 }
03214 
03215 MachineBasicBlock *
03216 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
03217                                          MachineBasicBlock *MBB,
03218                                          unsigned Opcode) const {
03219   MachineFunction &MF = *MBB->getParent();
03220   const SystemZInstrInfo *TII =
03221       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
03222   MachineRegisterInfo &MRI = MF.getRegInfo();
03223   DebugLoc DL = MI->getDebugLoc();
03224 
03225   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
03226   uint64_t       DestDisp = MI->getOperand(1).getImm();
03227   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
03228   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
03229   uint64_t       Length   = MI->getOperand(4).getImm();
03230 
03231   // When generating more than one CLC, all but the last will need to
03232   // branch to the end when a difference is found.
03233   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
03234                                splitBlockAfter(MI, MBB) : nullptr);
03235 
03236   // Check for the loop form, in which operand 5 is the trip count.
03237   if (MI->getNumExplicitOperands() > 5) {
03238     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
03239 
03240     uint64_t StartCountReg = MI->getOperand(5).getReg();
03241     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
03242     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
03243                               forceReg(MI, DestBase, TII));
03244 
03245     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
03246     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
03247     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
03248                             MRI.createVirtualRegister(RC));
03249     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
03250     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
03251                             MRI.createVirtualRegister(RC));
03252 
03253     RC = &SystemZ::GR64BitRegClass;
03254     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
03255     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
03256 
03257     MachineBasicBlock *StartMBB = MBB;
03258     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
03259     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
03260     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
03261 
03262     //  StartMBB:
03263     //   # fall through to LoopMMB
03264     MBB->addSuccessor(LoopMBB);
03265 
03266     //  LoopMBB:
03267     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
03268     //                      [ %NextDestReg, NextMBB ]
03269     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
03270     //                     [ %NextSrcReg, NextMBB ]
03271     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
03272     //                       [ %NextCountReg, NextMBB ]
03273     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
03274     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
03275     //   ( JLH EndMBB )
03276     //
03277     // The prefetch is used only for MVC.  The JLH is used only for CLC.
03278     MBB = LoopMBB;
03279 
03280     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
03281       .addReg(StartDestReg).addMBB(StartMBB)
03282       .addReg(NextDestReg).addMBB(NextMBB);
03283     if (!HaveSingleBase)
03284       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
03285         .addReg(StartSrcReg).addMBB(StartMBB)
03286         .addReg(NextSrcReg).addMBB(NextMBB);
03287     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
03288       .addReg(StartCountReg).addMBB(StartMBB)
03289       .addReg(NextCountReg).addMBB(NextMBB);
03290     if (Opcode == SystemZ::MVC)
03291       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
03292         .addImm(SystemZ::PFD_WRITE)
03293         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
03294     BuildMI(MBB, DL, TII->get(Opcode))
03295       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
03296       .addReg(ThisSrcReg).addImm(SrcDisp);
03297     if (EndMBB) {
03298       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03299         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
03300         .addMBB(EndMBB);
03301       MBB->addSuccessor(EndMBB);
03302       MBB->addSuccessor(NextMBB);
03303     }
03304 
03305     // NextMBB:
03306     //   %NextDestReg = LA 256(%ThisDestReg)
03307     //   %NextSrcReg = LA 256(%ThisSrcReg)
03308     //   %NextCountReg = AGHI %ThisCountReg, -1
03309     //   CGHI %NextCountReg, 0
03310     //   JLH LoopMBB
03311     //   # fall through to DoneMMB
03312     //
03313     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
03314     MBB = NextMBB;
03315 
03316     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
03317       .addReg(ThisDestReg).addImm(256).addReg(0);
03318     if (!HaveSingleBase)
03319       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
03320         .addReg(ThisSrcReg).addImm(256).addReg(0);
03321     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
03322       .addReg(ThisCountReg).addImm(-1);
03323     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
03324       .addReg(NextCountReg).addImm(0);
03325     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03326       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
03327       .addMBB(LoopMBB);
03328     MBB->addSuccessor(LoopMBB);
03329     MBB->addSuccessor(DoneMBB);
03330 
03331     DestBase = MachineOperand::CreateReg(NextDestReg, false);
03332     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
03333     Length &= 255;
03334     MBB = DoneMBB;
03335   }
03336   // Handle any remaining bytes with straight-line code.
03337   while (Length > 0) {
03338     uint64_t ThisLength = std::min(Length, uint64_t(256));
03339     // The previous iteration might have created out-of-range displacements.
03340     // Apply them using LAY if so.
03341     if (!isUInt<12>(DestDisp)) {
03342       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
03343       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
03344         .addOperand(DestBase).addImm(DestDisp).addReg(0);
03345       DestBase = MachineOperand::CreateReg(Reg, false);
03346       DestDisp = 0;
03347     }
03348     if (!isUInt<12>(SrcDisp)) {
03349       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
03350       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
03351         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
03352       SrcBase = MachineOperand::CreateReg(Reg, false);
03353       SrcDisp = 0;
03354     }
03355     BuildMI(*MBB, MI, DL, TII->get(Opcode))
03356       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
03357       .addOperand(SrcBase).addImm(SrcDisp);
03358     DestDisp += ThisLength;
03359     SrcDisp += ThisLength;
03360     Length -= ThisLength;
03361     // If there's another CLC to go, branch to the end if a difference
03362     // was found.
03363     if (EndMBB && Length > 0) {
03364       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
03365       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03366         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
03367         .addMBB(EndMBB);
03368       MBB->addSuccessor(EndMBB);
03369       MBB->addSuccessor(NextMBB);
03370       MBB = NextMBB;
03371     }
03372   }
03373   if (EndMBB) {
03374     MBB->addSuccessor(EndMBB);
03375     MBB = EndMBB;
03376     MBB->addLiveIn(SystemZ::CC);
03377   }
03378 
03379   MI->eraseFromParent();
03380   return MBB;
03381 }
03382 
03383 // Decompose string pseudo-instruction MI into a loop that continually performs
03384 // Opcode until CC != 3.
03385 MachineBasicBlock *
03386 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
03387                                          MachineBasicBlock *MBB,
03388                                          unsigned Opcode) const {
03389   MachineFunction &MF = *MBB->getParent();
03390   const SystemZInstrInfo *TII =
03391       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
03392   MachineRegisterInfo &MRI = MF.getRegInfo();
03393   DebugLoc DL = MI->getDebugLoc();
03394 
03395   uint64_t End1Reg   = MI->getOperand(0).getReg();
03396   uint64_t Start1Reg = MI->getOperand(1).getReg();
03397   uint64_t Start2Reg = MI->getOperand(2).getReg();
03398   uint64_t CharReg   = MI->getOperand(3).getReg();
03399 
03400   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
03401   uint64_t This1Reg = MRI.createVirtualRegister(RC);
03402   uint64_t This2Reg = MRI.createVirtualRegister(RC);
03403   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
03404 
03405   MachineBasicBlock *StartMBB = MBB;
03406   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
03407   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
03408 
03409   //  StartMBB:
03410   //   # fall through to LoopMMB
03411   MBB->addSuccessor(LoopMBB);
03412 
03413   //  LoopMBB:
03414   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
03415   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
03416   //   R0L = %CharReg
03417   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
03418   //   JO LoopMBB
03419   //   # fall through to DoneMMB
03420   //
03421   // The load of R0L can be hoisted by post-RA LICM.
03422   MBB = LoopMBB;
03423 
03424   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
03425     .addReg(Start1Reg).addMBB(StartMBB)
03426     .addReg(End1Reg).addMBB(LoopMBB);
03427   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
03428     .addReg(Start2Reg).addMBB(StartMBB)
03429     .addReg(End2Reg).addMBB(LoopMBB);
03430   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
03431   BuildMI(MBB, DL, TII->get(Opcode))
03432     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
03433     .addReg(This1Reg).addReg(This2Reg);
03434   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03435     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
03436   MBB->addSuccessor(LoopMBB);
03437   MBB->addSuccessor(DoneMBB);
03438 
03439   DoneMBB->addLiveIn(SystemZ::CC);
03440 
03441   MI->eraseFromParent();
03442   return DoneMBB;
03443 }
03444 
03445 MachineBasicBlock *SystemZTargetLowering::
03446 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
03447   switch (MI->getOpcode()) {
03448   case SystemZ::Select32Mux:
03449   case SystemZ::Select32:
03450   case SystemZ::SelectF32:
03451   case SystemZ::Select64:
03452   case SystemZ::SelectF64:
03453   case SystemZ::SelectF128:
03454     return emitSelect(MI, MBB);
03455 
03456   case SystemZ::CondStore8Mux:
03457     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
03458   case SystemZ::CondStore8MuxInv:
03459     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
03460   case SystemZ::CondStore16Mux:
03461     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
03462   case SystemZ::CondStore16MuxInv:
03463     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
03464   case SystemZ::CondStore8:
03465     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
03466   case SystemZ::CondStore8Inv:
03467     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
03468   case SystemZ::CondStore16:
03469     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
03470   case SystemZ::CondStore16Inv:
03471     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
03472   case SystemZ::CondStore32:
03473     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
03474   case SystemZ::CondStore32Inv:
03475     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
03476   case SystemZ::CondStore64:
03477     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
03478   case SystemZ::CondStore64Inv:
03479     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
03480   case SystemZ::CondStoreF32:
03481     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
03482   case SystemZ::CondStoreF32Inv:
03483     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
03484   case SystemZ::CondStoreF64:
03485     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
03486   case SystemZ::CondStoreF64Inv:
03487     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
03488 
03489   case SystemZ::AEXT128_64:
03490     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
03491   case SystemZ::ZEXT128_32:
03492     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
03493   case SystemZ::ZEXT128_64:
03494     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
03495 
03496   case SystemZ::ATOMIC_SWAPW:
03497     return emitAtomicLoadBinary(MI, MBB, 0, 0);
03498   case SystemZ::ATOMIC_SWAP_32:
03499     return emitAtomicLoadBinary(MI, MBB, 0, 32);
03500   case SystemZ::ATOMIC_SWAP_64:
03501     return emitAtomicLoadBinary(MI, MBB, 0, 64);
03502 
03503   case SystemZ::ATOMIC_LOADW_AR:
03504     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
03505   case SystemZ::ATOMIC_LOADW_AFI:
03506     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
03507   case SystemZ::ATOMIC_LOAD_AR:
03508     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
03509   case SystemZ::ATOMIC_LOAD_AHI:
03510     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
03511   case SystemZ::ATOMIC_LOAD_AFI:
03512     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
03513   case SystemZ::ATOMIC_LOAD_AGR:
03514     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
03515   case SystemZ::ATOMIC_LOAD_AGHI:
03516     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
03517   case SystemZ::ATOMIC_LOAD_AGFI:
03518     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
03519 
03520   case SystemZ::ATOMIC_LOADW_SR:
03521     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
03522   case SystemZ::ATOMIC_LOAD_SR:
03523     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
03524   case SystemZ::ATOMIC_LOAD_SGR:
03525     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
03526 
03527   case SystemZ::ATOMIC_LOADW_NR:
03528     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
03529   case SystemZ::ATOMIC_LOADW_NILH:
03530     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
03531   case SystemZ::ATOMIC_LOAD_NR:
03532     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
03533   case SystemZ::ATOMIC_LOAD_NILL:
03534     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
03535   case SystemZ::ATOMIC_LOAD_NILH:
03536     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
03537   case SystemZ::ATOMIC_LOAD_NILF:
03538     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
03539   case SystemZ::ATOMIC_LOAD_NGR:
03540     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
03541   case SystemZ::ATOMIC_LOAD_NILL64:
03542     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
03543   case SystemZ::ATOMIC_LOAD_NILH64:
03544     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
03545   case SystemZ::ATOMIC_LOAD_NIHL64:
03546     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
03547   case SystemZ::ATOMIC_LOAD_NIHH64:
03548     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
03549   case SystemZ::ATOMIC_LOAD_NILF64:
03550     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
03551   case SystemZ::ATOMIC_LOAD_NIHF64:
03552     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
03553 
03554   case SystemZ::ATOMIC_LOADW_OR:
03555     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
03556   case SystemZ::ATOMIC_LOADW_OILH:
03557     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
03558   case SystemZ::ATOMIC_LOAD_OR:
03559     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
03560   case SystemZ::ATOMIC_LOAD_OILL:
03561     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
03562   case SystemZ::ATOMIC_LOAD_OILH:
03563     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
03564   case SystemZ::ATOMIC_LOAD_OILF:
03565     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
03566   case SystemZ::ATOMIC_LOAD_OGR:
03567     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
03568   case SystemZ::ATOMIC_LOAD_OILL64:
03569     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
03570   case SystemZ::ATOMIC_LOAD_OILH64:
03571     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
03572   case SystemZ::ATOMIC_LOAD_OIHL64:
03573     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
03574   case SystemZ::ATOMIC_LOAD_OIHH64:
03575     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
03576   case SystemZ::ATOMIC_LOAD_OILF64:
03577     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
03578   case SystemZ::ATOMIC_LOAD_OIHF64:
03579     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
03580 
03581   case SystemZ::ATOMIC_LOADW_XR:
03582     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
03583   case SystemZ::ATOMIC_LOADW_XILF:
03584     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
03585   case SystemZ::ATOMIC_LOAD_XR:
03586     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
03587   case SystemZ::ATOMIC_LOAD_XILF:
03588     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
03589   case SystemZ::ATOMIC_LOAD_XGR:
03590     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
03591   case SystemZ::ATOMIC_LOAD_XILF64:
03592     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
03593   case SystemZ::ATOMIC_LOAD_XIHF64:
03594     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
03595 
03596   case SystemZ::ATOMIC_LOADW_NRi:
03597     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
03598   case SystemZ::ATOMIC_LOADW_NILHi:
03599     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
03600   case SystemZ::ATOMIC_LOAD_NRi:
03601     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
03602   case SystemZ::ATOMIC_LOAD_NILLi:
03603     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
03604   case SystemZ::ATOMIC_LOAD_NILHi:
03605     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
03606   case SystemZ::ATOMIC_LOAD_NILFi:
03607     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
03608   case SystemZ::ATOMIC_LOAD_NGRi:
03609     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
03610   case SystemZ::ATOMIC_LOAD_NILL64i:
03611     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
03612   case SystemZ::ATOMIC_LOAD_NILH64i:
03613     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
03614   case SystemZ::ATOMIC_LOAD_NIHL64i:
03615     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
03616   case SystemZ::ATOMIC_LOAD_NIHH64i:
03617     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
03618   case SystemZ::ATOMIC_LOAD_NILF64i:
03619     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
03620   case SystemZ::ATOMIC_LOAD_NIHF64i:
03621     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
03622 
03623   case SystemZ::ATOMIC_LOADW_MIN:
03624     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03625                                 SystemZ::CCMASK_CMP_LE, 0);
03626   case SystemZ::ATOMIC_LOAD_MIN_32:
03627     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03628                                 SystemZ::CCMASK_CMP_LE, 32);
03629   case SystemZ::ATOMIC_LOAD_MIN_64:
03630     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
03631                                 SystemZ::CCMASK_CMP_LE, 64);
03632 
03633   case SystemZ::ATOMIC_LOADW_MAX:
03634     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03635                                 SystemZ::CCMASK_CMP_GE, 0);
03636   case SystemZ::ATOMIC_LOAD_MAX_32:
03637     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03638                                 SystemZ::CCMASK_CMP_GE, 32);
03639   case SystemZ::ATOMIC_LOAD_MAX_64:
03640     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
03641                                 SystemZ::CCMASK_CMP_GE, 64);
03642 
03643   case SystemZ::ATOMIC_LOADW_UMIN:
03644     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03645                                 SystemZ::CCMASK_CMP_LE, 0);
03646   case SystemZ::ATOMIC_LOAD_UMIN_32:
03647     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03648                                 SystemZ::CCMASK_CMP_LE, 32);
03649   case SystemZ::ATOMIC_LOAD_UMIN_64:
03650     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
03651                                 SystemZ::CCMASK_CMP_LE, 64);
03652 
03653   case SystemZ::ATOMIC_LOADW_UMAX:
03654     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03655                                 SystemZ::CCMASK_CMP_GE, 0);
03656   case SystemZ::ATOMIC_LOAD_UMAX_32:
03657     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03658                                 SystemZ::CCMASK_CMP_GE, 32);
03659   case SystemZ::ATOMIC_LOAD_UMAX_64:
03660     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
03661                                 SystemZ::CCMASK_CMP_GE, 64);
03662 
03663   case SystemZ::ATOMIC_CMP_SWAPW:
03664     return emitAtomicCmpSwapW(MI, MBB);
03665   case SystemZ::MVCSequence:
03666   case SystemZ::MVCLoop:
03667     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
03668   case SystemZ::NCSequence:
03669   case SystemZ::NCLoop:
03670     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
03671   case SystemZ::OCSequence:
03672   case SystemZ::OCLoop:
03673     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
03674   case SystemZ::XCSequence:
03675   case SystemZ::XCLoop:
03676     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
03677   case SystemZ::CLCSequence:
03678   case SystemZ::CLCLoop:
03679     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
03680   case SystemZ::CLSTLoop:
03681     return emitStringWrapper(MI, MBB, SystemZ::CLST);
03682   case SystemZ::MVSTLoop:
03683     return emitStringWrapper(MI, MBB, SystemZ::MVST);
03684   case SystemZ::SRSTLoop:
03685     return emitStringWrapper(MI, MBB, SystemZ::SRST);
03686   default:
03687     llvm_unreachable("Unexpected instr type to insert");
03688   }
03689 }