LCOV - code coverage report
Current view: top level - lib/CodeGen/SelectionDAG - TargetLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1638 1748 93.7 %
Date: 2018-02-22 04:41:24 Functions: 58 60 96.7 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This implements the TargetLowering class.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/CodeGen/TargetLowering.h"
      15             : #include "llvm/ADT/BitVector.h"
      16             : #include "llvm/ADT/STLExtras.h"
      17             : #include "llvm/CodeGen/CallingConvLower.h"
      18             : #include "llvm/CodeGen/MachineFrameInfo.h"
      19             : #include "llvm/CodeGen/MachineFunction.h"
      20             : #include "llvm/CodeGen/MachineJumpTableInfo.h"
      21             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      22             : #include "llvm/CodeGen/SelectionDAG.h"
      23             : #include "llvm/CodeGen/TargetLoweringObjectFile.h"
      24             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      25             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      26             : #include "llvm/IR/DataLayout.h"
      27             : #include "llvm/IR/DerivedTypes.h"
      28             : #include "llvm/IR/GlobalVariable.h"
      29             : #include "llvm/IR/LLVMContext.h"
      30             : #include "llvm/MC/MCAsmInfo.h"
      31             : #include "llvm/MC/MCExpr.h"
      32             : #include "llvm/Support/ErrorHandling.h"
      33             : #include "llvm/Support/KnownBits.h"
      34             : #include "llvm/Support/MathExtras.h"
      35             : #include "llvm/Target/TargetMachine.h"
      36             : #include <cctype>
      37             : using namespace llvm;
      38             : 
      39             : /// NOTE: The TargetMachine owns TLOF.
      40       31095 : TargetLowering::TargetLowering(const TargetMachine &tm)
      41       31095 :   : TargetLoweringBase(tm) {}
      42             : 
      43           0 : const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
      44           0 :   return nullptr;
      45             : }
      46             : 
      47     1821131 : bool TargetLowering::isPositionIndependent() const {
      48     1821131 :   return getTargetMachine().isPositionIndependent();
      49             : }
      50             : 
      51             : /// Check whether a given call node is in tail position within its function. If
      52             : /// so, it sets Chain to the input chain of the tail call.
      53        2365 : bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
      54             :                                           SDValue &Chain) const {
      55        2365 :   const Function &F = DAG.getMachineFunction().getFunction();
      56             : 
      57             :   // Conservatively require the attributes of the call to match those of
      58             :   // the return. Ignore noalias because it doesn't affect the call sequence.
      59        2365 :   AttributeList CallerAttrs = F.getAttributes();
      60        4730 :   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
      61        2365 :           .removeAttribute(Attribute::NoAlias)
      62        2365 :           .hasAttributes())
      63             :     return false;
      64             : 
      65             :   // It's not safe to eliminate the sign / zero extension of the return value.
      66        4686 :   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
      67        2343 :       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
      68             :     return false;
      69             : 
      70             :   // Check if the only use is a function return node.
      71        2343 :   return isUsedByReturnOnly(Node, Chain);
      72             : }
      73             : 
      74        1778 : bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
      75             :     const uint32_t *CallerPreservedMask,
      76             :     const SmallVectorImpl<CCValAssign> &ArgLocs,
      77             :     const SmallVectorImpl<SDValue> &OutVals) const {
      78        5026 :   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
      79        3258 :     const CCValAssign &ArgLoc = ArgLocs[I];
      80        3258 :     if (!ArgLoc.isRegLoc())
      81         199 :       continue;
      82        3059 :     unsigned Reg = ArgLoc.getLocReg();
      83             :     // Only look at callee saved registers.
      84        3059 :     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
      85        3043 :       continue;
      86             :     // Check that we pass the value used for the caller.
      87             :     // (We look for a CopyFromReg reading a virtual register that is used
      88             :     //  for the function live-in value of register Reg)
      89          16 :     SDValue Value = OutVals[I];
      90          16 :     if (Value->getOpcode() != ISD::CopyFromReg)
      91             :       return false;
      92          32 :     unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
      93          16 :     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
      94             :       return false;
      95             :   }
      96             :   return true;
      97             : }
      98             : 
      99             : /// \brief Set CallLoweringInfo attribute flags based on a call instruction
     100             : /// and called function attributes.
     101      422182 : void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS,
     102             :                                                      unsigned ArgIdx) {
     103      422182 :   IsSExt = CS->paramHasAttr(ArgIdx, Attribute::SExt);
     104      422182 :   IsZExt = CS->paramHasAttr(ArgIdx, Attribute::ZExt);
     105      422182 :   IsInReg = CS->paramHasAttr(ArgIdx, Attribute::InReg);
     106      422182 :   IsSRet = CS->paramHasAttr(ArgIdx, Attribute::StructRet);
     107      422182 :   IsNest = CS->paramHasAttr(ArgIdx, Attribute::Nest);
     108      422182 :   IsByVal = CS->paramHasAttr(ArgIdx, Attribute::ByVal);
     109      422182 :   IsInAlloca = CS->paramHasAttr(ArgIdx, Attribute::InAlloca);
     110      422182 :   IsReturned = CS->paramHasAttr(ArgIdx, Attribute::Returned);
     111      422182 :   IsSwiftSelf = CS->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
     112      422182 :   IsSwiftError = CS->paramHasAttr(ArgIdx, Attribute::SwiftError);
     113      422182 :   Alignment  = CS->getParamAlignment(ArgIdx);
     114      422182 : }
     115             : 
     116             : /// Generate a libcall taking the given operands as arguments and returning a
     117             : /// result of type RetVT.
     118             : std::pair<SDValue, SDValue>
     119        2799 : TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
     120             :                             ArrayRef<SDValue> Ops, bool isSigned,
     121             :                             const SDLoc &dl, bool doesNotReturn,
     122             :                             bool isReturnValueUsed) const {
     123             :   TargetLowering::ArgListTy Args;
     124        2799 :   Args.reserve(Ops.size());
     125             : 
     126             :   TargetLowering::ArgListEntry Entry;
     127       10513 :   for (SDValue Op : Ops) {
     128        3857 :     Entry.Node = Op;
     129        3857 :     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
     130        7714 :     Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
     131        7714 :     Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
     132        3857 :     Args.push_back(Entry);
     133             :   }
     134             : 
     135        2799 :   if (LC == RTLIB::UNKNOWN_LIBCALL)
     136           0 :     report_fatal_error("Unsupported library call operation!");
     137             :   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
     138        5598 :                                          getPointerTy(DAG.getDataLayout()));
     139             : 
     140        2799 :   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
     141        5598 :   TargetLowering::CallLoweringInfo CLI(DAG);
     142        2799 :   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
     143             :   CLI.setDebugLoc(dl)
     144             :       .setChain(DAG.getEntryNode())
     145        2799 :       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
     146             :       .setNoReturn(doesNotReturn)
     147             :       .setDiscardResult(!isReturnValueUsed)
     148             :       .setSExtResult(signExtend)
     149        2799 :       .setZExtResult(!signExtend);
     150        5598 :   return LowerCallTo(CLI);
     151             : }
     152             : 
     153             : /// Soften the operands of a comparison. This code is shared among BR_CC,
     154             : /// SELECT_CC, and SETCC handlers.
     155         300 : void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
     156             :                                          SDValue &NewLHS, SDValue &NewRHS,
     157             :                                          ISD::CondCode &CCCode,
     158             :                                          const SDLoc &dl) const {
     159             :   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
     160             :          && "Unsupported setcc type!");
     161             : 
     162             :   // Expand into one or more soft-fp libcall(s).
     163             :   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
     164             :   bool ShouldInvertCC = false;
     165         300 :   switch (CCCode) {
     166             :   case ISD::SETEQ:
     167             :   case ISD::SETOEQ:
     168             :     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
     169             :           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
     170             :           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
     171          62 :     break;
     172             :   case ISD::SETNE:
     173             :   case ISD::SETUNE:
     174             :     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
     175             :           (VT == MVT::f64) ? RTLIB::UNE_F64 :
     176             :           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
     177          45 :     break;
     178             :   case ISD::SETGE:
     179             :   case ISD::SETOGE:
     180             :     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
     181             :           (VT == MVT::f64) ? RTLIB::OGE_F64 :
     182             :           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
     183          28 :     break;
     184             :   case ISD::SETLT:
     185             :   case ISD::SETOLT:
     186             :     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
     187             :           (VT == MVT::f64) ? RTLIB::OLT_F64 :
     188             :           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
     189          40 :     break;
     190             :   case ISD::SETLE:
     191             :   case ISD::SETOLE:
     192             :     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
     193             :           (VT == MVT::f64) ? RTLIB::OLE_F64 :
     194             :           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
     195          28 :     break;
     196             :   case ISD::SETGT:
     197             :   case ISD::SETOGT:
     198             :     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
     199             :           (VT == MVT::f64) ? RTLIB::OGT_F64 :
     200             :           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
     201          36 :     break;
     202             :   case ISD::SETUO:
     203             :     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
     204             :           (VT == MVT::f64) ? RTLIB::UO_F64 :
     205             :           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
     206          15 :     break;
     207             :   case ISD::SETO:
     208             :     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
     209             :           (VT == MVT::f64) ? RTLIB::O_F64 :
     210             :           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
     211           5 :     break;
     212             :   case ISD::SETONE:
     213             :     // SETONE = SETOLT | SETOGT
     214             :     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
     215             :           (VT == MVT::f64) ? RTLIB::OLT_F64 :
     216             :           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
     217             :     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
     218             :           (VT == MVT::f64) ? RTLIB::OGT_F64 :
     219             :           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
     220           5 :     break;
     221             :   case ISD::SETUEQ:
     222             :     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
     223             :           (VT == MVT::f64) ? RTLIB::UO_F64 :
     224             :           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
     225             :     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
     226             :           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
     227             :           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
     228           8 :     break;
     229          28 :   default:
     230             :     // Invert CC for unordered comparisons
     231             :     ShouldInvertCC = true;
     232          28 :     switch (CCCode) {
     233             :     case ISD::SETULT:
     234             :       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
     235             :             (VT == MVT::f64) ? RTLIB::OGE_F64 :
     236             :             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
     237           5 :       break;
     238             :     case ISD::SETULE:
     239             :       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
     240             :             (VT == MVT::f64) ? RTLIB::OGT_F64 :
     241             :             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
     242           8 :       break;
     243             :     case ISD::SETUGT:
     244             :       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
     245             :             (VT == MVT::f64) ? RTLIB::OLE_F64 :
     246             :             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
     247           8 :       break;
     248             :     case ISD::SETUGE:
     249             :       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
     250             :             (VT == MVT::f64) ? RTLIB::OLT_F64 :
     251             :             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
     252           7 :       break;
     253           0 :     default: llvm_unreachable("Do not know how to soften this setcc!");
     254             :     }
     255             :   }
     256             : 
     257             :   // Use the target specific return value for comparions lib calls.
     258         300 :   EVT RetVT = getCmpLibcallReturnType();
     259         300 :   SDValue Ops[2] = {NewLHS, NewRHS};
     260         300 :   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
     261         300 :                        dl).first;
     262         300 :   NewRHS = DAG.getConstant(0, dl, RetVT);
     263             : 
     264         300 :   CCCode = getCmpLibcallCC(LC1);
     265         300 :   if (ShouldInvertCC)
     266          28 :     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
     267             : 
     268         300 :   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
     269             :     SDValue Tmp = DAG.getNode(
     270             :         ISD::SETCC, dl,
     271          13 :         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
     272          39 :         NewLHS, NewRHS, DAG.getCondCode(CCCode));
     273          13 :     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
     274          13 :                          dl).first;
     275          13 :     NewLHS = DAG.getNode(
     276             :         ISD::SETCC, dl,
     277          13 :         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
     278          39 :         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
     279          26 :     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
     280          13 :     NewRHS = SDValue();
     281             :   }
     282         300 : }
     283             : 
     284             : /// Return the entry encoding for a jump table in the current function. The
     285             : /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
     286         151 : unsigned TargetLowering::getJumpTableEncoding() const {
     287             :   // In non-pic modes, just use the address of a block.
     288         151 :   if (!isPositionIndependent())
     289             :     return MachineJumpTableInfo::EK_BlockAddress;
     290             : 
     291             :   // In PIC mode, if the target supports a GPRel32 directive, use it.
     292          40 :   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
     293             :     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
     294             : 
     295             :   // Otherwise, use a label difference.
     296          34 :   return MachineJumpTableInfo::EK_LabelDifference32;
     297             : }
     298             : 
     299          14 : SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
     300             :                                                  SelectionDAG &DAG) const {
     301             :   // If our PIC model is GP relative, use the global offset table as the base.
     302          14 :   unsigned JTEncoding = getJumpTableEncoding();
     303             : 
     304          14 :   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
     305             :       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
     306          14 :     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
     307             : 
     308           7 :   return Table;
     309             : }
     310             : 
     311             : /// This returns the relocation base for the given PIC jumptable, the same as
     312             : /// getPICJumpTableRelocBase, but as an MCExpr.
     313             : const MCExpr *
     314         464 : TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
     315             :                                              unsigned JTI,MCContext &Ctx) const{
     316             :   // The normal PIC reloc base is the label at the start of the jump table.
     317         928 :   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
     318             : }
     319             : 
     320             : bool
     321      670129 : TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
     322      670129 :   const TargetMachine &TM = getTargetMachine();
     323      670129 :   const GlobalValue *GV = GA->getGlobal();
     324             : 
     325             :   // If the address is not even local to this DSO we will have to load it from
     326             :   // a got and then add the offset.
     327      670129 :   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
     328             :     return false;
     329             : 
     330             :   // If the code is position independent we will have to add a base register.
     331      666365 :   if (isPositionIndependent())
     332             :     return false;
     333             : 
     334             :   // Otherwise we can do it.
     335        6187 :   return true;
     336             : }
     337             : 
     338             : //===----------------------------------------------------------------------===//
     339             : //  Optimization Methods
     340             : //===----------------------------------------------------------------------===//
     341             : 
     342             : /// If the specified instruction has a constant integer operand and there are
     343             : /// bits set in that constant that are not demanded, then clear those bits and
     344             : /// return true.
     345      616163 : bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
     346             :                                             TargetLoweringOpt &TLO) const {
     347      616163 :   SelectionDAG &DAG = TLO.DAG;
     348             :   SDLoc DL(Op);
     349             :   unsigned Opcode = Op.getOpcode();
     350             : 
     351             :   // Do target-specific constant optimization.
     352      616163 :   if (targetShrinkDemandedConstant(Op, Demanded, TLO))
     353        4986 :     return TLO.New.getNode();
     354             : 
     355             :   // FIXME: ISD::SELECT, ISD::SELECT_CC
     356      611177 :   switch (Opcode) {
     357             :   default:
     358             :     break;
     359      554449 :   case ISD::XOR:
     360             :   case ISD::AND:
     361             :   case ISD::OR: {
     362             :     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
     363             :     if (!Op1C)
     364             :       return false;
     365             : 
     366             :     // If this is a 'not' op, don't touch it because that's a canonical form.
     367      399628 :     const APInt &C = Op1C->getAPIntValue();
     368      429067 :     if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
     369             :       return false;
     370             : 
     371      399628 :     if (!C.isSubsetOf(Demanded)) {
     372       10479 :       EVT VT = Op.getValueType();
     373       31437 :       SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
     374       10479 :       SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
     375             :       return TLO.CombineTo(Op, NewOp);
     376             :     }
     377             : 
     378             :     break;
     379             :   }
     380             :   }
     381             : 
     382             :   return false;
     383             : }
     384             : 
     385             : /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
     386             : /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
     387             : /// generalized for targets with other types of implicit widening casts.
     388     2383902 : bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
     389             :                                       const APInt &Demanded,
     390             :                                       TargetLoweringOpt &TLO) const {
     391             :   assert(Op.getNumOperands() == 2 &&
     392             :          "ShrinkDemandedOp only supports binary operators!");
     393             :   assert(Op.getNode()->getNumValues() == 1 &&
     394             :          "ShrinkDemandedOp only supports nodes with one result!");
     395             : 
     396     2383902 :   SelectionDAG &DAG = TLO.DAG;
     397             :   SDLoc dl(Op);
     398             : 
     399             :   // Early return, as this function cannot handle vector types.
     400     4767804 :   if (Op.getValueType().isVector())
     401             :     return false;
     402             : 
     403             :   // Don't do this if the node has another user, which may require the
     404             :   // full value.
     405             :   if (!Op.getNode()->hasOneUse())
     406             :     return false;
     407             : 
     408             :   // Search for the smallest integer type with free casts to and from
     409             :   // Op's type. For expedience, just check power-of-2 integer types.
     410     1570819 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     411             :   unsigned DemandedSize = Demanded.getActiveBits();
     412             :   unsigned SmallVTBits = DemandedSize;
     413             :   if (!isPowerOf2_32(SmallVTBits))
     414       86554 :     SmallVTBits = NextPowerOf2(SmallVTBits);
     415     1742752 :   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
     416       58544 :     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
     417      152147 :     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
     418       70118 :         TLI.isZExtFree(SmallVT, Op.getValueType())) {
     419             :       // We found a type with free casts.
     420             :       SDValue X = DAG.getNode(
     421             :           Op.getOpcode(), dl, SmallVT,
     422             :           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
     423        3699 :           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
     424             :       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
     425        1233 :       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
     426             :       return TLO.CombineTo(Op, Z);
     427             :     }
     428             :   }
     429             :   return false;
     430             : }
     431             : 
     432             : bool
     433        3059 : TargetLowering::SimplifyDemandedBits(SDNode *User, unsigned OpIdx,
     434             :                                      const APInt &Demanded,
     435             :                                      DAGCombinerInfo &DCI,
     436             :                                      TargetLoweringOpt &TLO) const {
     437        6118 :   SDValue Op = User->getOperand(OpIdx);
     438        3059 :   KnownBits Known;
     439             : 
     440        3059 :   if (!SimplifyDemandedBits(Op, Demanded, Known, TLO, 0, true))
     441             :     return false;
     442             : 
     443             : 
     444             :   // Old will not always be the same as Op.  For example:
     445             :   //
     446             :   // Demanded = 0xffffff
     447             :   // Op = i64 truncate (i32 and x, 0xffffff)
     448             :   // In this case simplify demand bits will want to replace the 'and' node
     449             :   // with the value 'x', which will give us:
     450             :   // Old = i32 and x, 0xffffff
     451             :   // New = x
     452         344 :   if (TLO.Old.hasOneUse()) {
     453             :     // For the one use case, we just commit the change.
     454         159 :     DCI.CommitTargetLoweringOpt(TLO);
     455         159 :     return true;
     456             :   }
     457             : 
     458             :   // If Old has more than one use then it must be Op, because the
     459             :   // AssumeSingleUse flag is not propogated to recursive calls of
     460             :   // SimplifyDemanded bits, so the only node with multiple use that
     461             :   // it will attempt to combine will be Op.
     462             :   assert(TLO.Old == Op);
     463             : 
     464             :   SmallVector <SDValue, 4> NewOps;
     465          78 :   for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
     466          39 :     if (i == OpIdx) {
     467          13 :       NewOps.push_back(TLO.New);
     468          13 :       continue;
     469             :     }
     470          26 :     NewOps.push_back(User->getOperand(i));
     471             :   }
     472          26 :   User = TLO.DAG.UpdateNodeOperands(User, NewOps);
     473             :   // Op has less users now, so we may be able to perform additional combines
     474             :   // with it.
     475          13 :   DCI.AddToWorklist(Op.getNode());
     476             :   // User's operands have been updated, so we may be able to do new combines
     477             :   // with it.
     478          13 :   DCI.AddToWorklist(User);
     479             :   return true;
     480             : }
     481             : 
     482         186 : bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
     483             :                                           DAGCombinerInfo &DCI) const {
     484             : 
     485         186 :   SelectionDAG &DAG = DCI.DAG;
     486         186 :   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
     487         372 :                         !DCI.isBeforeLegalizeOps());
     488         186 :   KnownBits Known;
     489             : 
     490         186 :   bool Simplified = SimplifyDemandedBits(Op, DemandedMask, Known, TLO);
     491         186 :   if (Simplified)
     492          38 :     DCI.CommitTargetLoweringOpt(TLO);
     493         186 :   return Simplified;
     494             : }
     495             : 
     496             : /// Look at Op. At this point, we know that only the DemandedMask bits of the
     497             : /// result of Op are ever used downstream. If we can use this information to
     498             : /// simplify Op, create a new simplified DAG node and return true, returning the
     499             : /// original and new nodes in Old and New. Otherwise, analyze the expression and
     500             : /// return a mask of Known bits for the expression (used to simplify the
     501             : /// caller).  The Known bits may only be accurate for those bits in the
     502             : /// DemandedMask.
     503     8709043 : bool TargetLowering::SimplifyDemandedBits(SDValue Op,
     504             :                                           const APInt &DemandedMask,
     505             :                                           KnownBits &Known,
     506             :                                           TargetLoweringOpt &TLO,
     507             :                                           unsigned Depth,
     508             :                                           bool AssumeSingleUse) const {
     509     8709043 :   unsigned BitWidth = DemandedMask.getBitWidth();
     510             :   assert(Op.getScalarValueSizeInBits() == BitWidth &&
     511             :          "Mask size mismatches value type size!");
     512             :   APInt NewMask = DemandedMask;
     513             :   SDLoc dl(Op);
     514     8709044 :   auto &DL = TLO.DAG.getDataLayout();
     515             : 
     516             :   // Don't know anything.
     517     8709043 :   Known = KnownBits(BitWidth);
     518             : 
     519    17418088 :   if (Op.getOpcode() == ISD::Constant) {
     520             :     // We know all of the bits for a constant!
     521     3365108 :     Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
     522     1682554 :     Known.Zero = ~Known.One;
     523     1682554 :     return false;
     524             :   }
     525             : 
     526             :   // Other users may use these bits.
     527    14052980 :   EVT VT = Op.getValueType();
     528     2741861 :   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
     529     2740744 :     if (Depth != 0) {
     530             :       // If not at the root, Just compute the Known bits to
     531             :       // simplify things downstream.
     532     2055556 :       TLO.DAG.computeKnownBits(Op, Known, Depth);
     533     2055556 :       return false;
     534             :     }
     535             :     // If this is the root being simplified, allow it to have multiple uses,
     536             :     // just set the NewMask to all bits.
     537     1370376 :     NewMask = APInt::getAllOnesValue(BitWidth);
     538     4285746 :   } else if (DemandedMask == 0) {
     539             :     // Not demanding any bits from Op.
     540        2529 :     if (!Op.isUndef())
     541        3052 :       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
     542             :     return false;
     543     4283217 :   } else if (Depth == 6) {        // Limit search depth.
     544             :     return false;
     545             :   }
     546             : 
     547     4929681 :   KnownBits Known2, KnownOut;
     548     9859362 :   switch (Op.getOpcode()) {
     549       42746 :   case ISD::BUILD_VECTOR:
     550             :     // Collect the known bits that are shared by every constant vector element.
     551       42746 :     Known.Zero.setAllBits(); Known.One.setAllBits();
     552      328036 :     for (SDValue SrcOp : Op->ops()) {
     553             :       if (!isa<ConstantSDNode>(SrcOp)) {
     554             :         // We can only handle all constant values - bail out with no known bits.
     555        2380 :         Known = KnownBits(BitWidth);
     556             :         return false;
     557             :       }
     558      242544 :       Known2.One = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
     559      121272 :       Known2.Zero = ~Known2.One;
     560             : 
     561             :       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
     562      121272 :       if (Known2.One.getBitWidth() != BitWidth) {
     563             :         assert(Known2.getBitWidth() > BitWidth &&
     564             :                "Expected BUILD_VECTOR implicit truncation");
     565       10132 :         Known2 = Known2.trunc(BitWidth);
     566             :       }
     567             : 
     568             :       // Known bits are the values that are shared by every element.
     569             :       // TODO: support per-element known bits.
     570             :       Known.One &= Known2.One;
     571             :       Known.Zero &= Known2.Zero;
     572             :     }
     573             :     return false;   // Don't fall through, will infinitely loop.
     574      282331 :   case ISD::AND:
     575             :     // If the RHS is a constant, check to see if the LHS would be zero without
     576             :     // using the bits from the RHS.  Below, we use knowledge about the RHS to
     577             :     // simplify the LHS, here we're using information from the LHS to simplify
     578             :     // the RHS.
     579      282331 :     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op.getOperand(1))) {
     580      450322 :       SDValue Op0 = Op.getOperand(0);
     581      160799 :       KnownBits LHSKnown;
     582             :       // Do not increment Depth here; that can cause an infinite loop.
     583      225161 :       TLO.DAG.computeKnownBits(Op0, LHSKnown, Depth);
     584             :       // If the LHS already has zeros where RHSC does, this 'and' is dead.
     585     1350966 :       if ((LHSKnown.Zero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
     586      118276 :         return TLO.CombineTo(Op, Op0);
     587             : 
     588             :       // If any of the set bits in the RHS are known zero on the LHS, shrink
     589             :       // the constant.
     590      684988 :       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & NewMask, TLO))
     591             :         return true;
     592             : 
     593             :       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
     594             :       // constant, but if this 'and' is only clearing bits that were just set by
     595             :       // the xor, then this 'and' can be eliminated by shrinking the mask of
     596             :       // the xor. For example, for a 32-bit X:
     597             :       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
     598      322050 :       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
     599      482656 :           LHSKnown.One == ~RHSC->getAPIntValue()) {
     600          17 :         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0),
     601          34 :                                       Op.getOperand(1));
     602             :         return TLO.CombineTo(Op, Xor);
     603             :       }
     604             :     }
     605             : 
     606      435938 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
     607             :       return true;
     608             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     609     1307478 :     if (SimplifyDemandedBits(Op.getOperand(0), ~Known.Zero & NewMask,
     610             :                              Known2, TLO, Depth+1))
     611             :       return true;
     612             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     613             : 
     614             :     // If all of the demanded bits are known one on one side, return the other.
     615             :     // These bits cannot contribute to the result of the 'and'.
     616      638247 :     if (NewMask.isSubsetOf(Known2.Zero | Known.One))
     617         324 :       return TLO.CombineTo(Op, Op.getOperand(0));
     618      425174 :     if (NewMask.isSubsetOf(Known.Zero | Known2.One))
     619        5612 :       return TLO.CombineTo(Op, Op.getOperand(1));
     620             :     // If all of the demanded bits in the inputs are known zeros, return zero.
     621      419562 :     if (NewMask.isSubsetOf(Known.Zero | Known2.Zero))
     622           8 :       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
     623             :     // If the RHS is a constant, see if we can simplify it.
     624      839108 :     if (ShrinkDemandedConstant(Op, ~Known2.Zero & NewMask, TLO))
     625             :       return true;
     626             :     // If the operation can be done in a smaller type, do so.
     627      209777 :     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
     628             :       return true;
     629             : 
     630             :     // Output known-1 bits are only known if set in both the LHS & RHS.
     631             :     Known.One &= Known2.One;
     632             :     // Output known-0 are known to be clear if zero in either the LHS | RHS.
     633             :     Known.Zero |= Known2.Zero;
     634             :     break;
     635      156322 :   case ISD::OR:
     636      312644 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
     637             :       return true;
     638             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     639      914004 :     if (SimplifyDemandedBits(Op.getOperand(0), ~Known.One & NewMask,
     640             :                              Known2, TLO, Depth+1))
     641             :       return true;
     642             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     643             : 
     644             :     // If all of the demanded bits are known zero on one side, return the other.
     645             :     // These bits cannot contribute to the result of the 'or'.
     646      448083 :     if (NewMask.isSubsetOf(Known2.One | Known.Zero))
     647         852 :       return TLO.CombineTo(Op, Op.getOperand(0));
     648      297870 :     if (NewMask.isSubsetOf(Known.One | Known2.Zero))
     649        2012 :       return TLO.CombineTo(Op, Op.getOperand(1));
     650             :     // If the RHS is a constant, see if we can simplify it.
     651      147929 :     if (ShrinkDemandedConstant(Op, NewMask, TLO))
     652             :       return true;
     653             :     // If the operation can be done in a smaller type, do so.
     654      147903 :     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
     655             :       return true;
     656             : 
     657             :     // Output known-0 bits are only known if clear in both the LHS & RHS.
     658             :     Known.Zero &= Known2.Zero;
     659             :     // Output known-1 are known to be set if set in either the LHS | RHS.
     660             :     Known.One |= Known2.One;
     661             :     break;
     662      103987 :   case ISD::XOR: {
     663      207974 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
     664             :       return true;
     665             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     666      207804 :     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, Known2, TLO, Depth+1))
     667             :       return true;
     668             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     669             : 
     670             :     // If all of the demanded bits are known zero on one side, return the other.
     671             :     // These bits cannot contribute to the result of the 'xor'.
     672      207628 :     if (NewMask.isSubsetOf(Known.Zero))
     673          18 :       return TLO.CombineTo(Op, Op.getOperand(0));
     674      103805 :     if (NewMask.isSubsetOf(Known2.Zero))
     675          12 :       return TLO.CombineTo(Op, Op.getOperand(1));
     676             :     // If the operation can be done in a smaller type, do so.
     677      103799 :     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
     678             :       return true;
     679             : 
     680             :     // If all of the unknown bits are known to be zero on one side or the other
     681             :     // (but not both) turn this into an *inclusive* or.
     682             :     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
     683      726362 :     if ((NewMask & ~Known.Zero & ~Known2.Zero) == 0)
     684         408 :       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT,
     685             :                                                Op.getOperand(0),
     686         136 :                                                Op.getOperand(1)));
     687             : 
     688             :     // Output known-0 bits are known if clear or set in both the LHS & RHS.
     689      518150 :     KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
     690             :     // Output known-1 are known to be set if set in only one of the LHS, RHS.
     691      414520 :     KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
     692             : 
     693             :     // If all of the demanded bits on one side are known, and all of the set
     694             :     // bits on that side are also known to be set on the other side, turn this
     695             :     // into an AND, as we know the bits will be cleared.
     696             :     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
     697             :     // NB: it is okay if more bits are known than are requested
     698      207260 :     if (NewMask.isSubsetOf(Known.Zero|Known.One)) { // all known on one side
     699       83164 :       if (Known.One == Known2.One) { // set bits are the same on both sides
     700          15 :         SDValue ANDC = TLO.DAG.getConstant(~Known.One & NewMask, dl, VT);
     701           9 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
     702           3 :                                                  Op.getOperand(0), ANDC));
     703             :       }
     704             :     }
     705             : 
     706             :     // If the RHS is a constant, see if we can change it. Don't alter a -1
     707             :     // constant because that's a 'not' op, and that is better for combining and
     708             :     // codegen.
     709      207254 :     ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1));
     710      180165 :     if (C && !C->isAllOnesValue()) {
     711       30464 :       if (NewMask.isSubsetOf(C->getAPIntValue())) {
     712             :         // We're flipping all demanded bits. Flip the undemanded bits too.
     713         174 :         SDValue New = TLO.DAG.getNOT(dl, Op.getOperand(0), VT);
     714             :         return TLO.CombineTo(Op, New);
     715             :       }
     716             :       // If we can't turn this into a 'not', try to shrink the constant.
     717       30377 :       if (ShrinkDemandedConstant(Op, NewMask, TLO))
     718             :         return true;
     719             :     }
     720             : 
     721      103507 :     Known = std::move(KnownOut);
     722      103507 :     break;
     723             :   }
     724       52664 :   case ISD::SELECT:
     725      105328 :     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, Known, TLO, Depth+1))
     726             :       return true;
     727      105270 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known2, TLO, Depth+1))
     728             :       return true;
     729             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     730             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     731             : 
     732             :     // If the operands are constants, see if we can simplify them.
     733       52605 :     if (ShrinkDemandedConstant(Op, NewMask, TLO))
     734             :       return true;
     735             : 
     736             :     // Only known if known in both the LHS and RHS.
     737       52605 :     Known.One &= Known2.One;
     738       52605 :     Known.Zero &= Known2.Zero;
     739             :     break;
     740        3855 :   case ISD::SELECT_CC:
     741        7710 :     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, Known, TLO, Depth+1))
     742             :       return true;
     743        7710 :     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, Known2, TLO, Depth+1))
     744             :       return true;
     745             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     746             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     747             : 
     748             :     // If the operands are constants, see if we can simplify them.
     749        3855 :     if (ShrinkDemandedConstant(Op, NewMask, TLO))
     750             :       return true;
     751             : 
     752             :     // Only known if known in both the LHS and RHS.
     753        3855 :     Known.One &= Known2.One;
     754        3855 :     Known.Zero &= Known2.Zero;
     755             :     break;
     756       55289 :   case ISD::SETCC: {
     757       55289 :     SDValue Op0 = Op.getOperand(0);
     758       55289 :     SDValue Op1 = Op.getOperand(1);
     759       55289 :     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
     760             :     // If (1) we only need the sign-bit, (2) the setcc operands are the same
     761             :     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
     762             :     // -1, we may be able to bypass the setcc.
     763       55911 :     if (NewMask.isSignMask() && Op0.getScalarValueSizeInBits() == BitWidth &&
     764         622 :         getBooleanContents(VT) ==
     765             :             BooleanContent::ZeroOrNegativeOneBooleanContent) {
     766             :       // If we're testing X < 0, then this compare isn't needed - just use X!
     767             :       // FIXME: We're limiting to integer types here, but this should also work
     768             :       // if we don't care about FP signed-zero. The use of SETLT with FP means
     769             :       // that we don't care about NaNs.
     770        1278 :       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
     771          46 :           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
     772          23 :         return TLO.CombineTo(Op, Op0);
     773             : 
     774             :       // TODO: Should we check for other forms of sign-bit comparisons?
     775             :       // Examples: X <= -1, X >= 0
     776             :     }
     777      110532 :     if (getBooleanContents(Op0.getValueType()) ==
     778       55266 :             TargetLowering::ZeroOrOneBooleanContent &&
     779             :         BitWidth > 1)
     780       18820 :       Known.Zero.setBitsFrom(1);
     781       55266 :     break;
     782             :   }
     783      390506 :   case ISD::SHL:
     784      390506 :     if (ConstantSDNode *SA = isConstOrConstSplat(Op.getOperand(1))) {
     785      766664 :       SDValue InOp = Op.getOperand(0);
     786             : 
     787             :       // If the shift count is an invalid immediate, don't do anything.
     788     1149996 :       if (SA->getAPIntValue().uge(BitWidth))
     789             :         break;
     790             : 
     791      383316 :       unsigned ShAmt = SA->getZExtValue();
     792             : 
     793             :       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
     794             :       // single shift.  We can do this if the bottom bits (which are shifted
     795             :       // out) are never demanded.
     796      383316 :       if (InOp.getOpcode() == ISD::SRL) {
     797        3816 :         if (ConstantSDNode *SA2 = isConstOrConstSplat(InOp.getOperand(1))) {
     798       14008 :           if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
     799        1822 :             if (SA2->getAPIntValue().ult(BitWidth)) {
     800         911 :               unsigned C1 = SA2->getZExtValue();
     801             :               unsigned Opc = ISD::SHL;
     802         911 :               int Diff = ShAmt-C1;
     803         911 :               if (Diff < 0) {
     804          31 :                 Diff = -Diff;
     805             :                 Opc = ISD::SRL;
     806             :               }
     807             : 
     808             :               SDValue NewSA =
     809        2733 :                 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
     810        2733 :               return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
     811             :                                                        InOp.getOperand(0),
     812             :                                                        NewSA));
     813             :             }
     814             :           }
     815             :         }
     816             :       }
     817             : 
     818      764810 :       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), Known, TLO, Depth+1))
     819             :         return true;
     820             : 
     821             :       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
     822             :       // are not demanded. This will likely allow the anyext to be folded away.
     823      372913 :       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
     824       13626 :         SDValue InnerOp = InOp.getOperand(0);
     825       13626 :         EVT InnerVT = InnerOp.getValueType();
     826             :         unsigned InnerBits = InnerVT.getScalarSizeInBits();
     827       13876 :         if (ShAmt < InnerBits && NewMask.getActiveBits() <= InnerBits &&
     828          48 :             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
     829           5 :           EVT ShTy = getShiftAmountTy(InnerVT, DL);
     830          10 :           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
     831           0 :             ShTy = InnerVT;
     832             :           SDValue NarrowShl =
     833           5 :             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
     834           5 :                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
     835             :           return
     836          10 :             TLO.CombineTo(Op,
     837           5 :                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
     838             :         }
     839             :         // Repeat the SHL optimization above in cases where an extension
     840             :         // intervenes: (shl (anyext (shr x, c1)), c2) to
     841             :         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
     842             :         // aren't demanded (as above) and that the shifted upper c1 bits of
     843             :         // x aren't demanded.
     844       27833 :         if (InOp.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
     845             :             InnerOp.hasOneUse()) {
     846         604 :           if (ConstantSDNode *SA2 = isConstOrConstSplat(InnerOp.getOperand(1))) {
     847        1142 :             unsigned InnerShAmt = SA2->getLimitedValue(InnerBits);
     848             :             if (InnerShAmt < ShAmt &&
     849         569 :                 InnerShAmt < InnerBits &&
     850        1148 :                 NewMask.getActiveBits() <= (InnerBits - InnerShAmt + ShAmt) &&
     851           8 :                 NewMask.countTrailingZeros() >= ShAmt) {
     852             :               SDValue NewSA =
     853           4 :                 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
     854           6 :                                     Op.getOperand(1).getValueType());
     855           2 :               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
     856           2 :                                                InnerOp.getOperand(0));
     857           6 :               return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
     858             :                                                        NewExt, NewSA));
     859             :             }
     860             :           }
     861             :         }
     862             :       }
     863             : 
     864      372906 :       Known.Zero <<= ShAmt;
     865      372906 :       Known.One  <<= ShAmt;
     866             :       // low bits known zero.
     867             :       Known.Zero.setLowBits(ShAmt);
     868             :     }
     869             :     break;
     870      210818 :   case ISD::SRL:
     871      210818 :     if (ConstantSDNode *SA = isConstOrConstSplat(Op.getOperand(1))) {
     872      409576 :       SDValue InOp = Op.getOperand(0);
     873             : 
     874             :       // If the shift count is an invalid immediate, don't do anything.
     875      614364 :       if (SA->getAPIntValue().uge(BitWidth))
     876             :         break;
     877             : 
     878      204784 :       unsigned ShAmt = SA->getZExtValue();
     879             :       APInt InDemandedMask = (NewMask << ShAmt);
     880             : 
     881             :       // If the shift is exact, then it does demand the low bits (and knows that
     882             :       // they are zero).
     883      409568 :       if (Op->getFlags().hasExact())
     884             :         InDemandedMask.setLowBits(ShAmt);
     885             : 
     886             :       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
     887             :       // single shift.  We can do this if the top bits (which are shifted out)
     888             :       // are never demanded.
     889      204784 :       if (InOp.getOpcode() == ISD::SHL) {
     890        1506 :         if (ConstantSDNode *SA2 = isConstOrConstSplat(InOp.getOperand(1))) {
     891        2994 :           if (ShAmt &&
     892        4990 :               (NewMask & APInt::getHighBitsSet(BitWidth, ShAmt)) == 0) {
     893        1702 :             if (SA2->getAPIntValue().ult(BitWidth)) {
     894         851 :               unsigned C1 = SA2->getZExtValue();
     895             :               unsigned Opc = ISD::SRL;
     896         851 :               int Diff = ShAmt-C1;
     897         851 :               if (Diff < 0) {
     898           0 :                 Diff = -Diff;
     899             :                 Opc = ISD::SHL;
     900             :               }
     901             : 
     902             :               SDValue NewSA =
     903        2553 :                 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
     904        2553 :               return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
     905             :                                                        InOp.getOperand(0),
     906             :                                                        NewSA));
     907             :             }
     908             :           }
     909             :         }
     910             :       }
     911             : 
     912             :       // Compute the new bits that are at the top now.
     913      203933 :       if (SimplifyDemandedBits(InOp, InDemandedMask, Known, TLO, Depth+1))
     914             :         return true;
     915             :       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     916      192917 :       Known.Zero.lshrInPlace(ShAmt);
     917      192917 :       Known.One.lshrInPlace(ShAmt);
     918             : 
     919             :       Known.Zero.setHighBits(ShAmt);  // High bits known zero.
     920             :     }
     921             :     break;
     922             :   case ISD::SRA:
     923             :     // If this is an arithmetic shift right and only the low-bit is set, we can
     924             :     // always convert this into a logical shr, even if the shift amount is
     925             :     // variable.  The low bit of the shift cannot be an input sign bit unless
     926             :     // the shift amount is >= the size of the datatype, which is undefined.
     927       34454 :     if (NewMask.isOneValue())
     928          60 :       return TLO.CombineTo(Op,
     929          30 :                            TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
     930             :                                            Op.getOperand(1)));
     931             : 
     932       34424 :     if (ConstantSDNode *SA = isConstOrConstSplat(Op.getOperand(1))) {
     933             :       // If the shift count is an invalid immediate, don't do anything.
     934      101799 :       if (SA->getAPIntValue().uge(BitWidth))
     935             :         break;
     936             : 
     937       33933 :       unsigned ShAmt = SA->getZExtValue();
     938             :       APInt InDemandedMask = (NewMask << ShAmt);
     939             : 
     940             :       // If the shift is exact, then it does demand the low bits (and knows that
     941             :       // they are zero).
     942       67866 :       if (Op->getFlags().hasExact())
     943             :         InDemandedMask.setLowBits(ShAmt);
     944             : 
     945             :       // If any of the demanded bits are produced by the sign extension, we also
     946             :       // demand the input sign bit.
     947       33933 :       if (NewMask.countLeadingZeros() < ShAmt)
     948       33634 :         InDemandedMask.setSignBit();
     949             : 
     950       67866 :       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, Known, TLO,
     951             :                                Depth+1))
     952             :         return true;
     953             :       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     954       32025 :       Known.Zero.lshrInPlace(ShAmt);
     955       32025 :       Known.One.lshrInPlace(ShAmt);
     956             : 
     957             :       // If the input sign bit is known to be zero, or if none of the top bits
     958             :       // are demanded, turn this into an unsigned shift right.
     959       96062 :       if (Known.Zero[BitWidth - ShAmt - 1] ||
     960       32012 :           NewMask.countLeadingZeros() >= ShAmt) {
     961             :         SDNodeFlags Flags;
     962         594 :         Flags.setExact(Op->getFlags().hasExact());
     963         297 :         return TLO.CombineTo(Op,
     964         297 :                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
     965             :                                              Op.getOperand(1), Flags));
     966             :       }
     967             : 
     968       31728 :       int Log2 = NewMask.exactLogBase2();
     969       31728 :       if (Log2 >= 0) {
     970             :         // The bit must come from the sign.
     971             :         SDValue NewSA =
     972         356 :           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
     973         534 :                               Op.getOperand(1).getValueType());
     974         534 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
     975         178 :                                                  Op.getOperand(0), NewSA));
     976             :       }
     977             : 
     978       31550 :       if (Known.One[BitWidth - ShAmt - 1])
     979             :         // New bits are known one.
     980             :         Known.One.setHighBits(ShAmt);
     981             :     }
     982             :     break;
     983       53197 :   case ISD::SIGN_EXTEND_INREG: {
     984       53197 :     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
     985             :     unsigned ExVTBits = ExVT.getScalarSizeInBits();
     986             : 
     987             :     // If we only care about the highest bit, don't bother shifting right.
     988       53197 :     if (NewMask.isSignMask()) {
     989         380 :       SDValue InOp = Op.getOperand(0);
     990             :       bool AlreadySignExtended =
     991         190 :         TLO.DAG.ComputeNumSignBits(InOp) >= BitWidth-ExVTBits+1;
     992             :       // However if the input is already sign extended we expect the sign
     993             :       // extension to be dropped altogether later and do not simplify.
     994         190 :       if (!AlreadySignExtended) {
     995             :         // Compute the correct shift amount type, which must be getShiftAmountTy
     996             :         // for scalar types after legalization.
     997         190 :         EVT ShiftAmtTy = VT;
     998         379 :         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
     999           3 :           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
    1000             : 
    1001         190 :         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
    1002         190 :                                                ShiftAmtTy);
    1003         570 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, InOp,
    1004             :                                                  ShiftAmt));
    1005             :       }
    1006             :     }
    1007             : 
    1008             :     // If none of the extended bits are demanded, eliminate the sextinreg.
    1009       53007 :     if (NewMask.getActiveBits() <= ExVTBits)
    1010         826 :       return TLO.CombineTo(Op, Op.getOperand(0));
    1011             : 
    1012       52594 :     APInt InputDemandedBits = NewMask.getLoBits(ExVTBits);
    1013             : 
    1014             :     // Since the sign extended bits are demanded, we know that the sign
    1015             :     // bit is demanded.
    1016       52594 :     InputDemandedBits.setBit(ExVTBits - 1);
    1017             : 
    1018      105188 :     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
    1019             :                              Known, TLO, Depth+1))
    1020             :       return true;
    1021             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1022             : 
    1023             :     // If the sign bit of the input is known set or clear, then we know the
    1024             :     // top bits of the result.
    1025             : 
    1026             :     // If the input sign bit is known zero, convert this into a zero extension.
    1027       50493 :     if (Known.Zero[ExVTBits - 1])
    1028           0 :       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
    1029           0 :                                    Op.getOperand(0), dl, ExVT.getScalarType()));
    1030             : 
    1031       50493 :     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
    1032       50493 :     if (Known.One[ExVTBits - 1]) {    // Input sign bit known set
    1033           2 :       Known.One.setBitsFrom(ExVTBits);
    1034           2 :       Known.Zero &= Mask;
    1035             :     } else {                       // Input sign bit unknown
    1036       50491 :       Known.Zero &= Mask;
    1037       50491 :       Known.One &= Mask;
    1038             :     }
    1039             :     break;
    1040             :   }
    1041        6363 :   case ISD::BUILD_PAIR: {
    1042       12726 :     EVT HalfVT = Op.getOperand(0).getValueType();
    1043             :     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
    1044             : 
    1045       12726 :     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
    1046       12726 :     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
    1047             : 
    1048             :     KnownBits KnownLo, KnownHi;
    1049             : 
    1050       12726 :     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
    1051        1127 :       return true;
    1052             : 
    1053       12430 :     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
    1054             :       return true;
    1055             : 
    1056       10472 :     Known.Zero = KnownLo.Zero.zext(BitWidth) |
    1057       15708 :                 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
    1058             : 
    1059       10472 :     Known.One = KnownLo.One.zext(BitWidth) |
    1060       15708 :                KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
    1061        5236 :     break;
    1062             :   }
    1063      217932 :   case ISD::ZERO_EXTEND: {
    1064      217932 :     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
    1065             : 
    1066             :     // If none of the top bits are demanded, convert this into an any_extend.
    1067      217932 :     if (NewMask.getActiveBits() <= OperandBitWidth)
    1068        4941 :       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
    1069        1647 :                                                Op.getOperand(0)));
    1070             : 
    1071      216285 :     APInt InMask = NewMask.trunc(OperandBitWidth);
    1072      432570 :     if (SimplifyDemandedBits(Op.getOperand(0), InMask, Known, TLO, Depth+1))
    1073             :       return true;
    1074             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1075      215755 :     Known = Known.zext(BitWidth);
    1076      215755 :     Known.Zero.setBitsFrom(OperandBitWidth);
    1077             :     break;
    1078             :   }
    1079       11403 :   case ISD::SIGN_EXTEND: {
    1080       34209 :     unsigned InBits = Op.getOperand(0).getValueType().getScalarSizeInBits();
    1081             : 
    1082             :     // If none of the top bits are demanded, convert this into an any_extend.
    1083       11403 :     if (NewMask.getActiveBits() <= InBits)
    1084        4950 :       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
    1085        1650 :                                               Op.getOperand(0)));
    1086             : 
    1087             :     // Since some of the sign extended bits are demanded, we know that the sign
    1088             :     // bit is demanded.
    1089        9753 :     APInt InDemandedBits = NewMask.trunc(InBits);
    1090        9753 :     InDemandedBits.setBit(InBits - 1);
    1091             : 
    1092       19506 :     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, Known, TLO,
    1093             :                              Depth+1))
    1094             :       return true;
    1095             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1096             :     // If the sign bit is known one, the top bits match.
    1097        9691 :     Known = Known.sext(BitWidth);
    1098             : 
    1099             :     // If the sign bit is known zero, convert this to a zero extend.
    1100        9691 :     if (Known.isNonNegative())
    1101        6699 :       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT,
    1102        2233 :                                                Op.getOperand(0)));
    1103             :     break;
    1104             :   }
    1105       66467 :   case ISD::ANY_EXTEND: {
    1106       66467 :     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
    1107       66467 :     APInt InMask = NewMask.trunc(OperandBitWidth);
    1108      132934 :     if (SimplifyDemandedBits(Op.getOperand(0), InMask, Known, TLO, Depth+1))
    1109             :       return true;
    1110             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1111       65967 :     Known = Known.zext(BitWidth);
    1112             :     break;
    1113             :   }
    1114      180156 :   case ISD::TRUNCATE: {
    1115             :     // Simplify the input, using demanded bit information, and compute the known
    1116             :     // zero/one bits live out.
    1117      180156 :     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
    1118      180156 :     APInt TruncMask = NewMask.zext(OperandBitWidth);
    1119      360312 :     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, Known, TLO, Depth+1))
    1120             :       return true;
    1121      171713 :     Known = Known.trunc(BitWidth);
    1122             : 
    1123             :     // If the input is only used by this truncate, see if we can shrink it based
    1124             :     // on the known demanded bits.
    1125      343426 :     if (Op.getOperand(0).getNode()->hasOneUse()) {
    1126             :       SDValue In = Op.getOperand(0);
    1127      132403 :       switch (In.getOpcode()) {
    1128      132255 :       default: break;
    1129       34780 :       case ISD::SRL:
    1130             :         // Shrink SRL by a constant if none of the high bits shifted in are
    1131             :         // demanded.
    1132       34780 :         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
    1133             :           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
    1134             :           // undesirable.
    1135             :           break;
    1136             :         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
    1137             :         if (!ShAmt)
    1138             :           break;
    1139       29811 :         SDValue Shift = In.getOperand(1);
    1140       29811 :         if (TLO.LegalTypes()) {
    1141       28266 :           uint64_t ShVal = ShAmt->getZExtValue();
    1142       28266 :           Shift = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL));
    1143             :         }
    1144             : 
    1145       59622 :         if (ShAmt->getZExtValue() < BitWidth) {
    1146             :           APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
    1147        1340 :                                                  OperandBitWidth - BitWidth);
    1148        2680 :           HighBits.lshrInPlace(ShAmt->getZExtValue());
    1149        2680 :           HighBits = HighBits.trunc(BitWidth);
    1150             : 
    1151        2680 :           if (!(HighBits & NewMask)) {
    1152             :             // None of the shifted in bits are needed.  Add a truncate of the
    1153             :             // shift input, then shift it.
    1154         148 :             SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl, VT,
    1155         148 :                                                In.getOperand(0));
    1156         444 :             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc,
    1157             :                                                      Shift));
    1158             :           }
    1159             :         }
    1160             :         break;
    1161             :       }
    1162             :     }
    1163             : 
    1164             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1165             :     break;
    1166             :   }
    1167       34341 :   case ISD::AssertZext: {
    1168             :     // AssertZext demands all of the high bits, plus any of the low bits
    1169             :     // demanded by its users.
    1170       34341 :     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
    1171       34341 :     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
    1172      206046 :     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
    1173             :                              Known, TLO, Depth+1))
    1174             :       return true;
    1175             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1176             : 
    1177      103023 :     Known.Zero |= ~InMask;
    1178             :     break;
    1179             :   }
    1180       88576 :   case ISD::BITCAST:
    1181             :     // If this is an FP->Int bitcast and if the sign bit is the only
    1182             :     // thing demanded, turn this into a FGETSIGN.
    1183      193206 :     if (!TLO.LegalOperations() && !VT.isVector() &&
    1184      100511 :         !Op.getOperand(0).getValueType().isVector() &&
    1185      267641 :         NewMask == APInt::getSignMask(Op.getValueSizeInBits()) &&
    1186         124 :         Op.getOperand(0).getValueType().isFloatingPoint()) {
    1187          31 :       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
    1188             :       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
    1189          31 :       if ((OpVTLegal || i32Legal) && VT.isSimple() &&
    1190          10 :            Op.getOperand(0).getValueType() != MVT::f128) {
    1191             :         // Cannot eliminate/lower SHL for f128 yet.
    1192           5 :         EVT Ty = OpVTLegal ? VT : MVT::i32;
    1193             :         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
    1194             :         // place.  We expect the SHL to be eliminated by other optimizations.
    1195          15 :         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
    1196           5 :         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
    1197           5 :         if (!OpVTLegal && OpVTSizeInBits > 32)
    1198           0 :           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
    1199           5 :         unsigned ShVal = Op.getValueSizeInBits() - 1;
    1200           5 :         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
    1201          15 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
    1202             :       }
    1203             :     }
    1204             :     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
    1205             :     // recursive call where Known may be useful to the caller.
    1206       88571 :     if (Depth > 0) {
    1207       87176 :       TLO.DAG.computeKnownBits(Op, Known, Depth);
    1208       87176 :       return false;
    1209             :     }
    1210             :     break;
    1211     1929463 :   case ISD::ADD:
    1212             :   case ISD::MUL:
    1213             :   case ISD::SUB: {
    1214             :     // Add, Sub, and Mul don't demand any bits in positions beyond that
    1215             :     // of the highest bit demanded of them.
    1216     1929463 :     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
    1217     1929463 :     unsigned NewMaskLZ = NewMask.countLeadingZeros();
    1218     1929463 :     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - NewMaskLZ);
    1219     3855757 :     if (SimplifyDemandedBits(Op0, LoMask, Known2, TLO, Depth + 1) ||
    1220     3851887 :         SimplifyDemandedBits(Op1, LoMask, Known2, TLO, Depth + 1) ||
    1221             :         // See if the operation should be performed at a smaller bit width.
    1222     1922423 :         ShrinkDemandedOp(Op, BitWidth, NewMask, TLO)) {
    1223       14872 :       SDNodeFlags Flags = Op.getNode()->getFlags();
    1224        7436 :       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
    1225             :         // Disable the nsw and nuw flags. We can no longer guarantee that we
    1226             :         // won't wrap after simplification.
    1227             :         Flags.setNoSignedWrap(false);
    1228             :         Flags.setNoUnsignedWrap(false);
    1229         357 :         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
    1230         357 :                                         Flags);
    1231             :         return TLO.CombineTo(Op, NewOp);
    1232             :       }
    1233             :       return true;
    1234             :     }
    1235             : 
    1236             :     // If we have a constant operand, we may be able to turn it into -1 if we
    1237             :     // do not demand the high bits. This can make the constant smaller to
    1238             :     // encode, allow more general folding, or match specialized instruction
    1239             :     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
    1240             :     // is probably not useful (and could be detrimental).
    1241     1922028 :     ConstantSDNode *C = isConstOrConstSplat(Op1);
    1242     1922028 :     APInt HighMask = APInt::getHighBitsSet(NewMask.getBitWidth(), NewMaskLZ);
    1243     8952526 :     if (C && !C->isAllOnesValue() && !C->isOne() &&
    1244     5766084 :         (C->getAPIntValue() | HighMask).isAllOnesValue()) {
    1245          15 :       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
    1246             :       // We can't guarantee that the new math op doesn't wrap, so explicitly
    1247             :       // clear those flags to prevent folding with a potential existing node
    1248             :       // that has those flags set.
    1249             :       SDNodeFlags Flags;
    1250             :       Flags.setNoSignedWrap(false);
    1251             :       Flags.setNoUnsignedWrap(false);
    1252          30 :       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
    1253             :       return TLO.CombineTo(Op, NewOp);
    1254             :     }
    1255             : 
    1256             :     LLVM_FALLTHROUGH;
    1257             :   }
    1258             :   default:
    1259             :     // Just use computeKnownBits to compute output bits.
    1260     2930824 :     TLO.DAG.computeKnownBits(Op, Known, Depth);
    1261     2930823 :     break;
    1262             :   }
    1263             : 
    1264             :   // If we know the value of all of the demanded bits, return this as a
    1265             :   // constant.
    1266    13998687 :   if (NewMask.isSubsetOf(Known.Zero|Known.One)) {
    1267             :     // Avoid folding to a constant if any OpaqueConstant is involved.
    1268        8072 :     const SDNode *N = Op.getNode();
    1269             :     for (SDNodeIterator I = SDNodeIterator::begin(N),
    1270       22084 :          E = SDNodeIterator::end(N); I != E; ++I) {
    1271             :       SDNode *Op = *I;
    1272             :       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
    1273        8468 :         if (C->isOpaque())
    1274             :           return false;
    1275             :     }
    1276       16136 :     return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
    1277             :   }
    1278             : 
    1279             :   return false;
    1280             : }
    1281             : 
    1282           0 : bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
    1283             :                                                 const APInt &DemandedElts,
    1284             :                                                 APInt &KnownUndef,
    1285             :                                                 APInt &KnownZero,
    1286             :                                                 DAGCombinerInfo &DCI) const {
    1287           0 :   SelectionDAG &DAG = DCI.DAG;
    1288           0 :   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
    1289           0 :                         !DCI.isBeforeLegalizeOps());
    1290             : 
    1291             :   bool Simplified =
    1292           0 :       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
    1293           0 :   if (Simplified)
    1294           0 :     DCI.CommitTargetLoweringOpt(TLO);
    1295           0 :   return Simplified;
    1296             : }
    1297             : 
    1298      188894 : bool TargetLowering::SimplifyDemandedVectorElts(
    1299             :     SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef,
    1300             :     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
    1301             :     bool AssumeSingleUse) const {
    1302      377788 :   EVT VT = Op.getValueType();
    1303             :   APInt DemandedElts = DemandedEltMask;
    1304      188894 :   unsigned NumElts = DemandedElts.getBitWidth();
    1305             :   assert(VT.isVector() && "Expected vector op");
    1306             :   assert(VT.getVectorNumElements() == NumElts &&
    1307             :          "Mask size mismatches value type element count!");
    1308             : 
    1309      566682 :   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
    1310             : 
    1311             :   // Undef operand.
    1312      377788 :   if (Op.isUndef()) {
    1313       40401 :     KnownUndef.setAllBits();
    1314       40401 :     return false;
    1315             :   }
    1316             : 
    1317             :   // If Op has other users, assume that all elements are needed.
    1318       27697 :   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
    1319       27697 :     DemandedElts.setAllBits();
    1320             : 
    1321             :   // Not demanding any elements from Op.
    1322      148493 :   if (DemandedElts == 0) {
    1323         377 :     KnownUndef.setAllBits();
    1324         754 :     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
    1325             :   }
    1326             : 
    1327             :   // Limit search depth.
    1328      148116 :   if (Depth >= 6)
    1329             :     return false;
    1330             : 
    1331             :   SDLoc DL(Op);
    1332             :   unsigned EltSizeInBits = VT.getScalarSizeInBits();
    1333             : 
    1334      295710 :   switch (Op.getOpcode()) {
    1335             :   case ISD::SCALAR_TO_VECTOR: {
    1336         494 :     if (!DemandedElts[0]) {
    1337           0 :       KnownUndef.setAllBits();
    1338           0 :       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
    1339             :     }
    1340         494 :     KnownUndef.setHighBits(NumElts - 1);
    1341             :     break;
    1342             :   }
    1343             :   case ISD::BUILD_VECTOR: {
    1344             :     // Check all elements and simplify any unused elements with UNDEF.
    1345        8342 :     if (!DemandedElts.isAllOnesValue()) {
    1346             :       // Don't simplify BROADCASTS.
    1347        4598 :       if (llvm::any_of(Op->op_values(),
    1348       11764 :                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
    1349        1472 :         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
    1350             :         bool Updated = false;
    1351       34000 :         for (unsigned i = 0; i != NumElts; ++i) {
    1352       38260 :           if (!DemandedElts[i] && !Ops[i].isUndef()) {
    1353        1593 :             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
    1354             :             KnownUndef.setBit(i);
    1355             :             Updated = true;
    1356             :           }
    1357             :         }
    1358        1472 :         if (Updated)
    1359         672 :           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
    1360             :       }
    1361             :     }
    1362      205012 :     for (unsigned i = 0; i != NumElts; ++i) {
    1363      196894 :       SDValue SrcOp = Op.getOperand(i);
    1364      196894 :       if (SrcOp.isUndef()) {
    1365             :         KnownUndef.setBit(i);
    1366      176163 :       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
    1367       95225 :                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
    1368             :         KnownZero.setBit(i);
    1369             :       }
    1370             :     }
    1371             :     break;
    1372             :   }
    1373        3893 :   case ISD::CONCAT_VECTORS: {
    1374        7786 :     EVT SubVT = Op.getOperand(0).getValueType();
    1375             :     unsigned NumSubVecs = Op.getNumOperands();
    1376        3893 :     unsigned NumSubElts = SubVT.getVectorNumElements();
    1377       24205 :     for (unsigned i = 0; i != NumSubVecs; ++i) {
    1378       20560 :       SDValue SubOp = Op.getOperand(i);
    1379       10280 :       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
    1380             :       APInt SubUndef, SubZero;
    1381       10280 :       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
    1382             :                                      Depth + 1))
    1383             :         return true;
    1384       10156 :       KnownUndef.insertBits(SubUndef, i * NumSubElts);
    1385       10156 :       KnownZero.insertBits(SubZero, i * NumSubElts);
    1386             :     }
    1387        3769 :     break;
    1388             :   }
    1389          14 :   case ISD::INSERT_SUBVECTOR: {
    1390             :     if (!isa<ConstantSDNode>(Op.getOperand(2)))
    1391             :       break;
    1392          14 :     SDValue Base = Op.getOperand(0);
    1393          14 :     SDValue Sub = Op.getOperand(1);
    1394          14 :     EVT SubVT = Sub.getValueType();
    1395          14 :     unsigned NumSubElts = SubVT.getVectorNumElements();
    1396          14 :     APInt Idx = cast<ConstantSDNode>(Op.getOperand(2))->getAPIntValue();
    1397          28 :     if (Idx.uge(NumElts - NumSubElts))
    1398             :       break;
    1399          14 :     unsigned SubIdx = Idx.getZExtValue();
    1400          14 :     APInt SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
    1401             :     APInt SubUndef, SubZero;
    1402          14 :     if (SimplifyDemandedVectorElts(Sub, SubElts, SubUndef, SubZero, TLO,
    1403             :                                    Depth + 1))
    1404             :       return true;
    1405             :     APInt BaseElts = DemandedElts;
    1406          28 :     BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
    1407          14 :     if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO,
    1408             :                                    Depth + 1))
    1409             :       return true;
    1410          14 :     KnownUndef.insertBits(SubUndef, SubIdx);
    1411          14 :     KnownZero.insertBits(SubZero, SubIdx);
    1412             :     break;
    1413             :   }
    1414        2396 :   case ISD::INSERT_VECTOR_ELT: {
    1415        2396 :     SDValue Vec = Op.getOperand(0);
    1416        2396 :     SDValue Scl = Op.getOperand(1);
    1417             :     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
    1418             : 
    1419             :     // For a legal, constant insertion index, if we don't need this insertion
    1420             :     // then strip it, else remove it from the demanded elts.
    1421        4792 :     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
    1422        2396 :       unsigned Idx = CIdx->getZExtValue();
    1423        2396 :       if (!DemandedElts[Idx])
    1424         106 :         return TLO.CombineTo(Op, Vec);
    1425             :       DemandedElts.clearBit(Idx);
    1426             : 
    1427        2361 :       if (SimplifyDemandedVectorElts(Vec, DemandedElts, KnownUndef,
    1428             :                                      KnownZero, TLO, Depth + 1))
    1429             :         return true;
    1430             : 
    1431             :       KnownUndef.clearBit(Idx);
    1432        2325 :       if (Scl.isUndef())
    1433             :         KnownUndef.setBit(Idx);
    1434             : 
    1435             :       KnownZero.clearBit(Idx);
    1436        2325 :       if (isNullConstant(Scl) || isNullFPConstant(Scl))
    1437             :         KnownZero.setBit(Idx);
    1438        2325 :       break;
    1439             :     }
    1440             : 
    1441             :     APInt VecUndef, VecZero;
    1442           0 :     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
    1443             :                                    Depth + 1))
    1444             :       return true;
    1445             :     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
    1446             :     break;
    1447             :   }
    1448             :   case ISD::VSELECT: {
    1449             :     APInt DemandedLHS(DemandedElts);
    1450             :     APInt DemandedRHS(DemandedElts);
    1451             : 
    1452             :     // TODO - add support for constant vselect masks.
    1453             : 
    1454             :     // See if we can simplify either vselect operand.
    1455             :     APInt UndefLHS, ZeroLHS;
    1456             :     APInt UndefRHS, ZeroRHS;
    1457         358 :     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
    1458             :                                    ZeroLHS, TLO, Depth + 1))
    1459             :       return true;
    1460         338 :     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
    1461             :                                    ZeroRHS, TLO, Depth + 1))
    1462             :       return true;
    1463             : 
    1464         169 :     KnownUndef = UndefLHS & UndefRHS;
    1465         169 :     KnownZero = ZeroLHS & ZeroRHS;
    1466             :     break;
    1467             :   }
    1468             :   case ISD::VECTOR_SHUFFLE: {
    1469             :     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
    1470             : 
    1471             :     // Collect demanded elements from shuffle operands..
    1472             :     APInt DemandedLHS(NumElts, 0);
    1473             :     APInt DemandedRHS(NumElts, 0);
    1474     1987555 :     for (unsigned i = 0; i != NumElts; ++i) {
    1475     1925578 :       int M = ShuffleMask[i];
    1476     1932429 :       if (M < 0 || !DemandedElts[i])
    1477      180986 :         continue;
    1478             :       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
    1479      781803 :       if (M < (int)NumElts)
    1480      635360 :         DemandedLHS.setBit(M);
    1481             :       else
    1482      146443 :         DemandedRHS.setBit(M - NumElts);
    1483             :     }
    1484             : 
    1485             :     // See if we can simplify either shuffle operand.
    1486             :     APInt UndefLHS, ZeroLHS;
    1487             :     APInt UndefRHS, ZeroRHS;
    1488      123954 :     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
    1489             :                                    ZeroLHS, TLO, Depth + 1))
    1490             :       return true;
    1491      121674 :     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
    1492             :                                    ZeroRHS, TLO, Depth + 1))
    1493             :       return true;
    1494             : 
    1495             :     // Simplify mask using undef elements from LHS/RHS.
    1496             :     bool Updated = false;
    1497             :     bool IdentityLHS = true, IdentityRHS = true;
    1498             :     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
    1499     1955128 :     for (unsigned i = 0; i != NumElts; ++i) {
    1500      947388 :       int &M = NewMask[i];
    1501      947388 :       if (M < 0)
    1502      172136 :         continue;
    1503     1403963 :       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
    1504      283438 :           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
    1505             :         Updated = true;
    1506        5854 :         M = -1;
    1507             :       }
    1508      775252 :       IdentityLHS &= (M < 0) || (M == (int)i);
    1509      775252 :       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
    1510             :     }
    1511             : 
    1512             :     // Update legal shuffle masks based on demanded elements if it won't reduce
    1513             :     // to Identity which can cause premature removal of the shuffle mask.
    1514       61180 :     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps &&
    1515       61355 :         isShuffleMaskLegal(NewMask, VT))
    1516        1306 :       return TLO.CombineTo(Op,
    1517         653 :                            TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0),
    1518         653 :                                                     Op.getOperand(1), NewMask));
    1519             : 
    1520             :     // Propagate undef/zero elements from LHS/RHS.
    1521     1944011 :     for (unsigned i = 0; i != NumElts; ++i) {
    1522     1884312 :       int M = ShuffleMask[i];
    1523      942156 :       if (M < 0) {
    1524             :         KnownUndef.setBit(i);
    1525      770528 :       } else if (M < (int)NumElts) {
    1526     1258506 :         if (UndefLHS[M])
    1527             :           KnownUndef.setBit(i);
    1528      629253 :         if (ZeroLHS[M])
    1529             :           KnownZero.setBit(i);
    1530             :       } else {
    1531      282550 :         if (UndefRHS[M - NumElts])
    1532             :           KnownUndef.setBit(i);
    1533      141275 :         if (ZeroRHS[M - NumElts])
    1534             :           KnownZero.setBit(i);
    1535             :       }
    1536             :     }
    1537             :     break;
    1538             :   }
    1539       70560 :   default: {
    1540       70560 :     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
    1541        5149 :       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
    1542        5149 :                                                   KnownZero, TLO, Depth))
    1543             :         return true;
    1544             :     break;
    1545             :   }
    1546             :   }
    1547             : 
    1548             :   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
    1549             :   return false;
    1550             : }
    1551             : 
    1552             : /// Determine which of the bits specified in Mask are known to be either zero or
    1553             : /// one and return them in the Known.
    1554       54762 : void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
    1555             :                                                    KnownBits &Known,
    1556             :                                                    const APInt &DemandedElts,
    1557             :                                                    const SelectionDAG &DAG,
    1558             :                                                    unsigned Depth) const {
    1559             :   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
    1560             :           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
    1561             :           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
    1562             :           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
    1563             :          "Should use MaskedValueIsZero if you don't know whether Op"
    1564             :          " is a target node!");
    1565             :   Known.resetAll();
    1566       54762 : }
    1567             : 
    1568      921692 : void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
    1569             :                                                    KnownBits &Known,
    1570             :                                                    const APInt &DemandedElts,
    1571             :                                                    const SelectionDAG &DAG,
    1572             :                                                    unsigned Depth) const {
    1573             :   assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex");
    1574             : 
    1575      921692 :   if (unsigned Align = DAG.InferPtrAlignment(Op)) {
    1576             :     // The low bits are known zero if the pointer is aligned.
    1577      921692 :     Known.Zero.setLowBits(Log2_32(Align));
    1578             :   }
    1579      921692 : }
    1580             : 
    1581             : /// This method can be implemented by targets that want to expose additional
    1582             : /// information about sign bits to the DAG Combiner.
    1583        1249 : unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
    1584             :                                                          const APInt &,
    1585             :                                                          const SelectionDAG &,
    1586             :                                                          unsigned Depth) const {
    1587             :   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
    1588             :           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
    1589             :           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
    1590             :           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
    1591             :          "Should use ComputeNumSignBits if you don't know whether Op"
    1592             :          " is a target node!");
    1593        1249 :   return 1;
    1594             : }
    1595             : 
    1596        5149 : bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
    1597             :     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
    1598             :     TargetLoweringOpt &TLO, unsigned Depth) const {
    1599             :   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
    1600             :           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
    1601             :           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
    1602             :           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
    1603             :          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
    1604             :          " is a target node!");
    1605        5149 :   return false;
    1606             : }
    1607             : 
    1608             : // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
    1609             : // work with truncating build vectors and vectors with elements of less than
    1610             : // 8 bits.
    1611       84028 : bool TargetLowering::isConstTrueVal(const SDNode *N) const {
    1612       84028 :   if (!N)
    1613             :     return false;
    1614             : 
    1615             :   APInt CVal;
    1616             :   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
    1617      121690 :     CVal = CN->getAPIntValue();
    1618             :   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
    1619        3069 :     auto *CN = BV->getConstantSplatNode();
    1620        3069 :     if (!CN)
    1621             :       return false;
    1622             : 
    1623             :     // If this is a truncating build vector, truncate the splat value.
    1624             :     // Otherwise, we may fail to match the expected values below.
    1625        8874 :     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
    1626        5916 :     CVal = CN->getAPIntValue();
    1627        2958 :     if (BVEltWidth < CVal.getBitWidth())
    1628         794 :       CVal = CVal.trunc(BVEltWidth);
    1629             :   } else {
    1630             :     return false;
    1631             :   }
    1632             : 
    1633      127606 :   switch (getBooleanContents(N->getValueType(0))) {
    1634             :   case UndefinedBooleanContent:
    1635         300 :     return CVal[0];
    1636             :   case ZeroOrOneBooleanContent:
    1637             :     return CVal.isOneValue();
    1638             :   case ZeroOrNegativeOneBooleanContent:
    1639             :     return CVal.isAllOnesValue();
    1640             :   }
    1641             : 
    1642           0 :   llvm_unreachable("Invalid boolean contents");
    1643             : }
    1644             : 
    1645         484 : bool TargetLowering::isConstFalseVal(const SDNode *N) const {
    1646         484 :   if (!N)
    1647             :     return false;
    1648             : 
    1649             :   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
    1650             :   if (!CN) {
    1651             :     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
    1652             :     if (!BV)
    1653             :       return false;
    1654             : 
    1655             :     // Only interested in constant splats, we don't care about undef
    1656             :     // elements in identifying boolean constants and getConstantSplatNode
    1657             :     // returns NULL if all ops are undef;
    1658           0 :     CN = BV->getConstantSplatNode();
    1659           0 :     if (!CN)
    1660             :       return false;
    1661             :   }
    1662             : 
    1663         964 :   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
    1664           0 :     return !CN->getAPIntValue()[0];
    1665             : 
    1666         482 :   return CN->isNullValue();
    1667             : }
    1668             : 
    1669           8 : bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
    1670             :                                        bool SExt) const {
    1671             :   if (VT == MVT::i1)
    1672           0 :     return N->isOne();
    1673             : 
    1674           8 :   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
    1675           8 :   switch (Cnt) {
    1676           0 :   case TargetLowering::ZeroOrOneBooleanContent:
    1677             :     // An extended value of 1 is always true, unless its original type is i1,
    1678             :     // in which case it will be sign extended to -1.
    1679           0 :     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
    1680           8 :   case TargetLowering::UndefinedBooleanContent:
    1681             :   case TargetLowering::ZeroOrNegativeOneBooleanContent:
    1682          16 :     return N->isAllOnesValue() && SExt;
    1683             :   }
    1684           0 :   llvm_unreachable("Unexpected enumeration.");
    1685             : }
    1686             : 
    1687             : /// This helper function of SimplifySetCC tries to optimize the comparison when
    1688             : /// either operand of the SetCC node is a bitwise-and instruction.
    1689      191294 : SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
    1690             :                                              ISD::CondCode Cond,
    1691             :                                              DAGCombinerInfo &DCI,
    1692             :                                              const SDLoc &DL) const {
    1693             :   // Match these patterns in any of their permutations:
    1694             :   // (X & Y) == Y
    1695             :   // (X & Y) != Y
    1696      191627 :   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
    1697             :     std::swap(N0, N1);
    1698             : 
    1699      191294 :   EVT OpVT = N0.getValueType();
    1700      199099 :   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
    1701        7805 :       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
    1702      183489 :     return SDValue();
    1703             : 
    1704        7805 :   SDValue X, Y;
    1705             :   if (N0.getOperand(0) == N1) {
    1706         268 :     X = N0.getOperand(1);
    1707         268 :     Y = N0.getOperand(0);
    1708             :   } else if (N0.getOperand(1) == N1) {
    1709         440 :     X = N0.getOperand(0);
    1710         440 :     Y = N0.getOperand(1);
    1711             :   } else {
    1712        7097 :     return SDValue();
    1713             :   }
    1714             : 
    1715         708 :   SelectionDAG &DAG = DCI.DAG;
    1716         708 :   SDValue Zero = DAG.getConstant(0, DL, OpVT);
    1717         708 :   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
    1718             :     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
    1719             :     // Note that where Y is variable and is known to have at most one bit set
    1720             :     // (for example, if it is Z & 1) we cannot do this; the expressions are not
    1721             :     // equivalent when Y == 0.
    1722         180 :     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
    1723         360 :     if (DCI.isBeforeLegalizeOps() ||
    1724             :         isCondCodeLegal(Cond, N0.getSimpleValueType()))
    1725         180 :       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
    1726         528 :   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
    1727             :     // If the target supports an 'and-not' or 'and-complement' logic operation,
    1728             :     // try to use that to make a comparison operation more efficient.
    1729             :     // But don't do this transform if the mask is a single bit because there are
    1730             :     // more efficient ways to deal with that case (for example, 'bt' on x86 or
    1731             :     // 'rlwinm' on PPC).
    1732             : 
    1733             :     // Bail out if the compare operand that we want to turn into a zero is
    1734             :     // already a zero (otherwise, infinite loop).
    1735             :     auto *YConst = dyn_cast<ConstantSDNode>(Y);
    1736          24 :     if (YConst && YConst->isNullValue())
    1737           0 :       return SDValue();
    1738             : 
    1739             :     // Transform this into: ~X & Y == 0.
    1740          68 :     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
    1741          68 :     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
    1742          34 :     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
    1743             :   }
    1744             : 
    1745         494 :   return SDValue();
    1746             : }
    1747             : 
    1748             : /// Try to simplify a setcc built with the specified operands and cc. If it is
    1749             : /// unable to simplify it, return a null SDValue.
    1750      293821 : SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
    1751             :                                       ISD::CondCode Cond, bool foldBooleans,
    1752             :                                       DAGCombinerInfo &DCI,
    1753             :                                       const SDLoc &dl) const {
    1754      293821 :   SelectionDAG &DAG = DCI.DAG;
    1755      587642 :   EVT OpVT = N0.getValueType();
    1756             : 
    1757             :   // These setcc operations always fold.
    1758      293821 :   switch (Cond) {
    1759             :   default: break;
    1760           0 :   case ISD::SETFALSE:
    1761           0 :   case ISD::SETFALSE2: return DAG.getBoolConstant(false, dl, VT, OpVT);
    1762           0 :   case ISD::SETTRUE:
    1763           0 :   case ISD::SETTRUE2:  return DAG.getBoolConstant(true, dl, VT, OpVT);
    1764             :   }
    1765             : 
    1766             :   // Ensure that the constant occurs on the RHS and fold constant comparisons.
    1767             :   // TODO: Handle non-splat vector constants. All undef causes trouble.
    1768      293821 :   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
    1769      294749 :   if (isConstOrConstSplat(N0) &&
    1770         928 :       (DCI.isBeforeLegalizeOps() ||
    1771             :        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
    1772         798 :     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
    1773             : 
    1774             :   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
    1775      198208 :     const APInt &C1 = N1C->getAPIntValue();
    1776             : 
    1777             :     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
    1778             :     // equality comparison, then we're just comparing whether X itself is
    1779             :     // zero.
    1780      199630 :     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
    1781      198790 :         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
    1782           0 :         N0.getOperand(1).getOpcode() == ISD::Constant) {
    1783             :       const APInt &ShAmt
    1784           0 :         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
    1785           0 :       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    1786           0 :           ShAmt == Log2_32(N0.getValueSizeInBits())) {
    1787           0 :         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
    1788             :           // (srl (ctlz x), 5) == 0  -> X != 0
    1789             :           // (srl (ctlz x), 5) != 1  -> X != 0
    1790             :           Cond = ISD::SETNE;
    1791             :         } else {
    1792             :           // (srl (ctlz x), 5) != 0  -> X == 0
    1793             :           // (srl (ctlz x), 5) == 1  -> X == 0
    1794             :           Cond = ISD::SETEQ;
    1795             :         }
    1796           0 :         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
    1797           0 :         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
    1798           0 :                             Zero, Cond);
    1799             :       }
    1800             :     }
    1801             : 
    1802      198208 :     SDValue CTPOP = N0;
    1803             :     // Look through truncs that don't change the value of a ctpop.
    1804      462721 :     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
    1805        3355 :       CTPOP = N0.getOperand(0);
    1806             : 
    1807      462566 :     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
    1808           4 :         (N0 == CTPOP ||
    1809           4 :          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
    1810           8 :       EVT CTVT = CTPOP.getValueType();
    1811           4 :       SDValue CTOp = CTPOP.getOperand(0);
    1812             : 
    1813             :       // (ctpop x) u< 2 -> (x & x-1) == 0
    1814             :       // (ctpop x) u> 1 -> (x & x-1) != 0
    1815           4 :       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
    1816             :         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
    1817           4 :                                   DAG.getConstant(1, dl, CTVT));
    1818           4 :         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
    1819           4 :         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
    1820           4 :         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
    1821             :       }
    1822             : 
    1823             :       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
    1824             :     }
    1825             : 
    1826             :     // (zext x) == C --> x == (trunc C)
    1827             :     // (sext x) == C --> x == (trunc C)
    1828      356157 :     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    1829      282030 :         DCI.isBeforeLegalize() && N0->hasOneUse()) {
    1830       12319 :       unsigned MinBits = N0.getValueSizeInBits();
    1831       12319 :       SDValue PreExt;
    1832             :       bool Signed = false;
    1833       24638 :       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
    1834             :         // ZExt
    1835         930 :         MinBits = N0->getOperand(0).getValueSizeInBits();
    1836         465 :         PreExt = N0->getOperand(0);
    1837       11854 :       } else if (N0->getOpcode() == ISD::AND) {
    1838             :         // DAGCombine turns costly ZExts into ANDs
    1839        2153 :         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
    1840        4588 :           if ((C->getAPIntValue()+1).isPowerOf2()) {
    1841         588 :             MinBits = C->getAPIntValue().countTrailingOnes();
    1842         588 :             PreExt = N0->getOperand(0);
    1843             :           }
    1844        9701 :       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
    1845             :         // SExt
    1846         296 :         MinBits = N0->getOperand(0).getValueSizeInBits();
    1847         148 :         PreExt = N0->getOperand(0);
    1848             :         Signed = true;
    1849             :       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
    1850             :         // ZEXTLOAD / SEXTLOAD
    1851        1140 :         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
    1852           0 :           MinBits = LN0->getMemoryVT().getSizeInBits();
    1853           0 :           PreExt = N0;
    1854        1140 :         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
    1855             :           Signed = true;
    1856          96 :           MinBits = LN0->getMemoryVT().getSizeInBits();
    1857          96 :           PreExt = N0;
    1858             :         }
    1859             :       }
    1860             : 
    1861             :       // Figure out how many bits we need to preserve this constant.
    1862         244 :       unsigned ReqdBits = Signed ?
    1863         244 :         C1.getBitWidth() - C1.getNumSignBits() + 1 :
    1864             :         C1.getActiveBits();
    1865             : 
    1866             :       // Make sure we're not losing bits from the constant.
    1867       12319 :       if (MinBits > 0 &&
    1868       13616 :           MinBits < C1.getBitWidth() &&
    1869             :           MinBits >= ReqdBits) {
    1870        1206 :         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
    1871        1206 :         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
    1872             :           // Will get folded away.
    1873          92 :           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
    1874          92 :           if (MinBits == 1 && C1 == 1)
    1875             :             // Invert the condition.
    1876             :             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
    1877           0 :                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    1878         184 :           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
    1879          92 :           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
    1880             :         }
    1881             : 
    1882             :         // If truncating the setcc operands is not desirable, we can still
    1883             :         // simplify the expression in some cases:
    1884             :         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
    1885             :         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
    1886             :         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
    1887             :         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
    1888             :         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
    1889             :         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
    1890        1114 :         SDValue TopSetCC = N0->getOperand(0);
    1891        1114 :         unsigned N0Opc = N0->getOpcode();
    1892        1114 :         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
    1893         216 :         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
    1894         202 :             TopSetCC.getOpcode() == ISD::SETCC &&
    1895         404 :             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
    1896         210 :             (isConstFalseVal(N1C) ||
    1897          16 :              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
    1898             : 
    1899         398 :           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
    1900           5 :                          (!N1C->isNullValue() && Cond == ISD::SETNE);
    1901             : 
    1902             :           if (!Inverse)
    1903          99 :             return TopSetCC;
    1904             : 
    1905         200 :           ISD::CondCode InvCond = ISD::getSetCCInverse(
    1906             :               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
    1907         300 :               TopSetCC.getOperand(0).getValueType().isInteger());
    1908             :           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
    1909             :                                       TopSetCC.getOperand(1),
    1910         100 :                                       InvCond);
    1911             :         }
    1912             :       }
    1913             :     }
    1914             : 
    1915             :     // If the LHS is '(and load, const)', the RHS is 0, the test is for
    1916             :     // equality or unsigned, and all 1 bits of the const are in the same
    1917             :     // partial word, see if we can shorten the load.
    1918      304280 :     if (DCI.isBeforeLegalize() &&
    1919      100201 :         !ISD::isSignedIntSetCC(Cond) &&
    1920      103258 :         N0.getOpcode() == ISD::AND && C1 == 0 &&
    1921        1967 :         N0.getNode()->hasOneUse() &&
    1922             :         isa<LoadSDNode>(N0.getOperand(0)) &&
    1923      197913 :         N0.getOperand(0).getNode()->hasOneUse() &&
    1924             :         isa<ConstantSDNode>(N0.getOperand(1))) {
    1925             :       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
    1926             :       APInt bestMask;
    1927             :       unsigned bestWidth = 0, bestOffset = 0;
    1928         218 :       if (!Lod->isVolatile() && Lod->isUnindexed()) {
    1929         109 :         unsigned origWidth = N0.getValueSizeInBits();
    1930             :         unsigned maskWidth = origWidth;
    1931             :         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
    1932             :         // 8 bits, but have to be careful...
    1933         109 :         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
    1934           0 :           origWidth = Lod->getMemoryVT().getSizeInBits();
    1935             :         const APInt &Mask =
    1936         218 :           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
    1937         207 :         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
    1938          98 :           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
    1939         292 :           for (unsigned offset=0; offset<origWidth/width; offset++) {
    1940         184 :             if (Mask.isSubsetOf(newMask)) {
    1941         174 :               if (DAG.getDataLayout().isLittleEndian())
    1942          69 :                 bestOffset = (uint64_t)offset * (width/8);
    1943             :               else
    1944          18 :                 bestOffset = (origWidth/width - offset - 1) * (width/8);
    1945         174 :               bestMask = Mask.lshr(offset * (width/8) * 8);
    1946             :               bestWidth = width;
    1947          87 :               break;
    1948             :             }
    1949          97 :             newMask <<= width;
    1950             :           }
    1951             :         }
    1952             :       }
    1953         109 :       if (bestWidth) {
    1954          37 :         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
    1955             :         if (newVT.isRound()) {
    1956          72 :           EVT PtrType = Lod->getOperand(1).getValueType();
    1957          36 :           SDValue Ptr = Lod->getBasePtr();
    1958          36 :           if (bestOffset != 0)
    1959          17 :             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
    1960          34 :                               DAG.getConstant(bestOffset, dl, PtrType));
    1961          72 :           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
    1962             :           SDValue NewLoad = DAG.getLoad(
    1963             :               newVT, dl, Lod->getChain(), Ptr,
    1964         108 :               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
    1965             :           return DAG.getSetCC(dl, VT,
    1966             :                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
    1967          72 :                                       DAG.getConstant(bestMask.trunc(bestWidth),
    1968             :                                                       dl, newVT)),
    1969         108 :                               DAG.getConstant(0LL, dl, newVT), Cond);
    1970             :         }
    1971             :       }
    1972             :     }
    1973             : 
    1974             :     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
    1975      395754 :     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
    1976         401 :       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
    1977             : 
    1978             :       // If the comparison constant has bits in the upper part, the
    1979             :       // zero-extended value could never match.
    1980         802 :       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
    1981         401 :                                               C1.getBitWidth() - InSize))) {
    1982          27 :         switch (Cond) {
    1983           9 :         case ISD::SETUGT:
    1984             :         case ISD::SETUGE:
    1985             :         case ISD::SETEQ:
    1986           9 :           return DAG.getConstant(0, dl, VT);
    1987          12 :         case ISD::SETULT:
    1988             :         case ISD::SETULE:
    1989             :         case ISD::SETNE:
    1990          12 :           return DAG.getConstant(1, dl, VT);
    1991           1 :         case ISD::SETGT:
    1992             :         case ISD::SETGE:
    1993             :           // True if the sign bit of C1 is set.
    1994           2 :           return DAG.getConstant(C1.isNegative(), dl, VT);
    1995             :         case ISD::SETLT:
    1996             :         case ISD::SETLE:
    1997             :           // True if the sign bit of C1 isn't set.
    1998           5 :           return DAG.getConstant(C1.isNonNegative(), dl, VT);
    1999             :         default:
    2000             :           break;
    2001             :         }
    2002             :       }
    2003             : 
    2004             :       // Otherwise, we can perform the comparison with the low bits.
    2005             :       switch (Cond) {
    2006         335 :       case ISD::SETEQ:
    2007             :       case ISD::SETNE:
    2008             :       case ISD::SETUGT:
    2009             :       case ISD::SETUGE:
    2010             :       case ISD::SETULT:
    2011             :       case ISD::SETULE: {
    2012        1005 :         EVT newVT = N0.getOperand(0).getValueType();
    2013         670 :         if (DCI.isBeforeLegalizeOps() ||
    2014           6 :             (isOperationLegal(ISD::SETCC, newVT) &&
    2015             :              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
    2016             :           EVT NewSetCCVT =
    2017         626 :               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
    2018         626 :           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
    2019             : 
    2020         313 :           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
    2021         313 :                                           NewConst, Cond);
    2022         626 :           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
    2023             :         }
    2024          22 :         break;
    2025             :       }
    2026             :       default:
    2027             :         break;   // todo, be more careful with signed comparisons
    2028             :       }
    2029      197476 :     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
    2030             :                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
    2031          45 :       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
    2032          45 :       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
    2033          90 :       EVT ExtDstTy = N0.getValueType();
    2034          45 :       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
    2035             : 
    2036             :       // If the constant doesn't fit into the number of bits for the source of
    2037             :       // the sign extension, it is impossible for both sides to be equal.
    2038          45 :       if (C1.getMinSignedBits() > ExtSrcTyBits)
    2039           2 :         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
    2040             : 
    2041          43 :       SDValue ZextOp;
    2042          86 :       EVT Op0Ty = N0.getOperand(0).getValueType();
    2043           0 :       if (Op0Ty == ExtSrcTy) {
    2044           0 :         ZextOp = N0.getOperand(0);
    2045             :       } else {
    2046          43 :         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
    2047          86 :         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
    2048          86 :                               DAG.getConstant(Imm, dl, Op0Ty));
    2049             :       }
    2050          43 :       if (!DCI.isCalledByLegalizer())
    2051          43 :         DCI.AddToWorklist(ZextOp.getNode());
    2052             :       // Otherwise, make this a use of a zext.
    2053             :       return DAG.getSetCC(dl, VT, ZextOp,
    2054         129 :                           DAG.getConstant(C1 & APInt::getLowBitsSet(
    2055             :                                                               ExtDstTyBits,
    2056             :                                                               ExtSrcTyBits),
    2057             :                                           dl, ExtDstTy),
    2058          43 :                           Cond);
    2059      449445 :     } else if ((N1C->isNullValue() || N1C->isOne()) &&
    2060             :                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
    2061             :       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
    2062             :       if (N0.getOpcode() == ISD::SETCC &&
    2063      143668 :           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
    2064         102 :         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
    2065         102 :         if (TrueWhenTrue)
    2066          28 :           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
    2067             :         // Invert the condition.
    2068          74 :         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
    2069          74 :         CC = ISD::getSetCCInverse(CC,
    2070         222 :                                   N0.getOperand(0).getValueType().isInteger());
    2071         148 :         if (DCI.isBeforeLegalizeOps() ||
    2072           0 :             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
    2073         148 :           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
    2074             :       }
    2075             : 
    2076      286410 :       if ((N0.getOpcode() == ISD::XOR ||
    2077        6079 :            (N0.getOpcode() == ISD::AND &&
    2078        6079 :             N0.getOperand(0).getOpcode() == ISD::XOR &&
    2079             :             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
    2080      143469 :           isa<ConstantSDNode>(N0.getOperand(1)) &&
    2081         119 :           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
    2082             :         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
    2083             :         // can only do this if the top bits are known zero.
    2084          39 :         unsigned BitWidth = N0.getValueSizeInBits();
    2085          78 :         if (DAG.MaskedValueIsZero(N0,
    2086          78 :                                   APInt::getHighBitsSet(BitWidth,
    2087             :                                                         BitWidth-1))) {
    2088             :           // Okay, get the un-inverted input value.
    2089          25 :           SDValue Val;
    2090          50 :           if (N0.getOpcode() == ISD::XOR) {
    2091          25 :             Val = N0.getOperand(0);
    2092             :           } else {
    2093             :             assert(N0.getOpcode() == ISD::AND &&
    2094             :                     N0.getOperand(0).getOpcode() == ISD::XOR);
    2095             :             // ((X^1)&1)^1 -> X & 1
    2096           0 :             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
    2097           0 :                               N0.getOperand(0).getOperand(0),
    2098           0 :                               N0.getOperand(1));
    2099             :           }
    2100             : 
    2101             :           return DAG.getSetCC(dl, VT, Val, N1,
    2102          25 :                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    2103             :         }
    2104      286622 :       } else if (N1C->isOne() &&
    2105        4800 :                  (VT == MVT::i1 ||
    2106        9600 :                   getBooleanContents(N0->getValueType(0)) ==
    2107             :                       ZeroOrOneBooleanContent)) {
    2108        6208 :         SDValue Op0 = N0;
    2109        6208 :         if (Op0.getOpcode() == ISD::TRUNCATE)
    2110         370 :           Op0 = Op0.getOperand(0);
    2111             : 
    2112           4 :         if ((Op0.getOpcode() == ISD::XOR) &&
    2113        6215 :             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
    2114           3 :             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
    2115             :           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
    2116           3 :           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
    2117             :           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
    2118        3549 :                               Cond);
    2119             :         }
    2120             :         if (Op0.getOpcode() == ISD::AND &&
    2121        6576 :             isa<ConstantSDNode>(Op0.getOperand(1)) &&
    2122         371 :             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
    2123             :           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
    2124         361 :           if (Op0.getValueType().bitsGT(VT))
    2125          36 :             Op0 = DAG.getNode(ISD::AND, dl, VT,
    2126             :                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
    2127         108 :                           DAG.getConstant(1, dl, VT));
    2128         325 :           else if (Op0.getValueType().bitsLT(VT))
    2129           1 :             Op0 = DAG.getNode(ISD::AND, dl, VT,
    2130             :                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
    2131           3 :                         DAG.getConstant(1, dl, VT));
    2132             : 
    2133             :           return DAG.getSetCC(dl, VT, Op0,
    2134             :                               DAG.getConstant(0, dl, Op0.getValueType()),
    2135         722 :                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    2136             :         }
    2137        5844 :         if (Op0.getOpcode() == ISD::AssertZext &&
    2138             :             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
    2139             :           return DAG.getSetCC(dl, VT, Op0,
    2140             :                               DAG.getConstant(0, dl, Op0.getValueType()),
    2141        6364 :                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    2142             :       }
    2143             :     }
    2144             :   }
    2145             : 
    2146             :   // These simplifications apply to splat vectors as well.
    2147             :   // TODO: Handle more splat vector cases.
    2148      288634 :   if (auto *N1C = isConstOrConstSplat(N1)) {
    2149      198062 :     const APInt &C1 = N1C->getAPIntValue();
    2150             : 
    2151             :     APInt MinVal, MaxVal;
    2152      594186 :     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
    2153      198062 :     if (ISD::isSignedIntSetCC(Cond)) {
    2154       28988 :       MinVal = APInt::getSignedMinValue(OperandBitSize);
    2155       28988 :       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
    2156             :     } else {
    2157      367136 :       MinVal = APInt::getMinValue(OperandBitSize);
    2158      183568 :       MaxVal = APInt::getMaxValue(OperandBitSize);
    2159             :     }
    2160             : 
    2161             :     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
    2162      198062 :     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
    2163             :       // X >= MIN --> true
    2164        3684 :       if (C1 == MinVal)
    2165          52 :         return DAG.getBoolConstant(true, dl, VT, OpVT);
    2166             : 
    2167        3632 :       if (!VT.isVector()) { // TODO: Support this for vectors.
    2168             :         // X >= C0 --> X > (C0 - 1)
    2169        3585 :         APInt C = C1 - 1;
    2170        3585 :         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
    2171        3585 :         if ((DCI.isBeforeLegalizeOps() ||
    2172        7170 :              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
    2173          26 :             (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
    2174          26 :                                   isLegalICmpImmediate(C.getSExtValue())))) {
    2175             :           return DAG.getSetCC(dl, VT, N0,
    2176             :                               DAG.getConstant(C, dl, N1.getValueType()),
    2177        3572 :                               NewCC);
    2178             :         }
    2179             :       }
    2180             :     }
    2181             : 
    2182      194438 :     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
    2183             :       // X <= MAX --> true
    2184        3387 :       if (C1 == MaxVal)
    2185           4 :         return DAG.getBoolConstant(true, dl, VT, OpVT);
    2186             : 
    2187             :       // X <= C0 --> X < (C0 + 1)
    2188        3383 :       if (!VT.isVector()) { // TODO: Support this for vectors.
    2189        3306 :         APInt C = C1 + 1;
    2190        3306 :         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
    2191        3306 :         if ((DCI.isBeforeLegalizeOps() ||
    2192        6612 :              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
    2193          52 :             (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
    2194          52 :                                   isLegalICmpImmediate(C.getSExtValue())))) {
    2195             :           return DAG.getSetCC(dl, VT, N0,
    2196             :                               DAG.getConstant(C, dl, N1.getValueType()),
    2197        3280 :                               NewCC);
    2198             :         }
    2199             :       }
    2200             :     }
    2201             : 
    2202      191154 :     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
    2203       19511 :       if (C1 == MinVal)
    2204          58 :         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
    2205             : 
    2206       19453 :       if (!VT.isVector()) { // TODO: Support this for vectors.
    2207             :         // Canonicalize setlt X, Max --> setne X, Max
    2208       19143 :         if (C1 == MaxVal)
    2209          14 :           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
    2210             : 
    2211             :         // If we have setult X, 1, turn it into seteq X, 0
    2212       38258 :         if (C1 == MinVal+1)
    2213             :           return DAG.getSetCC(dl, VT, N0,
    2214             :                               DAG.getConstant(MinVal, dl, N0.getValueType()),
    2215         530 :                               ISD::SETEQ);
    2216             :       }
    2217             :     }
    2218             : 
    2219      190817 :     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
    2220       14223 :       if (C1 == MaxVal)
    2221           8 :         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
    2222             : 
    2223       14215 :       if (!VT.isVector()) { // TODO: Support this for vectors.
    2224             :         // Canonicalize setgt X, Min --> setne X, Min
    2225       14058 :         if (C1 == MinVal)
    2226         165 :           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
    2227             : 
    2228             :         // If we have setugt X, Max-1, turn it into seteq X, Max
    2229       41679 :         if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
    2230             :           return DAG.getSetCC(dl, VT, N0,
    2231             :                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
    2232           4 :                               ISD::SETEQ);
    2233             :       }
    2234             :     }
    2235             : 
    2236             :     // If we have "setcc X, C0", check to see if we can shrink the immediate
    2237             :     // by changing cc.
    2238      190642 :     if (!VT.isVector()) { // TODO: Support this for vectors.
    2239             :       // SETUGT X, SINTMAX  -> SETLT X, 0
    2240      381240 :       if (Cond == ISD::SETUGT &&
    2241      381240 :           C1 == APInt::getSignedMaxValue(OperandBitSize))
    2242             :         return DAG.getSetCC(dl, VT, N0,
    2243             :                             DAG.getConstant(0, dl, N1.getValueType()),
    2244           0 :                             ISD::SETLT);
    2245             : 
    2246             :       // SETULT X, SINTMIN  -> SETGT X, -1
    2247      385180 :       if (Cond == ISD::SETULT &&
    2248      385106 :           C1 == APInt::getSignedMinValue(OperandBitSize)) {
    2249             :         SDValue ConstMinusOne =
    2250         148 :             DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
    2251          74 :                             N1.getValueType());
    2252          74 :         return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
    2253             :       }
    2254             :     }
    2255             :   }
    2256             : 
    2257             :   // Back to non-vector simplifications.
    2258             :   // TODO: Can we do these for vector splats?
    2259             :   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
    2260      186344 :     const APInt &C1 = N1C->getAPIntValue();
    2261             : 
    2262             :     // Fold bit comparisons when we can.
    2263      186344 :     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    2264      153624 :         (VT == N0.getValueType() ||
    2265      363723 :          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
    2266             :         N0.getOpcode() == ISD::AND) {
    2267        4938 :       auto &DL = DAG.getDataLayout();
    2268        4938 :       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
    2269             :         EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
    2270        5368 :                                        !DCI.isBeforeLegalize());
    2271        2684 :         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
    2272             :           // Perform the xform if the AND RHS is a single bit.
    2273        1182 :           if (AndRHS->getAPIntValue().isPowerOf2()) {
    2274             :             return DAG.getNode(ISD::TRUNCATE, dl, VT,
    2275             :                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
    2276             :                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
    2277         486 :                                    ShiftTy)));
    2278             :           }
    2279        6027 :         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
    2280             :           // (X & 8) == 8  -->  (X & 8) >> 3
    2281             :           // Perform the xform if C1 is a single bit.
    2282          32 :           if (C1.isPowerOf2()) {
    2283             :             return DAG.getNode(ISD::TRUNCATE, dl, VT,
    2284             :                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
    2285             :                                       DAG.getConstant(C1.logBase2(), dl,
    2286           0 :                                                       ShiftTy)));
    2287             :           }
    2288             :         }
    2289             :       }
    2290             :     }
    2291             : 
    2292      372180 :     if (C1.getMinSignedBits() <= 64 &&
    2293      372158 :         !isLegalICmpImmediate(C1.getSExtValue())) {
    2294             :       // (X & -256) == 256 -> (X >> 8) == 1
    2295         360 :       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    2296        1174 :           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
    2297          12 :         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
    2298          12 :           const APInt &AndRHSC = AndRHS->getAPIntValue();
    2299          68 :           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
    2300           8 :             unsigned ShiftBits = AndRHSC.countTrailingZeros();
    2301           8 :             auto &DL = DAG.getDataLayout();
    2302             :             EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
    2303          16 :                                            !DCI.isBeforeLegalize());
    2304          16 :             EVT CmpTy = N0.getValueType();
    2305           8 :             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
    2306             :                                         DAG.getConstant(ShiftBits, dl,
    2307          16 :                                                         ShiftTy));
    2308          16 :             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
    2309           8 :             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
    2310             :           }
    2311             :         }
    2312        1116 :       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
    2313        1116 :                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
    2314         375 :         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
    2315             :         // X <  0x100000000 -> (X >> 32) <  1
    2316             :         // X >= 0x100000000 -> (X >> 32) >= 1
    2317             :         // X <= 0x0ffffffff -> (X >> 32) <  1
    2318             :         // X >  0x0ffffffff -> (X >> 32) >= 1
    2319             :         unsigned ShiftBits;
    2320             :         APInt NewC = C1;
    2321             :         ISD::CondCode NewCond = Cond;
    2322         375 :         if (AdjOne) {
    2323             :           ShiftBits = C1.countTrailingOnes();
    2324         181 :           NewC = NewC + 1;
    2325         181 :           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
    2326             :         } else {
    2327         194 :           ShiftBits = C1.countTrailingZeros();
    2328             :         }
    2329             :         NewC.lshrInPlace(ShiftBits);
    2330         603 :         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
    2331         456 :           isLegalICmpImmediate(NewC.getSExtValue())) {
    2332         210 :           auto &DL = DAG.getDataLayout();
    2333             :           EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
    2334         420 :                                          !DCI.isBeforeLegalize());
    2335         420 :           EVT CmpTy = N0.getValueType();
    2336             :           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
    2337         210 :                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
    2338         210 :           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
    2339         210 :           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
    2340             :         }
    2341             :       }
    2342             :     }
    2343             :   }
    2344             : 
    2345      280679 :   if (isa<ConstantFPSDNode>(N0.getNode())) {
    2346             :     // Constant fold or commute setcc.
    2347          56 :     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
    2348          56 :     if (O.getNode()) return O;
    2349             :   } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
    2350             :     // If the RHS of an FP comparison is a constant, simplify it away in
    2351             :     // some cases.
    2352        9244 :     if (CFP->getValueAPF().isNaN()) {
    2353             :       // If an operand is known to be a nan, we can fold it.
    2354           0 :       switch (ISD::getUnorderedFlavor(Cond)) {
    2355           0 :       default: llvm_unreachable("Unknown flavor!");
    2356           0 :       case 0:  // Known false.
    2357           0 :         return DAG.getBoolConstant(false, dl, VT, OpVT);
    2358           0 :       case 1:  // Known true.
    2359           0 :         return DAG.getBoolConstant(true, dl, VT, OpVT);
    2360           0 :       case 2:  // Undefined.
    2361           0 :         return DAG.getUNDEF(VT);
    2362             :       }
    2363             :     }
    2364             : 
    2365             :     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
    2366             :     // constant if knowing that the operand is non-nan is enough.  We prefer to
    2367             :     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
    2368             :     // materialize 0.0.
    2369        4622 :     if (Cond == ISD::SETO || Cond == ISD::SETUO)
    2370         105 :       return DAG.getSetCC(dl, VT, N0, N0, Cond);
    2371             : 
    2372             :     // setcc (fneg x), C -> setcc swap(pred) x, -C
    2373        4517 :     if (N0.getOpcode() == ISD::FNEG) {
    2374          61 :       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
    2375         122 :       if (DCI.isBeforeLegalizeOps() ||
    2376             :           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
    2377         122 :         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
    2378         122 :         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
    2379             :       }
    2380             :     }
    2381             : 
    2382             :     // If the condition is not legal, see if we can find an equivalent one
    2383             :     // which is legal.
    2384             :     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
    2385             :       // If the comparison was an awkward floating-point == or != and one of
    2386             :       // the comparison operands is infinity or negative infinity, convert the
    2387             :       // condition to a less-awkward <= or >=.
    2388         420 :       if (CFP->getValueAPF().isInfinity()) {
    2389          14 :         if (CFP->getValueAPF().isNegative()) {
    2390           4 :           if (Cond == ISD::SETOEQ &&
    2391             :               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
    2392           2 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
    2393           2 :           if (Cond == ISD::SETUEQ &&
    2394             :               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
    2395           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
    2396           2 :           if (Cond == ISD::SETUNE &&
    2397             :               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
    2398           2 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
    2399           0 :           if (Cond == ISD::SETONE &&
    2400             :               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
    2401           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
    2402             :         } else {
    2403          10 :           if (Cond == ISD::SETOEQ &&
    2404             :               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
    2405           8 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
    2406           2 :           if (Cond == ISD::SETUEQ &&
    2407             :               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
    2408           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
    2409           2 :           if (Cond == ISD::SETUNE &&
    2410             :               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
    2411           2 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
    2412           0 :           if (Cond == ISD::SETONE &&
    2413             :               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
    2414           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
    2415             :         }
    2416             :       }
    2417             :     }
    2418             :   }
    2419             : 
    2420             :   if (N0 == N1) {
    2421             :     // The sext(setcc()) => setcc() optimization relies on the appropriate
    2422             :     // constant being emitted.
    2423             : 
    2424             :     bool EqTrue = ISD::isTrueWhenEqual(Cond);
    2425             : 
    2426             :     // We can always fold X == X for integer setcc's.
    2427         589 :     if (N0.getValueType().isInteger())
    2428          90 :       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
    2429             : 
    2430             :     unsigned UOF = ISD::getUnorderedFlavor(Cond);
    2431         499 :     if (UOF == 2)   // FP operators that are undefined on NaNs.
    2432           0 :       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
    2433         499 :     if (UOF == unsigned(EqTrue))
    2434          19 :       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
    2435             :     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
    2436             :     // if it is not already.
    2437         480 :     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
    2438         597 :     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
    2439             :           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
    2440          45 :       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
    2441             :   }
    2442             : 
    2443      472028 :   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    2444      472307 :       N0.getValueType().isInteger()) {
    2445      191405 :     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
    2446             :         N0.getOpcode() == ISD::XOR) {
    2447             :       // Simplify (X+Y) == (X+Z) -->  Y == Z
    2448        5066 :       if (N0.getOpcode() == N1.getOpcode()) {
    2449             :         if (N0.getOperand(0) == N1.getOperand(0))
    2450           0 :           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
    2451             :         if (N0.getOperand(1) == N1.getOperand(1))
    2452           0 :           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
    2453          20 :         if (isCommutativeBinOp(N0.getOpcode())) {
    2454             :           // If X op Y == Y op X, try other combinations.
    2455          18 :           if (N0.getOperand(0) == N1.getOperand(1))
    2456             :             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
    2457           0 :                                 Cond);
    2458             :           if (N0.getOperand(1) == N1.getOperand(0))
    2459             :             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
    2460           0 :                                 Cond);
    2461             :         }
    2462             :       }
    2463             : 
    2464             :       // If RHS is a legal immediate value for a compare instruction, we need
    2465             :       // to be careful about increasing register pressure needlessly.
    2466             :       bool LegalRHSImm = false;
    2467             : 
    2468             :       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
    2469        4044 :         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
    2470             :           // Turn (X+C1) == C2 --> X == C2-C1
    2471        2641 :           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
    2472          58 :             return DAG.getSetCC(dl, VT, N0.getOperand(0),
    2473         232 :                                 DAG.getConstant(RHSC->getAPIntValue()-
    2474             :                                                 LHSR->getAPIntValue(),
    2475         174 :                                 dl, N0.getValueType()), Cond);
    2476             :           }
    2477             : 
    2478             :           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
    2479        2583 :           if (N0.getOpcode() == ISD::XOR)
    2480             :             // If we know that all of the inverted bits are zero, don't bother
    2481             :             // performing the inversion.
    2482         480 :             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
    2483             :               return
    2484          21 :                 DAG.getSetCC(dl, VT, N0.getOperand(0),
    2485          84 :                              DAG.getConstant(LHSR->getAPIntValue() ^
    2486             :                                                RHSC->getAPIntValue(),
    2487             :                                              dl, N0.getValueType()),
    2488          63 :                              Cond);
    2489             :         }
    2490             : 
    2491             :         // Turn (C1-X) == C2 --> X == C1-C2
    2492        3965 :         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
    2493          14 :           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
    2494             :             return
    2495           0 :               DAG.getSetCC(dl, VT, N0.getOperand(1),
    2496           0 :                            DAG.getConstant(SUBC->getAPIntValue() -
    2497             :                                              RHSC->getAPIntValue(),
    2498             :                                            dl, N0.getValueType()),
    2499           0 :                            Cond);
    2500             :           }
    2501             :         }
    2502             : 
    2503             :         // Could RHSC fold directly into a compare?
    2504        7930 :         if (RHSC->getValueType(0).getSizeInBits() <= 64)
    2505        7930 :           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
    2506             :       }
    2507             : 
    2508             :       // Simplify (X+Z) == X -->  Z == 0
    2509             :       // Don't do this if X is an immediate that can fold into a cmp
    2510             :       // instruction and X+Z has other uses. It could be an induction variable
    2511             :       // chain, and the transform would increase register pressure.
    2512        3965 :       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
    2513        1530 :         if (N0.getOperand(0) == N1)
    2514          24 :           return DAG.getSetCC(dl, VT, N0.getOperand(1),
    2515          72 :                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
    2516             :         if (N0.getOperand(1) == N1) {
    2517          28 :           if (isCommutativeBinOp(N0.getOpcode()))
    2518           2 :             return DAG.getSetCC(dl, VT, N0.getOperand(0),
    2519             :                                 DAG.getConstant(0, dl, N0.getValueType()),
    2520           6 :                                 Cond);
    2521          12 :           if (N0.getNode()->hasOneUse()) {
    2522             :             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
    2523           2 :             auto &DL = DAG.getDataLayout();
    2524             :             // (Z-X) == X  --> Z == X<<1
    2525             :             SDValue SH = DAG.getNode(
    2526             :                 ISD::SHL, dl, N1.getValueType(), N1,
    2527             :                 DAG.getConstant(1, dl,
    2528             :                                 getShiftAmountTy(N1.getValueType(), DL,
    2529           6 :                                                  !DCI.isBeforeLegalize())));
    2530           2 :             if (!DCI.isCalledByLegalizer())
    2531           2 :               DCI.AddToWorklist(SH.getNode());
    2532           4 :             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
    2533             :           }
    2534             :         }
    2535             :       }
    2536             :     }
    2537             : 
    2538      191298 :     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
    2539             :         N1.getOpcode() == ISD::XOR) {
    2540             :       // Simplify  X == (X+Z) -->  Z == 0
    2541             :       if (N1.getOperand(0) == N0)
    2542             :         return DAG.getSetCC(dl, VT, N1.getOperand(1),
    2543           2 :                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
    2544             :       if (N1.getOperand(1) == N0) {
    2545          15 :         if (isCommutativeBinOp(N1.getOpcode()))
    2546             :           return DAG.getSetCC(dl, VT, N1.getOperand(0),
    2547           0 :                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
    2548             :         if (N1.getNode()->hasOneUse()) {
    2549             :           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
    2550           3 :           auto &DL = DAG.getDataLayout();
    2551             :           // X == (Z-X)  --> X<<1 == Z
    2552             :           SDValue SH = DAG.getNode(
    2553             :               ISD::SHL, dl, N1.getValueType(), N0,
    2554             :               DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL,
    2555           9 :                                                       !DCI.isBeforeLegalize())));
    2556           3 :           if (!DCI.isCalledByLegalizer())
    2557           3 :             DCI.AddToWorklist(SH.getNode());
    2558           3 :           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
    2559             :         }
    2560             :       }
    2561             :     }
    2562             : 
    2563      191294 :     if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
    2564         214 :       return V;
    2565             :   }
    2566             : 
    2567             :   // Fold away ALL boolean setcc's.
    2568      280019 :   SDValue Temp;
    2569      561833 :   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
    2570        1044 :     EVT OpVT = N0.getValueType();
    2571         522 :     switch (Cond) {
    2572           0 :     default: llvm_unreachable("Unknown integer setcc!");
    2573             :     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
    2574          39 :       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
    2575          39 :       N0 = DAG.getNOT(dl, Temp, OpVT);
    2576          39 :       if (!DCI.isCalledByLegalizer())
    2577          39 :         DCI.AddToWorklist(Temp.getNode());
    2578             :       break;
    2579             :     case ISD::SETNE:  // X != Y   -->  (X^Y)
    2580         432 :       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
    2581         432 :       break;
    2582          15 :     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
    2583             :     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
    2584          15 :       Temp = DAG.getNOT(dl, N0, OpVT);
    2585          15 :       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
    2586          15 :       if (!DCI.isCalledByLegalizer())
    2587          15 :         DCI.AddToWorklist(Temp.getNode());
    2588             :       break;
    2589          18 :     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
    2590             :     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
    2591          18 :       Temp = DAG.getNOT(dl, N1, OpVT);
    2592          18 :       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
    2593          18 :       if (!DCI.isCalledByLegalizer())
    2594          18 :         DCI.AddToWorklist(Temp.getNode());
    2595             :       break;
    2596           9 :     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
    2597             :     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
    2598           9 :       Temp = DAG.getNOT(dl, N0, OpVT);
    2599           9 :       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
    2600           9 :       if (!DCI.isCalledByLegalizer())
    2601           9 :         DCI.AddToWorklist(Temp.getNode());
    2602             :       break;
    2603           9 :     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
    2604             :     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
    2605           9 :       Temp = DAG.getNOT(dl, N1, OpVT);
    2606           9 :       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
    2607           9 :       break;
    2608             :     }
    2609        1044 :     if (VT.getScalarType() != MVT::i1) {
    2610           3 :       if (!DCI.isCalledByLegalizer())
    2611           3 :         DCI.AddToWorklist(N0.getNode());
    2612             :       // FIXME: If running after legalize, we probably can't do this.
    2613           3 :       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
    2614           3 :       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
    2615             :     }
    2616         522 :     return N0;
    2617             :   }
    2618             : 
    2619             :   // Could not fold it.
    2620      279497 :   return SDValue();
    2621             : }
    2622             : 
    2623             : /// Returns true (and the GlobalValue and the offset) if the node is a
    2624             : /// GlobalAddress + offset.
    2625    20000126 : bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
    2626             :                                     int64_t &Offset) const {
    2627             :   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
    2628     2315584 :     GA = GASD->getGlobal();
    2629     2315584 :     Offset += GASD->getOffset();
    2630     2315584 :     return true;
    2631             :   }
    2632             : 
    2633    17684542 :   if (N->getOpcode() == ISD::ADD) {
    2634     8164513 :     SDValue N1 = N->getOperand(0);
    2635     8164513 :     SDValue N2 = N->getOperand(1);
    2636     8164513 :     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
    2637             :       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
    2638     1930814 :         Offset += V->getSExtValue();
    2639      965407 :         return true;
    2640             :       }
    2641     6658883 :     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
    2642             :       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
    2643           0 :         Offset += V->getSExtValue();
    2644           0 :         return true;
    2645             :       }
    2646             :     }
    2647             :   }
    2648             : 
    2649             :   return false;
    2650             : }
    2651             : 
    2652       14967 : SDValue TargetLowering::PerformDAGCombine(SDNode *N,
    2653             :                                           DAGCombinerInfo &DCI) const {
    2654             :   // Default implementation: no optimization.
    2655       14967 :   return SDValue();
    2656             : }
    2657             : 
    2658             : //===----------------------------------------------------------------------===//
    2659             : //  Inline Assembler Implementation Methods
    2660             : //===----------------------------------------------------------------------===//
    2661             : 
    2662             : TargetLowering::ConstraintType
    2663      465424 : TargetLowering::getConstraintType(StringRef Constraint) const {
    2664      465424 :   unsigned S = Constraint.size();
    2665             : 
    2666      465424 :   if (S == 1) {
    2667       28492 :     switch (Constraint[0]) {
    2668             :     default: break;
    2669             :     case 'r': return C_RegisterClass;
    2670             :     case 'm':    // memory
    2671             :     case 'o':    // offsetable
    2672             :     case 'V':    // not offsetable
    2673             :       return C_Memory;
    2674             :     case 'i':    // Simple Integer or Relocatable Constant
    2675             :     case 'n':    // Simple Integer
    2676             :     case 'E':    // Floating Point Constant
    2677             :     case 'F':    // Floating Point Constant
    2678             :     case 's':    // Relocatable Constant
    2679             :     case 'p':    // Address.
    2680             :     case 'X':    // Allow ANY value.
    2681             :     case 'I':    // Target registers.
    2682             :     case 'J':
    2683             :     case 'K':
    2684             :     case 'L':
    2685             :     case 'M':
    2686             :     case 'N':
    2687             :     case 'O':
    2688             :     case 'P':
    2689             :     case '<':
    2690             :     case '>':
    2691             :       return C_Other;
    2692             :     }
    2693             :   }
    2694             : 
    2695     1311465 :   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
    2696      436668 :     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
    2697             :       return C_Memory;
    2698             :     return C_Register;
    2699             :   }
    2700             :   return C_Unknown;
    2701             : }
    2702             : 
    2703             : /// Try to replace an X constraint, which matches anything, with another that
    2704             : /// has more specific requirements based on the type of the corresponding
    2705             : /// operand.
    2706         117 : const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
    2707         117 :   if (ConstraintVT.isInteger())
    2708             :     return "r";
    2709          39 :   if (ConstraintVT.isFloatingPoint())
    2710             :     return "f";      // works for many targets
    2711           3 :   return nullptr;
    2712             : }
    2713             : 
    2714             : /// Lower the specified operand into the Ops vector.
    2715             : /// If it is invalid, don't add anything to Ops.
    2716         217 : void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
    2717             :                                                   std::string &Constraint,
    2718             :                                                   std::vector<SDValue> &Ops,
    2719             :                                                   SelectionDAG &DAG) const {
    2720             : 
    2721         217 :   if (Constraint.length() > 1) return;
    2722             : 
    2723         217 :   char ConstraintLetter = Constraint[0];
    2724         217 :   switch (ConstraintLetter) {
    2725             :   default: break;
    2726          24 :   case 'X':     // Allows any operand; labels (basic block) use this.
    2727          48 :     if (Op.getOpcode() == ISD::BasicBlock) {
    2728           2 :       Ops.push_back(Op);
    2729           2 :       return;
    2730             :     }
    2731             :     LLVM_FALLTHROUGH;
    2732             :   case 'i':    // Simple Integer or Relocatable Constant
    2733             :   case 'n':    // Simple Integer
    2734             :   case 's': {  // Relocatable Constant
    2735             :     // These operands are interested in values of the form (GV+C), where C may
    2736             :     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
    2737             :     // is possible and fine if either GV or C are missing.
    2738             :     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
    2739             :     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
    2740             : 
    2741             :     // If we have "(add GV, C)", pull out GV/C
    2742         161 :     if (Op.getOpcode() == ISD::ADD) {
    2743             :       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    2744             :       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
    2745           4 :       if (!C || !GA) {
    2746             :         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
    2747             :         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
    2748             :       }
    2749           4 :       if (!C || !GA) {
    2750             :         C = nullptr;
    2751             :         GA = nullptr;
    2752             :       }
    2753             :     }
    2754             : 
    2755             :     // If we find a valid operand, map to the TargetXXX version so that the
    2756             :     // value itself doesn't get selected.
    2757         161 :     if (GA) {   // Either &GV   or   &GV+C
    2758          20 :       if (ConstraintLetter != 'n') {
    2759          19 :         int64_t Offs = GA->getOffset();
    2760          23 :         if (C) Offs += C->getZExtValue();
    2761          38 :         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
    2762          53 :                                                  C ? SDLoc(C) : SDLoc(),
    2763          38 :                                                  Op.getValueType(), Offs));
    2764             :       }
    2765             :       return;
    2766             :     }
    2767         141 :     if (C) {   // just C, no GV.
    2768             :       // Simple constants are not allowed for 's'.
    2769         123 :       if (ConstraintLetter != 's') {
    2770             :         // gcc prints these as sign extended.  Sign extend value to 64 bits
    2771             :         // now; without this it would get ZExt'd later in
    2772             :         // ScheduleDAGSDNodes::EmitNode, which is very generic.
    2773         369 :         Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
    2774         246 :                                             SDLoc(C), MVT::i64));
    2775             :       }
    2776             :       return;
    2777             :     }
    2778             :     break;
    2779             :   }
    2780             :   }
    2781             : }
    2782             : 
    2783             : std::pair<unsigned, const TargetRegisterClass *>
    2784       99914 : TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
    2785             :                                              StringRef Constraint,
    2786             :                                              MVT VT) const {
    2787      199724 :   if (Constraint.empty() || Constraint[0] != '{')
    2788         167 :     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
    2789             :   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
    2790             : 
    2791             :   // Remove the braces from around the name.
    2792       99747 :   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
    2793             : 
    2794             :   std::pair<unsigned, const TargetRegisterClass*> R =
    2795             :     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
    2796             : 
    2797             :   // Figure out which register class contains this reg.
    2798    16216857 :   for (const TargetRegisterClass *RC : RI->regclasses()) {
    2799             :     // If none of the value types for this register class are valid, we
    2800             :     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
    2801     8059381 :     if (!isLegalRC(*RI, *RC))
    2802     1934232 :       continue;
    2803             : 
    2804    75374861 :     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
    2805    75374861 :          I != E; ++I) {
    2806    69250538 :       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
    2807             :         std::pair<unsigned, const TargetRegisterClass*> S =
    2808      493674 :           std::make_pair(*I, RC);
    2809             : 
    2810             :         // If this register class has the requested value type, return it,
    2811             :         // otherwise keep searching and return the first class found
    2812             :         // if no other is found which explicitly has the requested type.
    2813      493674 :         if (RI->isTypeLegalForClass(*RC, VT))
    2814         826 :           return S;
    2815      492848 :         if (!R.second)
    2816             :           R = S;
    2817             :       }
    2818             :     }
    2819             :   }
    2820             : 
    2821       98921 :   return R;
    2822             : }
    2823             : 
    2824             : //===----------------------------------------------------------------------===//
    2825             : // Constraint Selection.
    2826             : 
    2827             : /// Return true of this is an input operand that is a matching constraint like
    2828             : /// "4".
    2829       10344 : bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
    2830             :   assert(!ConstraintCode.empty() && "No known constraint!");
    2831       10344 :   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
    2832             : }
    2833             : 
    2834             : /// If this is an input matching constraint, this method returns the output
    2835             : /// operand it matches.
    2836         523 : unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
    2837             :   assert(!ConstraintCode.empty() && "No known constraint!");
    2838         523 :   return atoi(ConstraintCode.c_str());
    2839             : }
    2840             : 
    2841             : /// Split up the constraint string from the inline assembly value into the
    2842             : /// specific constraints and their prefixes, and also tie in the associated
    2843             : /// operand values.
    2844             : /// If this returns an empty vector, and if the constraint string itself
    2845             : /// isn't empty, there was an error parsing.
    2846             : TargetLowering::AsmOperandInfoVector
    2847       33352 : TargetLowering::ParseConstraints(const DataLayout &DL,
    2848             :                                  const TargetRegisterInfo *TRI,
    2849             :                                  ImmutableCallSite CS) const {
    2850             :   /// Information about all of the constraints.
    2851             :   AsmOperandInfoVector ConstraintOperands;
    2852             :   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
    2853             :   unsigned maCount = 0; // Largest number of multiple alternative constraints.
    2854             : 
    2855             :   // Do a prepass over the constraints, canonicalizing them, and building up the
    2856             :   // ConstraintOperands list.
    2857             :   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
    2858             :   unsigned ResNo = 0;   // ResNo - The result number of the next output.
    2859             : 
    2860      261382 :   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
    2861      194678 :     ConstraintOperands.emplace_back(std::move(CI));
    2862             :     AsmOperandInfo &OpInfo = ConstraintOperands.back();
    2863             : 
    2864             :     // Update multiple alternative constraint count.
    2865      389356 :     if (OpInfo.multipleAlternatives.size() > maCount)
    2866         417 :       maCount = OpInfo.multipleAlternatives.size();
    2867             : 
    2868      194678 :     OpInfo.ConstraintVT = MVT::Other;
    2869             : 
    2870             :     // Compute the value type for each operand.
    2871      194678 :     switch (OpInfo.Type) {
    2872       12143 :     case InlineAsm::isOutput:
    2873             :       // Indirect outputs just consume an argument.
    2874       12143 :       if (OpInfo.isIndirect) {
    2875        1462 :         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
    2876         731 :         break;
    2877             :       }
    2878             : 
    2879             :       // The return value of the call is this value.  As such, there is no
    2880             :       // corresponding argument.
    2881             :       assert(!CS.getType()->isVoidTy() &&
    2882             :              "Bad inline asm!");
    2883             :       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
    2884        1728 :         OpInfo.ConstraintVT =
    2885        1728 :             getSimpleValueType(DL, STy->getElementType(ResNo));
    2886             :       } else {
    2887             :         assert(ResNo == 0 && "Asm only has one result!");
    2888       19368 :         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
    2889             :       }
    2890       11412 :       ++ResNo;
    2891       11412 :       break;
    2892       31069 :     case InlineAsm::isInput:
    2893       62138 :       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
    2894       31069 :       break;
    2895             :     case InlineAsm::isClobber:
    2896             :       // Nothing to do.
    2897             :       break;
    2898             :     }
    2899             : 
    2900      194678 :     if (OpInfo.CallOperandVal) {
    2901       31800 :       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
    2902       31800 :       if (OpInfo.isIndirect) {
    2903             :         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
    2904             :         if (!PtrTy)
    2905           0 :           report_fatal_error("Indirect operand for inline asm not a pointer!");
    2906        9176 :         OpTy = PtrTy->getElementType();
    2907             :       }
    2908             : 
    2909             :       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
    2910             :       if (StructType *STy = dyn_cast<StructType>(OpTy))
    2911          42 :         if (STy->getNumElements() == 1)
    2912          26 :           OpTy = STy->getElementType(0);
    2913             : 
    2914             :       // If OpTy is not a single value, it may be a struct/union that we
    2915             :       // can tile with integers.
    2916       31800 :       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
    2917          46 :         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
    2918          46 :         switch (BitSize) {
    2919             :         default: break;
    2920          23 :         case 1:
    2921             :         case 8:
    2922             :         case 16:
    2923             :         case 32:
    2924             :         case 64:
    2925             :         case 128:
    2926          23 :           OpInfo.ConstraintVT =
    2927          23 :             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
    2928          23 :           break;
    2929             :         }
    2930             :       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
    2931             :         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
    2932        1190 :         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
    2933             :       } else {
    2934       30564 :         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
    2935             :       }
    2936             :     }
    2937             :   }
    2938             : 
    2939             :   // If we have multiple alternative constraints, select the best alternative.
    2940       33352 :   if (!ConstraintOperands.empty()) {
    2941       29946 :     if (maCount) {
    2942             :       unsigned bestMAIndex = 0;
    2943             :       int bestWeight = -1;
    2944             :       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
    2945             :       int weight = -1;
    2946             :       unsigned maIndex;
    2947             :       // Compute the sums of the weights for each alternative, keeping track
    2948             :       // of the best (highest weight) one so far.
    2949        2193 :       for (maIndex = 0; maIndex < maCount; ++maIndex) {
    2950             :         int weightSum = 0;
    2951        4101 :         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
    2952        3213 :             cIndex != eIndex; ++cIndex) {
    2953        2502 :           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
    2954        2502 :           if (OpInfo.Type == InlineAsm::isClobber)
    2955         825 :             continue;
    2956             : 
    2957             :           // If this is an output operand with a matching input operand,
    2958             :           // look up the matching input. If their types mismatch, e.g. one
    2959             :           // is an integer, the other is floating point, or their sizes are
    2960             :           // different, flag it as an maCantMatch.
    2961        1677 :           if (OpInfo.hasMatchingInput()) {
    2962           0 :             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
    2963           0 :             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
    2964             :               if ((OpInfo.ConstraintVT.isInteger() !=
    2965           0 :                    Input.ConstraintVT.isInteger()) ||
    2966           0 :                   (OpInfo.ConstraintVT.getSizeInBits() !=
    2967           0 :                    Input.ConstraintVT.getSizeInBits())) {
    2968             :                 weightSum = -1;  // Can't match.
    2969             :                 break;
    2970             :               }
    2971             :             }
    2972             :           }
    2973        1677 :           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
    2974        1677 :           if (weight == -1) {
    2975             :             weightSum = -1;
    2976             :             break;
    2977             :           }
    2978        1500 :           weightSum += weight;
    2979             :         }
    2980             :         // Update best.
    2981         888 :         if (weightSum > bestWeight) {
    2982             :           bestWeight = weightSum;
    2983             :           bestMAIndex = maIndex;
    2984             :         }
    2985             :       }
    2986             : 
    2987             :       // Now select chosen alternative in each constraint.
    2988        2154 :       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
    2989        1737 :           cIndex != eIndex; ++cIndex) {
    2990        1320 :         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
    2991        1320 :         if (cInfo.Type == InlineAsm::isClobber)
    2992         489 :           continue;
    2993         831 :         cInfo.selectAlternative(bestMAIndex);
    2994             :       }
    2995             :     }
    2996             :   }
    2997             : 
    2998             :   // Check and hook up tied operands, choose constraint code to use.
    2999      261382 :   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
    3000      228030 :       cIndex != eIndex; ++cIndex) {
    3001      194678 :     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
    3002             : 
    3003             :     // If this is an output operand with a matching input operand, look up the
    3004             :     // matching input. If their types mismatch, e.g. one is an integer, the
    3005             :     // other is floating point, or their sizes are different, flag it as an
    3006             :     // error.
    3007      194678 :     if (OpInfo.hasMatchingInput()) {
    3008         813 :       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
    3009             : 
    3010         813 :       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
    3011             :         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
    3012             :             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
    3013          78 :                                          OpInfo.ConstraintVT);
    3014             :         std::pair<unsigned, const TargetRegisterClass *> InputRC =
    3015             :             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
    3016          78 :                                          Input.ConstraintVT);
    3017             :         if ((OpInfo.ConstraintVT.isInteger() !=
    3018          78 :              Input.ConstraintVT.isInteger()) ||
    3019          39 :             (MatchRC.second != InputRC.second)) {
    3020           0 :           report_fatal_error("Unsupported asm: input constraint"
    3021             :                              " with a matching output constraint of"
    3022             :                              " incompatible type!");
    3023             :         }
    3024             :       }
    3025             :     }
    3026             :   }
    3027             : 
    3028       33352 :   return ConstraintOperands;
    3029             : }
    3030             : 
    3031             : /// Return an integer indicating how general CT is.
    3032             : static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
    3033      145800 :   switch (CT) {
    3034             :   case TargetLowering::C_Other:
    3035             :   case TargetLowering::C_Unknown:
    3036             :     return 0;
    3037      144374 :   case TargetLowering::C_Register:
    3038             :     return 1;
    3039         556 :   case TargetLowering::C_RegisterClass:
    3040             :     return 2;
    3041         240 :   case TargetLowering::C_Memory:
    3042             :     return 3;
    3043             :   }
    3044           0 :   llvm_unreachable("Invalid constraint type");
    3045             : }
    3046             : 
    3047             : /// Examine constraint type and operand type and determine a weight value.
    3048             : /// This object must already have been set up with the operand type
    3049             : /// and the current alternative constraint selected.
    3050             : TargetLowering::ConstraintWeight
    3051        1677 :   TargetLowering::getMultipleConstraintMatchWeight(
    3052             :     AsmOperandInfo &info, int maIndex) const {
    3053             :   InlineAsm::ConstraintCodeVector *rCodes;
    3054        3354 :   if (maIndex >= (int)info.multipleAlternatives.size())
    3055           3 :     rCodes = &info.Codes;
    3056             :   else
    3057        3348 :     rCodes = &info.multipleAlternatives[maIndex].Codes;
    3058             :   ConstraintWeight BestWeight = CW_Invalid;
    3059             : 
    3060             :   // Loop over the options, keeping track of the most general one.
    3061        5244 :   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
    3062             :     ConstraintWeight weight =
    3063        3780 :       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
    3064        1890 :     if (weight > BestWeight)
    3065             :       BestWeight = weight;
    3066             :   }
    3067             : 
    3068        1677 :   return BestWeight;
    3069             : }
    3070             : 
    3071             : /// Examine constraint type and operand type and determine a weight value.
    3072             : /// This object must already have been set up with the operand type
    3073             : /// and the current alternative constraint selected.
    3074             : TargetLowering::ConstraintWeight
    3075        1266 :   TargetLowering::getSingleConstraintMatchWeight(
    3076             :     AsmOperandInfo &info, const char *constraint) const {
    3077             :   ConstraintWeight weight = CW_Invalid;
    3078        1266 :   Value *CallOperandVal = info.CallOperandVal;
    3079             :     // If we don't have a value, we can't do a match,
    3080             :     // but allow it at the lowest weight.
    3081        1266 :   if (!CallOperandVal)
    3082             :     return CW_Default;
    3083             :   // Look at the constraint type.
    3084        1176 :   switch (*constraint) {
    3085         111 :     case 'i': // immediate integer.
    3086             :     case 'n': // immediate integer with a known value.
    3087         111 :       if (isa<ConstantInt>(CallOperandVal))
    3088             :         weight = CW_Constant;
    3089             :       break;
    3090           0 :     case 's': // non-explicit intregal immediate.
    3091             :       if (isa<GlobalValue>(CallOperandVal))
    3092             :         weight = CW_Constant;
    3093             :       break;
    3094           0 :     case 'E': // immediate float if host format.
    3095             :     case 'F': // immediate float.
    3096           0 :       if (isa<ConstantFP>(CallOperandVal))
    3097             :         weight = CW_Constant;
    3098             :       break;
    3099             :     case '<': // memory operand with autodecrement.
    3100             :     case '>': // memory operand with autoincrement.
    3101             :     case 'm': // memory operand.
    3102             :     case 'o': // offsettable memory operand
    3103             :     case 'V': // non-offsettable memory operand
    3104             :       weight = CW_Memory;
    3105             :       break;
    3106         576 :     case 'r': // general register.
    3107             :     case 'g': // general register, memory operand or immediate integer.
    3108             :               // note: Clang converts "g" to "imr".
    3109        1152 :       if (CallOperandVal->getType()->isIntegerTy())
    3110             :         weight = CW_Register;
    3111             :       break;
    3112         147 :     case 'X': // any operand.
    3113             :     default:
    3114             :       weight = CW_Default;
    3115         147 :       break;
    3116             :   }
    3117             :   return weight;
    3118             : }
    3119             : 
    3120             : /// If there are multiple different constraints that we could pick for this
    3121             : /// operand (e.g. "imr") try to pick the 'best' one.
    3122             : /// This is somewhat tricky: constraints fall into four classes:
    3123             : ///    Other         -> immediates and magic values
    3124             : ///    Register      -> one specific register
    3125             : ///    RegisterClass -> a group of regs
    3126             : ///    Memory        -> memory
    3127             : /// Ideally, we would pick the most specific constraint possible: if we have
    3128             : /// something that fits into a register, we would pick it.  The problem here
    3129             : /// is that if we have something that could either be in a register or in
    3130             : /// memory that use of the register could cause selection of *other*
    3131             : /// operands to fail: they might only succeed if we pick memory.  Because of
    3132             : /// this the heuristic we use is:
    3133             : ///
    3134             : ///  1) If there is an 'other' constraint, and if the operand is valid for
    3135             : ///     that constraint, use it.  This makes us take advantage of 'i'
    3136             : ///     constraints when available.
    3137             : ///  2) Otherwise, pick the most general constraint present.  This prefers
    3138             : ///     'm' over 'r', for example.
    3139             : ///
    3140        9771 : static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
    3141             :                              const TargetLowering &TLI,
    3142             :                              SDValue Op, SelectionDAG *DAG) {
    3143             :   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
    3144             :   unsigned BestIdx = 0;
    3145             :   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
    3146             :   int BestGenerality = -1;
    3147             : 
    3148             :   // Loop over the options, keeping track of the most general one.
    3149      165375 :   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
    3150             :     TargetLowering::ConstraintType CType =
    3151      291804 :       TLI.getConstraintType(OpInfo.Codes[i]);
    3152             : 
    3153             :     // If this is an 'other' constraint, see if the operand is valid for it.
    3154             :     // For example, on X86 we might have an 'rI' constraint.  If the operand
    3155             :     // is an integer in the range [0..31] we want to use I (saving a load
    3156             :     // of a register), otherwise we must use 'r'.
    3157      145902 :     if (CType == TargetLowering::C_Other && Op.getNode()) {
    3158             :       assert(OpInfo.Codes[i].size() == 1 &&
    3159             :              "Unhandled multi-letter 'other' constraint");
    3160             :       std::vector<SDValue> ResultOps;
    3161         378 :       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
    3162         189 :                                        ResultOps, *DAG);
    3163         189 :       if (!ResultOps.empty()) {
    3164             :         BestType = CType;
    3165             :         BestIdx = i;
    3166             :         break;
    3167             :       }
    3168             :     }
    3169             : 
    3170             :     // Things with matching constraints can only be registers, per gcc
    3171             :     // documentation.  This mainly affects "g" constraints.
    3172      145866 :     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
    3173          33 :       continue;
    3174             : 
    3175             :     // This constraint letter is more general than the previous one, use it.
    3176      145800 :     int Generality = getConstraintGenerality(CType);
    3177      145800 :     if (Generality > BestGenerality) {
    3178             :       BestType = CType;
    3179             :       BestIdx = i;
    3180             :       BestGenerality = Generality;
    3181             :     }
    3182             :   }
    3183             : 
    3184       19542 :   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
    3185        9771 :   OpInfo.ConstraintType = BestType;
    3186        9771 : }
    3187             : 
    3188             : /// Determines the constraint code and constraint type to use for the specific
    3189             : /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
    3190      245715 : void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
    3191             :                                             SDValue Op,
    3192             :                                             SelectionDAG *DAG) const {
    3193             :   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
    3194             : 
    3195             :   // Single-letter constraints ('r') are very common.
    3196      491430 :   if (OpInfo.Codes.size() == 1) {
    3197      235944 :     OpInfo.ConstraintCode = OpInfo.Codes[0];
    3198      471888 :     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
    3199             :   } else {
    3200        9771 :     ChooseConstraint(OpInfo, *this, Op, DAG);
    3201             :   }
    3202             : 
    3203             :   // 'X' matches anything.
    3204      491430 :   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
    3205             :     // Labels and constants are handled elsewhere ('X' is the only thing
    3206             :     // that matches labels).  For Functions, the type here is the type of
    3207             :     // the result, which is not what we want to look at; leave them alone.
    3208             :     Value *v = OpInfo.CallOperandVal;
    3209         260 :     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
    3210             :       OpInfo.CallOperandVal = v;
    3211             :       return;
    3212             :     }
    3213             : 
    3214             :     // Otherwise, try to resolve it to something we know about by looking at
    3215             :     // the actual operand type.
    3216         376 :     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
    3217             :       OpInfo.ConstraintCode = Repl;
    3218         370 :       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
    3219             :     }
    3220             :   }
    3221             : }
    3222             : 
    3223             : /// \brief Given an exact SDIV by a constant, create a multiplication
    3224             : /// with the multiplicative inverse of the constant.
    3225         131 : static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
    3226             :                               const SDLoc &dl, SelectionDAG &DAG,
    3227             :                               std::vector<SDNode *> &Created) {
    3228             :   assert(d != 0 && "Division by zero!");
    3229             : 
    3230             :   // Shift the value upfront if it is even, so the LSB is one.
    3231         131 :   unsigned ShAmt = d.countTrailingZeros();
    3232         131 :   if (ShAmt) {
    3233             :     // TODO: For UDIV use SRL instead of SRA.
    3234             :     SDValue Amt =
    3235             :         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
    3236         260 :                                                         DAG.getDataLayout()));
    3237             :     SDNodeFlags Flags;
    3238             :     Flags.setExact(true);
    3239         130 :     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, Flags);
    3240         260 :     Created.push_back(Op1.getNode());
    3241         130 :     d.ashrInPlace(ShAmt);
    3242             :   }
    3243             : 
    3244             :   // Calculate the multiplicative inverse, using Newton's method.
    3245             :   APInt t, xn = d;
    3246        2011 :   while ((t = d*xn) != 1)
    3247        2332 :     xn *= APInt(d.getBitWidth(), 2) - t;
    3248             : 
    3249         131 :   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
    3250         131 :   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
    3251         262 :   Created.push_back(Mul.getNode());
    3252         262 :   return Mul;
    3253             : }
    3254             : 
    3255         711 : SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
    3256             :                                       SelectionDAG &DAG,
    3257             :                                       std::vector<SDNode *> *Created) const {
    3258         711 :   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
    3259         711 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3260        1422 :   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
    3261           3 :     return SDValue(N,0); // Lower SDIV as SDIV
    3262         708 :   return SDValue();
    3263             : }
    3264             : 
    3265             : /// \brief Given an ISD::SDIV node expressing a divide by constant,
    3266             : /// return a DAG expression to select that will generate the same value by
    3267             : /// multiplying by a magic number.
    3268             : /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
    3269         529 : SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
    3270             :                                   SelectionDAG &DAG, bool IsAfterLegalization,
    3271             :                                   std::vector<SDNode *> *Created) const {
    3272             :   assert(Created && "No vector to hold sdiv ops.");
    3273             : 
    3274        1058 :   EVT VT = N->getValueType(0);
    3275             :   SDLoc dl(N);
    3276             : 
    3277             :   // Check to see if we can do this.
    3278             :   // FIXME: We should be more aggressive here.
    3279         529 :   if (!isTypeLegal(VT))
    3280          44 :     return SDValue();
    3281             : 
    3282             :   // If the sdiv has an 'exact' bit we can use a simpler lowering.
    3283         485 :   if (N->getFlags().hasExact())
    3284         393 :     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
    3285             : 
    3286         354 :   APInt::ms magics = Divisor.magic();
    3287             : 
    3288             :   // Multiply the numerator (operand 0) by the magic value
    3289             :   // FIXME: We should support doing a MUL in a wider type
    3290             :   SDValue Q;
    3291         603 :   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
    3292             :                             isOperationLegalOrCustom(ISD::MULHS, VT))
    3293         228 :     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
    3294         228 :                     DAG.getConstant(magics.m, dl, VT));
    3295         403 :   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
    3296             :                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
    3297         199 :     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
    3298         199 :                               N->getOperand(0),
    3299         398 :                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
    3300             :   else
    3301          41 :     return SDValue();       // No mulhs or equvialent
    3302             :   // If d > 0 and m < 0, add the numerator
    3303         621 :   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
    3304         124 :     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
    3305         124 :     Created->push_back(Q.getNode());
    3306             :   }
    3307             :   // If d < 0 and m > 0, subtract the numerator.
    3308         626 :   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
    3309           0 :     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
    3310           0 :     Created->push_back(Q.getNode());
    3311             :   }
    3312         313 :   auto &DL = DAG.getDataLayout();
    3313             :   // Shift right algebraic if shift value is nonzero
    3314         313 :   if (magics.s > 0) {
    3315         294 :     Q = DAG.getNode(
    3316             :         ISD::SRA, dl, VT, Q,
    3317         882 :         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
    3318         588 :     Created->push_back(Q.getNode());
    3319             :   }
    3320             :   // Extract the sign bit and add it to the quotient
    3321             :   SDValue T =
    3322             :       DAG.getNode(ISD::SRL, dl, VT, Q,
    3323         313 :                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
    3324         939 :                                   getShiftAmountTy(Q.getValueType(), DL)));
    3325         626 :   Created->push_back(T.getNode());
    3326         313 :   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
    3327             : }
    3328             : 
    3329             : /// \brief Given an ISD::UDIV node expressing a divide by constant,
    3330             : /// return a DAG expression to select that will generate the same value by
    3331             : /// multiplying by a magic number.
    3332             : /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
    3333         515 : SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
    3334             :                                   SelectionDAG &DAG, bool IsAfterLegalization,
    3335             :                                   std::vector<SDNode *> *Created) const {
    3336             :   assert(Created && "No vector to hold udiv ops.");
    3337             : 
    3338        1030 :   EVT VT = N->getValueType(0);
    3339             :   SDLoc dl(N);
    3340         515 :   auto &DL = DAG.getDataLayout();
    3341             : 
    3342             :   // Check to see if we can do this.
    3343             :   // FIXME: We should be more aggressive here.
    3344             :   if (!isTypeLegal(VT))
    3345          40 :     return SDValue();
    3346             : 
    3347             :   // FIXME: We should use a narrower constant when the upper
    3348             :   // bits are known to be zero.
    3349         475 :   APInt::mu magics = Divisor.magicu();
    3350             : 
    3351         475 :   SDValue Q = N->getOperand(0);
    3352             : 
    3353             :   // If the divisor is even, we can avoid using the expensive fixup by shifting
    3354             :   // the divided value upfront.
    3355         716 :   if (magics.a != 0 && !Divisor[0]) {
    3356          42 :     unsigned Shift = Divisor.countTrailingZeros();
    3357          42 :     Q = DAG.getNode(
    3358             :         ISD::SRL, dl, VT, Q,
    3359         126 :         DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
    3360          84 :     Created->push_back(Q.getNode());
    3361             : 
    3362             :     // Get magic number for the shifted divisor.
    3363         126 :     magics = Divisor.lshr(Shift).magicu(Shift);
    3364             :     assert(magics.a == 0 && "Should use cheap fixup now");
    3365             :   }
    3366             : 
    3367             :   // Multiply the numerator (operand 0) by the magic value
    3368             :   // FIXME: We should support doing a MUL in a wider type
    3369         475 :   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
    3370             :                             isOperationLegalOrCustom(ISD::MULHU, VT))
    3371         108 :     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
    3372         367 :   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
    3373             :                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
    3374         331 :     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
    3375         331 :                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
    3376             :   else
    3377          36 :     return SDValue();       // No mulhu or equivalent
    3378             : 
    3379         878 :   Created->push_back(Q.getNode());
    3380             : 
    3381         439 :   if (magics.a == 0) {
    3382             :     assert(magics.s < Divisor.getBitWidth() &&
    3383             :            "We shouldn't generate an undefined shift!");
    3384             :     return DAG.getNode(
    3385             :         ISD::SRL, dl, VT, Q,
    3386         526 :         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
    3387             :   } else {
    3388         352 :     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
    3389         352 :     Created->push_back(NPQ.getNode());
    3390         176 :     NPQ = DAG.getNode(
    3391             :         ISD::SRL, dl, VT, NPQ,
    3392         528 :         DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
    3393         352 :     Created->push_back(NPQ.getNode());
    3394         176 :     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
    3395         352 :     Created->push_back(NPQ.getNode());
    3396             :     return DAG.getNode(
    3397             :         ISD::SRL, dl, VT, NPQ,
    3398         176 :         DAG.getConstant(magics.s - 1, dl,
    3399         352 :                         getShiftAmountTy(NPQ.getValueType(), DL)));
    3400             :   }
    3401             : }
    3402             : 
    3403          64 : bool TargetLowering::
    3404             : verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
    3405          64 :   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
    3406           0 :     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
    3407             :                                 "be a constant integer");
    3408           0 :     return true;
    3409             :   }
    3410             : 
    3411             :   return false;
    3412             : }
    3413             : 
    3414             : //===----------------------------------------------------------------------===//
    3415             : // Legalization Utilities
    3416             : //===----------------------------------------------------------------------===//
    3417             : 
    3418        2006 : bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
    3419             :                                     SDValue LHS, SDValue RHS,
    3420             :                                     SmallVectorImpl<SDValue> &Result,
    3421             :                                     EVT HiLoVT, SelectionDAG &DAG,
    3422             :                                     MulExpansionKind Kind, SDValue LL,
    3423             :                                     SDValue LH, SDValue RL, SDValue RH) const {
    3424             :   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
    3425             :          Opcode == ISD::SMUL_LOHI);
    3426             : 
    3427        2006 :   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
    3428        3898 :                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
    3429        2006 :   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
    3430        3898 :                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
    3431        2006 :   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
    3432        3898 :                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
    3433        2006 :   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
    3434        3898 :                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
    3435             : 
    3436        2006 :   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
    3437             :     return false;
    3438             : 
    3439             :   unsigned OuterBitSize = VT.getScalarSizeInBits();
    3440             :   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
    3441        1657 :   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
    3442        1657 :   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
    3443             : 
    3444             :   // LL, LH, RL, and RH must be either all NULL or all set to a value.
    3445             :   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
    3446             :          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
    3447             : 
    3448        1657 :   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
    3449             :   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
    3450        1999 :                           bool Signed) -> bool {
    3451        1999 :     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
    3452        2653 :       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
    3453        1781 :       Hi = SDValue(Lo.getNode(), 1);
    3454        1781 :       return true;
    3455             :     }
    3456         218 :     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
    3457         654 :       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
    3458         218 :       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
    3459         218 :       return true;
    3460             :     }
    3461             :     return false;
    3462        1657 :   };
    3463             : 
    3464        1657 :   SDValue Lo, Hi;
    3465             : 
    3466        1657 :   if (!LL.getNode() && !RL.getNode() &&
    3467         279 :       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
    3468         279 :     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
    3469         279 :     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
    3470             :   }
    3471             : 
    3472        1657 :   if (!LL.getNode())
    3473             :     return false;
    3474             : 
    3475        1657 :   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
    3476        2627 :   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
    3477         970 :       DAG.MaskedValueIsZero(RHS, HighMask)) {
    3478             :     // The inputs are both zero-extended.
    3479         967 :     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
    3480         967 :       Result.push_back(Lo);
    3481         967 :       Result.push_back(Hi);
    3482         967 :       if (Opcode != ISD::MUL) {
    3483           0 :         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
    3484           0 :         Result.push_back(Zero);
    3485           0 :         Result.push_back(Zero);
    3486             :       }
    3487             :       return true;
    3488             :     }
    3489             :   }
    3490             : 
    3491         690 :   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
    3492             :       RHSSB > InnerBitSize) {
    3493             :     // The input values are both sign-extended.
    3494             :     // TODO non-MUL case?
    3495         200 :     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
    3496         200 :       Result.push_back(Lo);
    3497         200 :       Result.push_back(Hi);
    3498         200 :       return true;
    3499             :     }
    3500             :   }
    3501             : 
    3502         490 :   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
    3503         980 :   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
    3504        1470 :   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
    3505             :     // FIXME getShiftAmountTy does not always return a sensible result when VT
    3506             :     // is an illegal type, and so the type may be too small to fit the shift
    3507             :     // amount. Override it with i32. The shift will have to be legalized.
    3508           0 :     ShiftAmountTy = MVT::i32;
    3509             :   }
    3510         490 :   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
    3511             : 
    3512         246 :   if (!LH.getNode() && !RH.getNode() &&
    3513         736 :       isOperationLegalOrCustom(ISD::SRL, VT) &&
    3514         246 :       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
    3515         246 :     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
    3516         246 :     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
    3517         246 :     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
    3518         246 :     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
    3519             :   }
    3520             : 
    3521         490 :   if (!LH.getNode())
    3522             :     return false;
    3523             : 
    3524         490 :   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
    3525             :     return false;
    3526             : 
    3527         490 :   Result.push_back(Lo);
    3528             : 
    3529         490 :   if (Opcode == ISD::MUL) {
    3530         376 :     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
    3531         376 :     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
    3532         376 :     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
    3533         376 :     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
    3534         376 :     Result.push_back(Hi);
    3535         376 :     return true;
    3536             :   }
    3537             : 
    3538             :   // Compute the full width result.
    3539         342 :   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
    3540        2394 :     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
    3541         342 :     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
    3542         684 :     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
    3543         342 :     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
    3544         114 :   };
    3545             : 
    3546         114 :   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
    3547         114 :   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
    3548             :     return false;
    3549             : 
    3550             :   // This is effectively the add part of a multiply-add of half-sized operands,
    3551             :   // so it cannot overflow.
    3552         114 :   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
    3553             : 
    3554         114 :   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
    3555             :     return false;
    3556             : 
    3557         114 :   Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
    3558         342 :                      Merge(Lo, Hi));
    3559             : 
    3560         114 :   SDValue Carry = Next.getValue(1);
    3561         114 :   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
    3562         114 :   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
    3563             : 
    3564         114 :   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
    3565             :     return false;
    3566             : 
    3567         114 :   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
    3568         114 :   Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
    3569         228 :                    Carry);
    3570         114 :   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
    3571             : 
    3572         114 :   if (Opcode == ISD::SMUL_LOHI) {
    3573             :     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
    3574           0 :                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
    3575           0 :     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
    3576             : 
    3577           0 :     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
    3578           0 :                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
    3579           0 :     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
    3580             :   }
    3581             : 
    3582         114 :   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
    3583         114 :   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
    3584         114 :   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
    3585         114 :   return true;
    3586             : }
    3587             : 
    3588        1892 : bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
    3589             :                                SelectionDAG &DAG, MulExpansionKind Kind,
    3590             :                                SDValue LL, SDValue LH, SDValue RL,
    3591             :                                SDValue RH) const {
    3592             :   SmallVector<SDValue, 2> Result;
    3593        5676 :   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
    3594        1892 :                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
    3595        1892 :                            DAG, Kind, LL, LH, RL, RH);
    3596        1892 :   if (Ok) {
    3597             :     assert(Result.size() == 2);
    3598        1543 :     Lo = Result[0];
    3599        1543 :     Hi = Result[1];
    3600             :   }
    3601        1892 :   return Ok;
    3602             : }
    3603             : 
    3604          74 : bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
    3605             :                                SelectionDAG &DAG) const {
    3606         148 :   EVT VT = Node->getOperand(0).getValueType();
    3607         148 :   EVT NVT = Node->getValueType(0);
    3608             :   SDLoc dl(SDValue(Node, 0));
    3609             : 
    3610             :   // FIXME: Only f32 to i64 conversions are supported.
    3611          74 :   if (VT != MVT::f32 || NVT != MVT::i64)
    3612             :     return false;
    3613             : 
    3614             :   // Expand f32 -> i64 conversion
    3615             :   // This algorithm comes from compiler-rt's implementation of fixsfdi:
    3616             :   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
    3617          74 :   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
    3618         148 :                                 VT.getSizeInBits());
    3619          74 :   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
    3620          74 :   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
    3621          74 :   SDValue Bias = DAG.getConstant(127, dl, IntVT);
    3622         148 :   SDValue SignMask = DAG.getConstant(APInt::getSignMask(VT.getSizeInBits()), dl,
    3623          74 :                                      IntVT);
    3624          74 :   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
    3625          74 :   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
    3626             : 
    3627         148 :   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
    3628             : 
    3629          74 :   auto &DL = DAG.getDataLayout();
    3630             :   SDValue ExponentBits = DAG.getNode(
    3631             :       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
    3632         148 :       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
    3633          74 :   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
    3634             : 
    3635             :   SDValue Sign = DAG.getNode(
    3636             :       ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
    3637         148 :       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
    3638          74 :   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
    3639             : 
    3640             :   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
    3641             :       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
    3642         148 :       DAG.getConstant(0x00800000, dl, IntVT));
    3643             : 
    3644          74 :   R = DAG.getZExtOrTrunc(R, dl, NVT);
    3645             : 
    3646          74 :   R = DAG.getSelectCC(
    3647             :       dl, Exponent, ExponentLoBit,
    3648             :       DAG.getNode(ISD::SHL, dl, NVT, R,
    3649             :                   DAG.getZExtOrTrunc(
    3650             :                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
    3651             :                       dl, getShiftAmountTy(IntVT, DL))),
    3652             :       DAG.getNode(ISD::SRL, dl, NVT, R,
    3653             :                   DAG.getZExtOrTrunc(
    3654             :                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
    3655             :                       dl, getShiftAmountTy(IntVT, DL))),
    3656         370 :       ISD::SETGT);
    3657             : 
    3658             :   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
    3659             :       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
    3660          74 :       Sign);
    3661             : 
    3662          74 :   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
    3663          74 :       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
    3664          74 :   return true;
    3665             : }
    3666             : 
    3667        1722 : SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
    3668             :                                             SelectionDAG &DAG) const {
    3669             :   SDLoc SL(LD);
    3670        1722 :   SDValue Chain = LD->getChain();
    3671        1722 :   SDValue BasePTR = LD->getBasePtr();
    3672        1722 :   EVT SrcVT = LD->getMemoryVT();
    3673             :   ISD::LoadExtType ExtType = LD->getExtensionType();
    3674             : 
    3675        1722 :   unsigned NumElem = SrcVT.getVectorNumElements();
    3676             : 
    3677        1722 :   EVT SrcEltVT = SrcVT.getScalarType();
    3678        3444 :   EVT DstEltVT = LD->getValueType(0).getScalarType();
    3679             : 
    3680        1722 :   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
    3681             :   assert(SrcEltVT.isByteSized());
    3682             : 
    3683        1722 :   EVT PtrVT = BasePTR.getValueType();
    3684             : 
    3685             :   SmallVector<SDValue, 8> Vals;
    3686             :   SmallVector<SDValue, 8> LoadChains;
    3687             : 
    3688       16422 :   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
    3689             :     SDValue ScalarLoad =
    3690             :         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
    3691        7350 :                        LD->getPointerInfo().getWithOffset(Idx * Stride),
    3692        7350 :                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
    3693       29400 :                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3694             : 
    3695        7350 :     BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
    3696       14700 :                           DAG.getConstant(Stride, SL, PtrVT));
    3697             : 
    3698        7350 :     Vals.push_back(ScalarLoad.getValue(0));
    3699        7350 :     LoadChains.push_back(ScalarLoad.getValue(1));
    3700             :   }
    3701             : 
    3702        1722 :   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
    3703        3444 :   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
    3704             : 
    3705        5166 :   return DAG.getMergeValues({ Value, NewChain }, SL);
    3706             : }
    3707             : 
    3708        1593 : SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
    3709             :                                              SelectionDAG &DAG) const {
    3710             :   SDLoc SL(ST);
    3711             : 
    3712        1593 :   SDValue Chain = ST->getChain();
    3713        1593 :   SDValue BasePtr = ST->getBasePtr();
    3714        1593 :   SDValue Value = ST->getValue();
    3715        1593 :   EVT StVT = ST->getMemoryVT();
    3716             : 
    3717             :   // The type of the data we want to save
    3718        1593 :   EVT RegVT = Value.getValueType();
    3719        1593 :   EVT RegSclVT = RegVT.getScalarType();
    3720             : 
    3721             :   // The type of data as saved in memory.
    3722        1593 :   EVT MemSclVT = StVT.getScalarType();
    3723             : 
    3724        3186 :   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
    3725        1593 :   unsigned NumElem = StVT.getVectorNumElements();
    3726             : 
    3727             :   // A vector must always be stored in memory as-is, i.e. without any padding
    3728             :   // between the elements, since various code depend on it, e.g. in the
    3729             :   // handling of a bitcast of a vector type to int, which may be done with a
    3730             :   // vector store followed by an integer load. A vector that does not have
    3731             :   // elements that are byte-sized must therefore be stored as an integer
    3732             :   // built out of the extracted vector elements.
    3733        1593 :   if (!MemSclVT.isByteSized()) {
    3734         167 :     unsigned NumBits = StVT.getSizeInBits();
    3735         167 :     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
    3736             : 
    3737         167 :     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
    3738             : 
    3739        4875 :     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
    3740             :       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
    3741        2354 :                                 DAG.getConstant(Idx, SL, IdxVT));
    3742        2354 :       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
    3743        2354 :       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
    3744             :       unsigned ShiftIntoIdx =
    3745        4708 :           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
    3746             :       SDValue ShiftAmount =
    3747        2354 :           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
    3748             :       SDValue ShiftedElt =
    3749        2354 :           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
    3750        2354 :       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
    3751             :     }
    3752             : 
    3753         167 :     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
    3754         167 :                         ST->getAlignment(), ST->getMemOperand()->getFlags(),
    3755         501 :                         ST->getAAInfo());
    3756             :   }
    3757             : 
    3758             :   // Store Stride in bytes
    3759        1426 :   unsigned Stride = MemSclVT.getSizeInBits() / 8;
    3760             :   assert (Stride && "Zero stride!");
    3761             :   // Extract each of the elements from the original vector and save them into
    3762             :   // memory individually.
    3763             :   SmallVector<SDValue, 8> Stores;
    3764       16734 :   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
    3765             :     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
    3766        7654 :                               DAG.getConstant(Idx, SL, IdxVT));
    3767             : 
    3768        7654 :     SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride);
    3769             : 
    3770             :     // This scalar TruncStore may be illegal, but we legalize it later.
    3771             :     SDValue Store = DAG.getTruncStore(
    3772        7654 :         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
    3773        7654 :         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
    3774       30616 :         ST->getMemOperand()->getFlags(), ST->getAAInfo());
    3775             : 
    3776        7654 :     Stores.push_back(Store);
    3777             :   }
    3778             : 
    3779        1426 :   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
    3780             : }
    3781             : 
    3782             : std::pair<SDValue, SDValue>
    3783         956 : TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
    3784             :   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
    3785             :          "unaligned indexed loads not implemented!");
    3786         956 :   SDValue Chain = LD->getChain();
    3787         956 :   SDValue Ptr = LD->getBasePtr();
    3788        1912 :   EVT VT = LD->getValueType(0);
    3789         956 :   EVT LoadedVT = LD->getMemoryVT();
    3790             :   SDLoc dl(LD);
    3791         956 :   auto &MF = DAG.getMachineFunction();
    3792             : 
    3793        1845 :   if (VT.isFloatingPoint() || VT.isVector()) {
    3794          70 :     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
    3795          46 :     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
    3796             :       if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
    3797             :         // Scalarize the load and let the individual components be handled.
    3798           0 :         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
    3799             :         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
    3800             :       }
    3801             : 
    3802             :       // Expand to a (misaligned) integer load of the same size,
    3803             :       // then bitconvert to floating point or vector.
    3804             :       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
    3805          46 :                                     LD->getMemOperand());
    3806          46 :       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
    3807          46 :       if (LoadedVT != VT)
    3808           0 :         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
    3809           0 :                              ISD::ANY_EXTEND, dl, VT, Result);
    3810             : 
    3811          46 :       return std::make_pair(Result, newLoad.getValue(1));
    3812             :     }
    3813             : 
    3814             :     // Copy the value to a (aligned) stack slot using (unaligned) integer
    3815             :     // loads and stores, then do a (aligned) load from the stack slot.
    3816          24 :     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
    3817             :     unsigned LoadedBytes = LoadedVT.getStoreSize();
    3818          24 :     unsigned RegBytes = RegVT.getSizeInBits() / 8;
    3819          24 :     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
    3820             : 
    3821             :     // Make sure the stack slot is also aligned for the register type.
    3822          24 :     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
    3823          24 :     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
    3824             :     SmallVector<SDValue, 8> Stores;
    3825          24 :     SDValue StackPtr = StackBase;
    3826             :     unsigned Offset = 0;
    3827             : 
    3828          24 :     EVT PtrVT = Ptr.getValueType();
    3829          24 :     EVT StackPtrVT = StackPtr.getValueType();
    3830             : 
    3831          24 :     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
    3832          24 :     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
    3833             : 
    3834             :     // Do all but one copies using the full register width.
    3835          94 :     for (unsigned i = 1; i < NumRegs; i++) {
    3836             :       // Load one integer register's worth from the original location.
    3837             :       SDValue Load = DAG.getLoad(
    3838          35 :           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
    3839          70 :           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
    3840         175 :           LD->getAAInfo());
    3841             :       // Follow the load with a store to the stack slot.  Remember the store.
    3842          35 :       Stores.push_back(DAG.getStore(
    3843             :           Load.getValue(1), dl, Load, StackPtr,
    3844          70 :           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
    3845             :       // Increment the pointers.
    3846          35 :       Offset += RegBytes;
    3847             : 
    3848          35 :       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
    3849          35 :       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
    3850             :     }
    3851             : 
    3852             :     // The last copy may be partial.  Do an extending load.
    3853          24 :     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
    3854          48 :                                   8 * (LoadedBytes - Offset));
    3855             :     SDValue Load =
    3856             :         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
    3857          24 :                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
    3858          24 :                        MinAlign(LD->getAlignment(), Offset),
    3859         120 :                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3860             :     // Follow the load with a store to the stack slot.  Remember the store.
    3861             :     // On big-endian machines this requires a truncating store to ensure
    3862             :     // that the bits end up in the right place.
    3863          24 :     Stores.push_back(DAG.getTruncStore(
    3864             :         Load.getValue(1), dl, Load, StackPtr,
    3865          48 :         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
    3866             : 
    3867             :     // The order of the stores doesn't matter - say it with a TokenFactor.
    3868          24 :     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
    3869             : 
    3870             :     // Finally, perform the original load only redirected to the stack slot.
    3871          24 :     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
    3872             :                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
    3873          48 :                           LoadedVT);
    3874             : 
    3875             :     // Callers expect a MERGE_VALUES node.
    3876             :     return std::make_pair(Load, TF);
    3877             :   }
    3878             : 
    3879             :   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
    3880             :          "Unaligned load of unsupported type.");
    3881             : 
    3882             :   // Compute the new VT that is half the size of the old one.  This is an
    3883             :   // integer MVT.
    3884         886 :   unsigned NumBits = LoadedVT.getSizeInBits();
    3885             :   EVT NewLoadedVT;
    3886         886 :   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
    3887         886 :   NumBits >>= 1;
    3888             : 
    3889         886 :   unsigned Alignment = LD->getAlignment();
    3890         886 :   unsigned IncrementSize = NumBits / 8;
    3891             :   ISD::LoadExtType HiExtType = LD->getExtensionType();
    3892             : 
    3893             :   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
    3894         886 :   if (HiExtType == ISD::NON_EXTLOAD)
    3895             :     HiExtType = ISD::ZEXTLOAD;
    3896             : 
    3897             :   // Load the value in two parts
    3898         886 :   SDValue Lo, Hi;
    3899        1772 :   if (DAG.getDataLayout().isLittleEndian()) {
    3900         812 :     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
    3901         812 :                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
    3902        2436 :                         LD->getAAInfo());
    3903             : 
    3904         812 :     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
    3905         812 :     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
    3906             :                         LD->getPointerInfo().getWithOffset(IncrementSize),
    3907         812 :                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
    3908        4060 :                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3909             :   } else {
    3910          74 :     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
    3911          74 :                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
    3912         222 :                         LD->getAAInfo());
    3913             : 
    3914          74 :     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
    3915          74 :     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
    3916             :                         LD->getPointerInfo().getWithOffset(IncrementSize),
    3917          74 :                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
    3918         370 :                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3919             :   }
    3920             : 
    3921             :   // aggregate the two parts
    3922             :   SDValue ShiftAmount =
    3923             :       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
    3924        1772 :                                                     DAG.getDataLayout()));
    3925         886 :   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
    3926         886 :   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
    3927             : 
    3928             :   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
    3929         886 :                              Hi.getValue(1));
    3930             : 
    3931             :   return std::make_pair(Result, TF);
    3932             : }
    3933             : 
    3934         970 : SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
    3935             :                                              SelectionDAG &DAG) const {
    3936             :   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
    3937             :          "unaligned indexed stores not implemented!");
    3938         970 :   SDValue Chain = ST->getChain();
    3939         970 :   SDValue Ptr = ST->getBasePtr();
    3940         970 :   SDValue Val = ST->getValue();
    3941         970 :   EVT VT = Val.getValueType();
    3942        1940 :   int Alignment = ST->getAlignment();
    3943         970 :   auto &MF = DAG.getMachineFunction();
    3944             : 
    3945             :   SDLoc dl(ST);
    3946        2859 :   if (ST->getMemoryVT().isFloatingPoint() ||
    3947        1889 :       ST->getMemoryVT().isVector()) {
    3948          81 :     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
    3949             :     if (isTypeLegal(intVT)) {
    3950             :       if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
    3951             :         // Scalarize the store and let the individual components be handled.
    3952          18 :         SDValue Result = scalarizeVectorStore(ST, DAG);
    3953             : 
    3954          18 :         return Result;
    3955             :       }
    3956             :       // Expand to a bitconvert of the value to the integer type of the
    3957             :       // same size, then a (misaligned) int store.
    3958             :       // FIXME: Does not handle truncating floating point stores!
    3959          38 :       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
    3960          38 :       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
    3961          76 :                             Alignment, ST->getMemOperand()->getFlags());
    3962          38 :       return Result;
    3963             :     }
    3964             :     // Do a (aligned) store to a stack slot, then copy from the stack slot
    3965             :     // to the final destination using (unaligned) integer loads and stores.
    3966          25 :     EVT StoredVT = ST->getMemoryVT();
    3967             :     MVT RegVT =
    3968          25 :       getRegisterType(*DAG.getContext(),
    3969          25 :                       EVT::getIntegerVT(*DAG.getContext(),
    3970          75 :                                         StoredVT.getSizeInBits()));
    3971          25 :     EVT PtrVT = Ptr.getValueType();
    3972             :     unsigned StoredBytes = StoredVT.getStoreSize();
    3973          25 :     unsigned RegBytes = RegVT.getSizeInBits() / 8;
    3974          25 :     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
    3975             : 
    3976             :     // Make sure the stack slot is also aligned for the register type.
    3977          25 :     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
    3978          25 :     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
    3979             : 
    3980             :     // Perform the original store, only redirected to the stack slot.
    3981             :     SDValue Store = DAG.getTruncStore(
    3982             :         Chain, dl, Val, StackPtr,
    3983          25 :         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoredVT);
    3984             : 
    3985          25 :     EVT StackPtrVT = StackPtr.getValueType();
    3986             : 
    3987          25 :     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
    3988          25 :     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
    3989             :     SmallVector<SDValue, 8> Stores;
    3990             :     unsigned Offset = 0;
    3991             : 
    3992             :     // Do all but one copies using the full register width.
    3993          99 :     for (unsigned i = 1; i < NumRegs; i++) {
    3994             :       // Load one integer register's worth from the stack slot.
    3995             :       SDValue Load = DAG.getLoad(
    3996             :           RegVT, dl, Store, StackPtr,
    3997          74 :           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
    3998             :       // Store it to the final location.  Remember the store.
    3999          37 :       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
    4000          37 :                                     ST->getPointerInfo().getWithOffset(Offset),
    4001          37 :                                     MinAlign(ST->getAlignment(), Offset),
    4002         148 :                                     ST->getMemOperand()->getFlags()));
    4003             :       // Increment the pointers.
    4004          37 :       Offset += RegBytes;
    4005          37 :       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
    4006          37 :       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
    4007             :     }
    4008             : 
    4009             :     // The last store may be partial.  Do a truncating store.  On big-endian
    4010             :     // machines this requires an extending load from the stack slot to ensure
    4011             :     // that the bits are in the right place.
    4012          25 :     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
    4013          50 :                                   8 * (StoredBytes - Offset));
    4014             : 
    4015             :     // Load from the stack slot.
    4016             :     SDValue Load = DAG.getExtLoad(
    4017             :         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
    4018          50 :         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT);
    4019             : 
    4020          25 :     Stores.push_back(
    4021          50 :         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
    4022          25 :                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
    4023          25 :                           MinAlign(ST->getAlignment(), Offset),
    4024         125 :                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
    4025             :     // The order of the stores doesn't matter - say it with a TokenFactor.
    4026          25 :     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
    4027          25 :     return Result;
    4028             :   }
    4029             : 
    4030             :   assert(ST->getMemoryVT().isInteger() &&
    4031             :          !ST->getMemoryVT().isVector() &&
    4032             :          "Unaligned store of unknown type.");
    4033             :   // Get the half-size VT
    4034         889 :   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
    4035         889 :   int NumBits = NewStoredVT.getSizeInBits();
    4036         889 :   int IncrementSize = NumBits / 8;
    4037             : 
    4038             :   // Divide the stored value in two parts.
    4039             :   SDValue ShiftAmount =
    4040             :       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
    4041        1778 :                                                     DAG.getDataLayout()));
    4042         889 :   SDValue Lo = Val;
    4043         889 :   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
    4044             : 
    4045             :   // Store the two parts
    4046             :   SDValue Store1, Store2;
    4047         889 :   Store1 = DAG.getTruncStore(Chain, dl,
    4048        1778 :                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
    4049             :                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
    4050        1778 :                              ST->getMemOperand()->getFlags());
    4051             : 
    4052         889 :   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
    4053             :   Alignment = MinAlign(Alignment, IncrementSize);
    4054         889 :   Store2 = DAG.getTruncStore(
    4055        1778 :       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
    4056             :       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
    4057        3556 :       ST->getMemOperand()->getFlags(), ST->getAAInfo());
    4058             : 
    4059             :   SDValue Result =
    4060         889 :     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
    4061         889 :   return Result;
    4062             : }
    4063             : 
    4064             : SDValue
    4065          36 : TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
    4066             :                                        const SDLoc &DL, EVT DataVT,
    4067             :                                        SelectionDAG &DAG,
    4068             :                                        bool IsCompressedMemory) const {
    4069          36 :   SDValue Increment;
    4070          72 :   EVT AddrVT = Addr.getValueType();
    4071          72 :   EVT MaskVT = Mask.getValueType();
    4072             :   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
    4073             :          "Incompatible types of Data and Mask");
    4074          36 :   if (IsCompressedMemory) {
    4075             :     // Incrementing the pointer according to number of '1's in the mask.
    4076           8 :     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
    4077           8 :     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
    4078           8 :     if (MaskIntVT.getSizeInBits() < 32) {
    4079           8 :       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
    4080           8 :       MaskIntVT = MVT::i32;
    4081             :     }
    4082             : 
    4083             :     // Count '1's with POPCNT.
    4084           8 :     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
    4085           8 :     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
    4086             :     // Scale is an element size in bytes.
    4087           8 :     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
    4088           8 :                                     AddrVT);
    4089           8 :     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
    4090             :   } else
    4091          28 :     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
    4092             : 
    4093          36 :   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
    4094             : }
    4095             : 
    4096        2898 : static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
    4097             :                                        SDValue Idx,
    4098             :                                        EVT VecVT,
    4099             :                                        const SDLoc &dl) {
    4100             :   if (isa<ConstantSDNode>(Idx))
    4101         947 :     return Idx;
    4102             : 
    4103        1951 :   EVT IdxVT = Idx.getValueType();
    4104        1951 :   unsigned NElts = VecVT.getVectorNumElements();
    4105             :   if (isPowerOf2_32(NElts)) {
    4106             :     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
    4107        1951 :                                      Log2_32(NElts));
    4108             :     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
    4109        1951 :                        DAG.getConstant(Imm, dl, IdxVT));
    4110             :   }
    4111             : 
    4112             :   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
    4113           0 :                      DAG.getConstant(NElts - 1, dl, IdxVT));
    4114             : }
    4115             : 
    4116        2898 : SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
    4117             :                                                 SDValue VecPtr, EVT VecVT,
    4118             :                                                 SDValue Index) const {
    4119             :   SDLoc dl(Index);
    4120             :   // Make sure the index type is big enough to compute in.
    4121        5796 :   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
    4122             : 
    4123        2898 :   EVT EltVT = VecVT.getVectorElementType();
    4124             : 
    4125             :   // Calculate the element offset and add it to the pointer.
    4126        2898 :   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
    4127             :   assert(EltSize * 8 == EltVT.getSizeInBits() &&
    4128             :          "Converting bits to bytes lost precision");
    4129             : 
    4130        2898 :   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
    4131             : 
    4132        2898 :   EVT IdxVT = Index.getValueType();
    4133             : 
    4134        2898 :   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
    4135        5796 :                       DAG.getConstant(EltSize, dl, IdxVT));
    4136        5796 :   return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index);
    4137             : }
    4138             : 
    4139             : //===----------------------------------------------------------------------===//
    4140             : // Implementation of Emulated TLS Model
    4141             : //===----------------------------------------------------------------------===//
    4142             : 
    4143         212 : SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
    4144             :                                                 SelectionDAG &DAG) const {
    4145             :   // Access to address of TLS varialbe xyz is lowered to a function call:
    4146             :   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
    4147         212 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    4148         212 :   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
    4149             :   SDLoc dl(GA);
    4150             : 
    4151             :   ArgListTy Args;
    4152             :   ArgListEntry Entry;
    4153         424 :   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
    4154         212 :   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
    4155             :   StringRef EmuTlsVarName(NameString);
    4156             :   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
    4157             :   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
    4158         212 :   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
    4159         212 :   Entry.Ty = VoidPtrType;
    4160         212 :   Args.push_back(Entry);
    4161             : 
    4162         212 :   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
    4163             : 
    4164         424 :   TargetLowering::CallLoweringInfo CLI(DAG);
    4165             :   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
    4166         212 :   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
    4167         212 :   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    4168             : 
    4169             :   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
    4170             :   // At last for X86 targets, maybe good for other targets too?
    4171         212 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    4172             :   MFI.setAdjustsStack(true);  // Is this only for X86 target?
    4173             :   MFI.setHasCalls(true);
    4174             : 
    4175             :   assert((GA->getOffset() == 0) &&
    4176             :          "Emulated TLS must have zero offset in GlobalAddressSDNode");
    4177         424 :   return CallResult.first;
    4178             : }
    4179             : 
    4180          25 : SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
    4181             :                                                 SelectionDAG &DAG) const {
    4182             :   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
    4183          25 :   if (!isCtlzFast())
    4184           0 :     return SDValue();
    4185          25 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    4186             :   SDLoc dl(Op);
    4187             :   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
    4188          46 :     if (C->isNullValue() && CC == ISD::SETEQ) {
    4189          14 :       EVT VT = Op.getOperand(0).getValueType();
    4190           7 :       SDValue Zext = Op.getOperand(0);
    4191           7 :       if (VT.bitsLT(MVT::i32)) {
    4192           0 :         VT = MVT::i32;
    4193           0 :         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
    4194             :       }
    4195           7 :       unsigned Log2b = Log2_32(VT.getSizeInBits());
    4196           7 :       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
    4197             :       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
    4198           7 :                                 DAG.getConstant(Log2b, dl, MVT::i32));
    4199           7 :       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
    4200             :     }
    4201             :   }
    4202          18 :   return SDValue();
    4203             : }

Generated by: LCOV version 1.13