LCOV - code coverage report
Current view: top level - lib/CodeGen/SelectionDAG - TargetLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1806 1959 92.2 %
Date: 2017-09-14 15:23:50 Functions: 55 57 96.5 %
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/Target/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/IR/DataLayout.h"
      24             : #include "llvm/IR/DerivedTypes.h"
      25             : #include "llvm/IR/GlobalVariable.h"
      26             : #include "llvm/IR/LLVMContext.h"
      27             : #include "llvm/MC/MCAsmInfo.h"
      28             : #include "llvm/MC/MCExpr.h"
      29             : #include "llvm/Support/ErrorHandling.h"
      30             : #include "llvm/Support/KnownBits.h"
      31             : #include "llvm/Support/MathExtras.h"
      32             : #include "llvm/Target/TargetLoweringObjectFile.h"
      33             : #include "llvm/Target/TargetMachine.h"
      34             : #include "llvm/Target/TargetRegisterInfo.h"
      35             : #include "llvm/Target/TargetSubtargetInfo.h"
      36             : #include <cctype>
      37             : using namespace llvm;
      38             : 
      39             : /// NOTE: The TargetMachine owns TLOF.
      40       28520 : TargetLowering::TargetLowering(const TargetMachine &tm)
      41       28520 :   : TargetLoweringBase(tm) {}
      42             : 
      43           0 : const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
      44           0 :   return nullptr;
      45             : }
      46             : 
      47     1759588 : bool TargetLowering::isPositionIndependent() const {
      48     1759588 :   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        1860 : bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
      54             :                                           SDValue &Chain) const {
      55        1860 :   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        1860 :   AttributeList CallerAttrs = F->getAttributes();
      60        3720 :   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
      61        1860 :           .removeAttribute(Attribute::NoAlias)
      62        1860 :           .hasAttributes())
      63             :     return false;
      64             : 
      65             :   // It's not safe to eliminate the sign / zero extension of the return value.
      66        3700 :   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
      67        1850 :       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
      68             :     return false;
      69             : 
      70             :   // Check if the only use is a function return node.
      71        1850 :   return isUsedByReturnOnly(Node, Chain);
      72             : }
      73             : 
      74        1608 : bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
      75             :     const uint32_t *CallerPreservedMask,
      76             :     const SmallVectorImpl<CCValAssign> &ArgLocs,
      77             :     const SmallVectorImpl<SDValue> &OutVals) const {
      78        6190 :   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
      79        5968 :     const CCValAssign &ArgLoc = ArgLocs[I];
      80        2984 :     if (!ArgLoc.isRegLoc())
      81        3150 :       continue;
      82        2802 :     unsigned Reg = ArgLoc.getLocReg();
      83             :     // Only look at callee saved registers.
      84        2802 :     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
      85        2786 :       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          32 :     SDValue Value = OutVals[I];
      90          16 :     if (Value->getOpcode() != ISD::CopyFromReg)
      91          10 :       return false;
      92          48 :     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      405973 : void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS,
     102             :                                                      unsigned ArgIdx) {
     103      405973 :   IsSExt = CS->paramHasAttr(ArgIdx, Attribute::SExt);
     104      405973 :   IsZExt = CS->paramHasAttr(ArgIdx, Attribute::ZExt);
     105      405973 :   IsInReg = CS->paramHasAttr(ArgIdx, Attribute::InReg);
     106      405973 :   IsSRet = CS->paramHasAttr(ArgIdx, Attribute::StructRet);
     107      405973 :   IsNest = CS->paramHasAttr(ArgIdx, Attribute::Nest);
     108      405973 :   IsByVal = CS->paramHasAttr(ArgIdx, Attribute::ByVal);
     109      405973 :   IsInAlloca = CS->paramHasAttr(ArgIdx, Attribute::InAlloca);
     110      405973 :   IsReturned = CS->paramHasAttr(ArgIdx, Attribute::Returned);
     111      405973 :   IsSwiftSelf = CS->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
     112      405973 :   IsSwiftError = CS->paramHasAttr(ArgIdx, Attribute::SwiftError);
     113      405973 :   Alignment  = CS->getParamAlignment(ArgIdx);
     114      405973 : }
     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        2716 : 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        5432 :   TargetLowering::ArgListTy Args;
     124        2716 :   Args.reserve(Ops.size());
     125             : 
     126        2716 :   TargetLowering::ArgListEntry Entry;
     127        9319 :   for (SDValue Op : Ops) {
     128        3887 :     Entry.Node = Op;
     129        7774 :     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
     130        7774 :     Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
     131        7774 :     Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
     132        3887 :     Args.push_back(Entry);
     133             :   }
     134             : 
     135        2716 :   if (LC == RTLIB::UNKNOWN_LIBCALL)
     136           0 :     report_fatal_error("Unsupported library call operation!");
     137             :   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
     138       13580 :                                          getPointerTy(DAG.getDataLayout()));
     139             : 
     140        2716 :   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
     141        5432 :   TargetLowering::CallLoweringInfo CLI(DAG);
     142        2716 :   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
     143        2716 :   CLI.setDebugLoc(dl)
     144        5432 :       .setChain(DAG.getEntryNode())
     145        5432 :       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
     146        5432 :       .setNoReturn(doesNotReturn)
     147        5432 :       .setDiscardResult(!isReturnValueUsed)
     148        5432 :       .setSExtResult(signExtend)
     149        5432 :       .setZExtResult(!signExtend);
     150        5432 :   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         289 : 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         289 :   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
     164         289 :   bool ShouldInvertCC = false;
     165         289 :   switch (CCCode) {
     166          62 :   case ISD::SETEQ:
     167             :   case ISD::SETOEQ:
     168         124 :     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
     169          38 :           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
     170           8 :           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
     171          62 :     break;
     172          41 :   case ISD::SETNE:
     173             :   case ISD::SETUNE:
     174          82 :     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
     175          25 :           (VT == MVT::f64) ? RTLIB::UNE_F64 :
     176           8 :           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
     177          41 :     break;
     178          28 :   case ISD::SETGE:
     179             :   case ISD::SETOGE:
     180          56 :     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
     181          21 :           (VT == MVT::f64) ? RTLIB::OGE_F64 :
     182           9 :           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
     183          28 :     break;
     184          36 :   case ISD::SETLT:
     185             :   case ISD::SETOLT:
     186          72 :     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
     187          29 :           (VT == MVT::f64) ? RTLIB::OLT_F64 :
     188          11 :           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
     189          36 :     break;
     190          28 :   case ISD::SETLE:
     191             :   case ISD::SETOLE:
     192          56 :     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
     193          21 :           (VT == MVT::f64) ? RTLIB::OLE_F64 :
     194           9 :           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
     195          28 :     break;
     196          35 :   case ISD::SETGT:
     197             :   case ISD::SETOGT:
     198          70 :     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
     199          29 :           (VT == MVT::f64) ? RTLIB::OGT_F64 :
     200          18 :           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
     201          35 :     break;
     202          15 :   case ISD::SETUO:
     203          30 :     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
     204           9 :           (VT == MVT::f64) ? RTLIB::UO_F64 :
     205           2 :           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
     206          15 :     break;
     207           5 :   case ISD::SETO:
     208          10 :     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
     209           2 :           (VT == MVT::f64) ? RTLIB::O_F64 :
     210           0 :           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
     211           5 :     break;
     212           5 :   case ISD::SETONE:
     213             :     // SETONE = SETOLT | SETOGT
     214          10 :     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
     215           3 :           (VT == MVT::f64) ? RTLIB::OLT_F64 :
     216           0 :           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
     217          10 :     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
     218           3 :           (VT == MVT::f64) ? RTLIB::OGT_F64 :
     219           0 :           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
     220           5 :     break;
     221           8 :   case ISD::SETUEQ:
     222          16 :     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
     223           5 :           (VT == MVT::f64) ? RTLIB::UO_F64 :
     224           1 :           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
     225          16 :     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
     226           5 :           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
     227           1 :           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
     228           8 :     break;
     229          26 :   default:
     230             :     // Invert CC for unordered comparisons
     231          26 :     ShouldInvertCC = true;
     232          26 :     switch (CCCode) {
     233           5 :     case ISD::SETULT:
     234          10 :       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
     235           3 :             (VT == MVT::f64) ? RTLIB::OGE_F64 :
     236           0 :             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
     237           5 :       break;
     238           8 :     case ISD::SETULE:
     239          16 :       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
     240           6 :             (VT == MVT::f64) ? RTLIB::OGT_F64 :
     241           2 :             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
     242           8 :       break;
     243           6 :     case ISD::SETUGT:
     244          12 :       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
     245           4 :             (VT == MVT::f64) ? RTLIB::OLE_F64 :
     246           1 :             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
     247           6 :       break;
     248           7 :     case ISD::SETUGE:
     249          14 :       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
     250           5 :             (VT == MVT::f64) ? RTLIB::OLT_F64 :
     251           1 :             (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         578 :   EVT RetVT = getCmpLibcallReturnType();
     259         289 :   SDValue Ops[2] = {NewLHS, NewRHS};
     260         289 :   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
     261         578 :                        dl).first;
     262         289 :   NewRHS = DAG.getConstant(0, dl, RetVT);
     263             : 
     264         578 :   CCCode = getCmpLibcallCC(LC1);
     265         289 :   if (ShouldInvertCC)
     266          26 :     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
     267             : 
     268         289 :   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          26 :                          dl).first;
     275          13 :     NewLHS = DAG.getNode(
     276             :         ISD::SETCC, dl,
     277          13 :         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
     278          52 :         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
     279          26 :     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
     280          13 :     NewRHS = SDValue();
     281             :   }
     282         289 : }
     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         138 : unsigned TargetLowering::getJumpTableEncoding() const {
     287             :   // In non-pic modes, just use the address of a block.
     288         138 :   if (!isPositionIndependent())
     289             :     return MachineJumpTableInfo::EK_BlockAddress;
     290             : 
     291             :   // In PIC mode, if the target supports a GPRel32 directive, use it.
     292          36 :   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          10 : 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          10 :   unsigned JTEncoding = getJumpTableEncoding();
     303             : 
     304          10 :   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
     305             :       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
     306          12 :     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         462 : 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         924 :   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
     318             : }
     319             : 
     320             : bool
     321      652739 : TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
     322      652739 :   const TargetMachine &TM = getTargetMachine();
     323      652739 :   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      652739 :   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      649044 :   if (isPositionIndependent())
     332             :     return false;
     333             : 
     334             :   // Otherwise we can do it.
     335        5886 :   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      497867 : bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
     346             :                                             TargetLoweringOpt &TLO) const {
     347      497867 :   SelectionDAG &DAG = TLO.DAG;
     348      995734 :   SDLoc DL(Op);
     349      995734 :   unsigned Opcode = Op.getOpcode();
     350             : 
     351             :   // Do target-specific constant optimization.
     352      497867 :   if (targetShrinkDemandedConstant(Op, Demanded, TLO))
     353           5 :     return TLO.New.getNode();
     354             : 
     355             :   // FIXME: ISD::SELECT, ISD::SELECT_CC
     356      497862 :   switch (Opcode) {
     357             :   default:
     358             :     break;
     359      441039 :   case ISD::XOR:
     360             :   case ISD::AND:
     361             :   case ISD::OR: {
     362     1218865 :     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      336787 :     const APInt &C = Op1C->getAPIntValue();
     368      364947 :     if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
     369             :       return false;
     370             : 
     371      336787 :     if (!C.isSubsetOf(Demanded)) {
     372       21534 :       EVT VT = Op.getValueType();
     373       43068 :       SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
     374       10767 :       SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
     375       10767 :       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     2213404 : 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     2213404 :   SelectionDAG &DAG = TLO.DAG;
     397     4426808 :   SDLoc dl(Op);
     398             : 
     399             :   // Early return, as this function cannot handle vector types.
     400     6640212 :   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     3480793 :   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     1437057 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     411     1437057 :   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
     412     1437057 :   unsigned SmallVTBits = DemandedSize;
     413       20640 :   if (!isPowerOf2_32(SmallVTBits))
     414       41280 :     SmallVTBits = NextPowerOf2(SmallVTBits);
     415     1551474 :   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
     416       40372 :     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
     417       99752 :     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
     418       38016 :         TLI.isZExtFree(SmallVT, Op.getValueType())) {
     419             :       // We found a type with free casts.
     420             :       SDValue X = DAG.getNode(
     421             :           Op.getOpcode(), dl, SmallVT,
     422        4466 :           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
     423       13398 :           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
     424        2233 :       bool NeedZext = DemandedSize > SmallVTBits;
     425             :       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
     426        4466 :                               dl, Op.getValueType(), X);
     427        2233 :       return TLO.CombineTo(Op, Z);
     428             :     }
     429             :   }
     430             :   return false;
     431             : }
     432             : 
     433             : bool
     434        2594 : TargetLowering::SimplifyDemandedBits(SDNode *User, unsigned OpIdx,
     435             :                                      const APInt &Demanded,
     436             :                                      DAGCombinerInfo &DCI,
     437             :                                      TargetLoweringOpt &TLO) const {
     438        5188 :   SDValue Op = User->getOperand(OpIdx);
     439        5188 :   KnownBits Known;
     440             : 
     441        2594 :   if (!SimplifyDemandedBits(Op, Demanded, Known, TLO, 0, true))
     442             :     return false;
     443             : 
     444             : 
     445             :   // Old will not always be the same as Op.  For example:
     446             :   //
     447             :   // Demanded = 0xffffff
     448             :   // Op = i64 truncate (i32 and x, 0xffffff)
     449             :   // In this case simplify demand bits will want to replace the 'and' node
     450             :   // with the value 'x', which will give us:
     451             :   // Old = i32 and x, 0xffffff
     452             :   // New = x
     453         342 :   if (TLO.Old.hasOneUse()) {
     454             :     // For the one use case, we just commit the change.
     455         159 :     DCI.CommitTargetLoweringOpt(TLO);
     456         159 :     return true;
     457             :   }
     458             : 
     459             :   // If Old has more than one use then it must be Op, because the
     460             :   // AssumeSingleUse flag is not propogated to recursive calls of
     461             :   // SimplifyDemanded bits, so the only node with multiple use that
     462             :   // it will attempt to combine will be opt.
     463             :   assert(TLO.Old == Op);
     464             : 
     465          12 :   SmallVector <SDValue, 4> NewOps;
     466          48 :   for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
     467          36 :     if (i == OpIdx) {
     468          12 :       NewOps.push_back(TLO.New);
     469          12 :       continue;
     470             :     }
     471          24 :     NewOps.push_back(User->getOperand(i));
     472             :   }
     473          24 :   TLO.DAG.UpdateNodeOperands(User, NewOps);
     474             :   // Op has less users now, so we may be able to perform additional combines
     475             :   // with it.
     476          12 :   DCI.AddToWorklist(Op.getNode());
     477             :   // User's operands have been updated, so we may be able to do new combines
     478             :   // with it.
     479          12 :   DCI.AddToWorklist(User);
     480          12 :   return true;
     481             : }
     482             : 
     483         186 : bool TargetLowering::SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
     484             :                                           DAGCombinerInfo &DCI) const {
     485             : 
     486         186 :   SelectionDAG &DAG = DCI.DAG;
     487         186 :   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
     488         744 :                         !DCI.isBeforeLegalizeOps());
     489         372 :   KnownBits Known;
     490             : 
     491         186 :   bool Simplified = SimplifyDemandedBits(Op, DemandedMask, Known, TLO);
     492         186 :   if (Simplified)
     493          38 :     DCI.CommitTargetLoweringOpt(TLO);
     494         186 :   return Simplified;
     495             : }
     496             : 
     497             : /// Look at Op. At this point, we know that only the DemandedMask bits of the
     498             : /// result of Op are ever used downstream. If we can use this information to
     499             : /// simplify Op, create a new simplified DAG node and return true, returning the
     500             : /// original and new nodes in Old and New. Otherwise, analyze the expression and
     501             : /// return a mask of Known bits for the expression (used to simplify the
     502             : /// caller).  The Known bits may only be accurate for those bits in the
     503             : /// DemandedMask.
     504     8108478 : bool TargetLowering::SimplifyDemandedBits(SDValue Op,
     505             :                                           const APInt &DemandedMask,
     506             :                                           KnownBits &Known,
     507             :                                           TargetLoweringOpt &TLO,
     508             :                                           unsigned Depth,
     509             :                                           bool AssumeSingleUse) const {
     510     8108478 :   unsigned BitWidth = DemandedMask.getBitWidth();
     511             :   assert(Op.getScalarValueSizeInBits() == BitWidth &&
     512             :          "Mask size mismatches value type size!");
     513    16216956 :   APInt NewMask = DemandedMask;
     514    16216956 :   SDLoc dl(Op);
     515    16216956 :   auto &DL = TLO.DAG.getDataLayout();
     516             : 
     517             :   // Don't know anything.
     518     8108478 :   Known = KnownBits(BitWidth);
     519             : 
     520             :   // Other users may use these bits.
     521    11302019 :   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
     522     3192602 :     if (Depth != 0) {
     523             :       // If not at the root, Just compute the Known bits to
     524             :       // simplify things downstream.
     525     2521013 :       TLO.DAG.computeKnownBits(Op, Known, Depth);
     526     2521013 :       return false;
     527             :     }
     528             :     // If this is the root being simplified, allow it to have multiple uses,
     529             :     // just set the NewMask to all bits.
     530     2014767 :     NewMask = APInt::getAllOnesValue(BitWidth);
     531     4915876 :   } else if (DemandedMask == 0) {
     532             :     // Not demanding any bits from Op.
     533        4664 :     if (!Op.isUndef())
     534        4167 :       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
     535             :     return false;
     536     4913544 :   } else if (Depth == 6) {        // Limit search depth.
     537             :     return false;
     538             :   }
     539             : 
     540    16731486 :   KnownBits Known2, KnownOut;
     541    11154324 :   switch (Op.getOpcode()) {
     542     1037010 :   case ISD::Constant:
     543             :     // We know all of the bits for a constant!
     544     2074020 :     Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
     545     6222060 :     Known.Zero = ~Known.One;
     546     1037010 :     return false;   // Don't fall through, will infinitely loop.
     547       42154 :   case ISD::BUILD_VECTOR:
     548             :     // Collect the known bits that are shared by every constant vector element.
     549       42154 :     Known.Zero.setAllBits(); Known.One.setAllBits();
     550      214617 :     for (SDValue SrcOp : Op->ops()) {
     551        2799 :       if (!isa<ConstantSDNode>(SrcOp)) {
     552             :         // We can only handle all constant values - bail out with no known bits.
     553        2799 :         Known = KnownBits(BitWidth);
     554             :         return false;
     555             :       }
     556      260618 :       Known2.One = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
     557      651545 :       Known2.Zero = ~Known2.One;
     558             : 
     559             :       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
     560      130309 :       if (Known2.One.getBitWidth() != BitWidth) {
     561             :         assert(Known2.getBitWidth() > BitWidth &&
     562             :                "Expected BUILD_VECTOR implicit truncation");
     563       10302 :         Known2 = Known2.trunc(BitWidth);
     564             :       }
     565             : 
     566             :       // Known bits are the values that are shared by every element.
     567             :       // TODO: support per-element known bits.
     568      260618 :       Known.One &= Known2.One;
     569      260618 :       Known.Zero &= Known2.Zero;
     570        2799 :     }
     571             :     return false;   // Don't fall through, will infinitely loop.
     572      233378 :   case ISD::AND:
     573             :     // If the RHS is a constant, check to see if the LHS would be zero without
     574             :     // using the bits from the RHS.  Below, we use knowledge about the RHS to
     575             :     // simplify the LHS, here we're using information from the LHS to simplify
     576             :     // the RHS.
     577      466756 :     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op.getOperand(1))) {
     578      375710 :       SDValue Op0 = Op.getOperand(0);
     579      313908 :       KnownBits LHSKnown;
     580             :       // Do not increment Depth here; that can cause an infinite loop.
     581      187855 :       TLO.DAG.computeKnownBits(Op0, LHSKnown, Depth);
     582             :       // If the LHS already has zeros where RHSC does, this and is dead.
     583     2442115 :       if ((LHSKnown.Zero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
     584      112869 :         return TLO.CombineTo(Op, Op0);
     585             : 
     586             :       // If any of the set bits in the RHS are known zero on the LHS, shrink
     587             :       // the constant.
     588      820728 :       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & NewMask, TLO))
     589             :         return true;
     590             : 
     591             :       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
     592             :       // constant, but if this 'and' is only clearing bits that were just set by
     593             :       // the xor, then this 'and' can be eliminated by shrinking the mask of
     594             :       // the xor. For example, for a 32-bit X:
     595             :       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
     596      252675 :       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
     597      379101 :           LHSKnown.One == ~RHSC->getAPIntValue()) {
     598           9 :         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(),
     599          36 :                                       Op0.getOperand(0), Op.getOperand(1));
     600           9 :         return TLO.CombineTo(Op, Xor);
     601             :       }
     602             :     }
     603             : 
     604      343152 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
     605             :       return true;
     606             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     607     1372240 :     if (SimplifyDemandedBits(Op.getOperand(0), ~Known.Zero & NewMask,
     608             :                              Known2, TLO, Depth+1))
     609             :       return true;
     610             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     611             : 
     612             :     // If all of the demanded bits are known one on one side, return the other.
     613             :     // These bits cannot contribute to the result of the 'and'.
     614      999060 :     if (NewMask.isSubsetOf(Known2.Zero | Known.One))
     615         117 :       return TLO.CombineTo(Op, Op.getOperand(0));
     616      998826 :     if (NewMask.isSubsetOf(Known.Zero | Known2.One))
     617        8385 :       return TLO.CombineTo(Op, Op.getOperand(1));
     618             :     // If all of the demanded bits in the inputs are known zeros, return zero.
     619      982056 :     if (NewMask.isSubsetOf(Known.Zero | Known2.Zero))
     620           0 :       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
     621             :     // If the RHS is a constant, see if we can simplify it.
     622      982056 :     if (ShrinkDemandedConstant(Op, ~Known2.Zero & NewMask, TLO))
     623             :       return true;
     624             :     // If the operation can be done in a smaller type, do so.
     625      163676 :     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
     626             :       return true;
     627             : 
     628             :     // Output known-1 bits are only known if set in both the LHS & RHS.
     629      323754 :     Known.One &= Known2.One;
     630             :     // Output known-0 are known to be clear if zero in either the LHS | RHS.
     631      161877 :     Known.Zero |= Known2.Zero;
     632             :     break;
     633      116301 :   case ISD::OR:
     634      232602 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
     635             :       return true;
     636             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     637      916608 :     if (SimplifyDemandedBits(Op.getOperand(0), ~Known.One & NewMask,
     638             :                              Known2, TLO, Depth+1))
     639             :       return true;
     640             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     641             : 
     642             :     // If all of the demanded bits are known zero on one side, return the other.
     643             :     // These bits cannot contribute to the result of the 'or'.
     644      676146 :     if (NewMask.isSubsetOf(Known2.One | Known.Zero))
     645         426 :       return TLO.CombineTo(Op, Op.getOperand(0));
     646      675294 :     if (NewMask.isSubsetOf(Known.One | Known2.Zero))
     647        2940 :       return TLO.CombineTo(Op, Op.getOperand(1));
     648             :     // If the RHS is a constant, see if we can simplify it.
     649      111569 :     if (ShrinkDemandedConstant(Op, NewMask, TLO))
     650             :       return true;
     651             :     // If the operation can be done in a smaller type, do so.
     652      111544 :     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
     653             :       return true;
     654             : 
     655             :     // Output known-0 bits are only known if clear in both the LHS & RHS.
     656      222900 :     Known.Zero &= Known2.Zero;
     657             :     // Output known-1 are known to be set if set in either the LHS | RHS.
     658      111450 :     Known.One |= Known2.One;
     659             :     break;
     660       94937 :   case ISD::XOR: {
     661      189874 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
     662             :       return true;
     663             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     664      189734 :     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, Known2, TLO, Depth+1))
     665             :       return true;
     666             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     667             : 
     668             :     // If all of the demanded bits are known zero on one side, return the other.
     669             :     // These bits cannot contribute to the result of the 'xor'.
     670      189586 :     if (NewMask.isSubsetOf(Known.Zero))
     671          21 :       return TLO.CombineTo(Op, Op.getOperand(0));
     672       94786 :     if (NewMask.isSubsetOf(Known2.Zero))
     673           3 :       return TLO.CombineTo(Op, Op.getOperand(1));
     674             :     // If the operation can be done in a smaller type, do so.
     675       94785 :     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
     676             :       return true;
     677             : 
     678             :     // If all of the unknown bits are known to be zero on one side or the other
     679             :     // (but not both) turn this into an *inclusive* or.
     680             :     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
     681     1137012 :     if ((NewMask & ~Known.Zero & ~Known2.Zero) == 0)
     682         165 :       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
     683          66 :                                                Op.getOperand(0),
     684          99 :                                                Op.getOperand(1)));
     685             : 
     686             :     // Output known-0 bits are known if clear or set in both the LHS & RHS.
     687     1136616 :     KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
     688             :     // Output known-1 are known to be set if set in only one of the LHS, RHS.
     689     1136616 :     KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
     690             : 
     691             :     // If all of the demanded bits on one side are known, and all of the set
     692             :     // bits on that side are also known to be set on the other side, turn this
     693             :     // into an AND, as we know the bits will be cleared.
     694             :     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
     695             :     // NB: it is okay if more bits are known than are requested
     696      568308 :     if (NewMask.isSubsetOf(Known.Zero|Known.One)) { // all known on one side
     697      150950 :       if (Known.One == Known2.One) { // set bits are the same on both sides
     698           6 :         EVT VT = Op.getValueType();
     699          21 :         SDValue ANDC = TLO.DAG.getConstant(~Known.One & NewMask, dl, VT);
     700          12 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
     701           9 :                                                  Op.getOperand(0), ANDC));
     702             :       }
     703             :     }
     704             : 
     705             :     // If the RHS is a constant, see if we can change it. Don't alter a -1
     706             :     // constant because that's a 'not' op, and that is better for combining and
     707             :     // codegen.
     708      189430 :     ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1));
     709      167226 :     if (C && !C->isAllOnesValue()) {
     710       87078 :       if (NewMask.isSubsetOf(C->getAPIntValue())) {
     711             :         // We're flipping all demanded bits. Flip the undemanded bits too.
     712         387 :         SDValue New = TLO.DAG.getNOT(dl, Op.getOperand(0), Op.getValueType());
     713         129 :         return TLO.CombineTo(Op, New);
     714             :       }
     715             :       // If we can't turn this into a 'not', try to shrink the constant.
     716       28897 :       if (ShrinkDemandedConstant(Op, NewMask, TLO))
     717             :         return true;
     718             :     }
     719             : 
     720       94573 :     Known = std::move(KnownOut);
     721       94573 :     break;
     722             :   }
     723       52031 :   case ISD::SELECT:
     724      104062 :     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, Known, TLO, Depth+1))
     725             :       return true;
     726      104014 :     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known2, TLO, Depth+1))
     727             :       return true;
     728             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     729             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     730             : 
     731             :     // If the operands are constants, see if we can simplify them.
     732       51979 :     if (ShrinkDemandedConstant(Op, NewMask, TLO))
     733             :       return true;
     734             : 
     735             :     // Only known if known in both the LHS and RHS.
     736      103958 :     Known.One &= Known2.One;
     737       51979 :     Known.Zero &= Known2.Zero;
     738             :     break;
     739        3897 :   case ISD::SELECT_CC:
     740        7794 :     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, Known, TLO, Depth+1))
     741             :       return true;
     742        7794 :     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, Known2, TLO, Depth+1))
     743             :       return true;
     744             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     745             :     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
     746             : 
     747             :     // If the operands are constants, see if we can simplify them.
     748        3897 :     if (ShrinkDemandedConstant(Op, NewMask, TLO))
     749             :       return true;
     750             : 
     751             :     // Only known if known in both the LHS and RHS.
     752        7794 :     Known.One &= Known2.One;
     753        3897 :     Known.Zero &= Known2.Zero;
     754             :     break;
     755       53483 :   case ISD::SETCC: {
     756      106966 :     SDValue Op0 = Op.getOperand(0);
     757      106966 :     SDValue Op1 = Op.getOperand(1);
     758      160449 :     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
     759             :     // If (1) we only need the sign-bit, (2) the setcc operands are the same
     760             :     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
     761             :     // -1, we may be able to bypass the setcc.
     762       54008 :     if (NewMask.isSignMask() && Op0.getScalarValueSizeInBits() == BitWidth &&
     763        1050 :         getBooleanContents(Op.getValueType()) ==
     764             :             BooleanContent::ZeroOrNegativeOneBooleanContent) {
     765             :       // If we're testing X < 0, then this compare isn't needed - just use X!
     766             :       // FIXME: We're limiting to integer types here, but this should also work
     767             :       // if we don't care about FP signed-zero. The use of SETLT with FP means
     768             :       // that we don't care about NaNs.
     769        1207 :       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
     770         162 :           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
     771          30 :         return TLO.CombineTo(Op, Op0);
     772             : 
     773             :       // TODO: Should we check for other forms of sign-bit comparisons?
     774             :       // Examples: X <= -1, X >= 0
     775             :     }
     776      106906 :     if (getBooleanContents(Op0.getValueType()) ==
     777       53453 :             TargetLowering::ZeroOrOneBooleanContent &&
     778             :         BitWidth > 1)
     779       18404 :       Known.Zero.setBitsFrom(1);
     780       53453 :     break;
     781             :   }
     782      345932 :   case ISD::SHL:
     783     1029806 :     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
     784      337942 :       unsigned ShAmt = SA->getZExtValue();
     785      675884 :       SDValue InOp = Op.getOperand(0);
     786             : 
     787             :       // If the shift count is an invalid immediate, don't do anything.
     788      337942 :       if (ShAmt >= BitWidth)
     789             :         break;
     790             : 
     791             :       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
     792             :       // single shift.  We can do this if the bottom bits (which are shifted
     793             :       // out) are never demanded.
     794      675864 :       if (InOp.getOpcode() == ISD::SRL &&
     795        6716 :           isa<ConstantSDNode>(InOp.getOperand(1))) {
     796       13272 :         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
     797        5624 :           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
     798        1406 :           unsigned Opc = ISD::SHL;
     799        1406 :           int Diff = ShAmt-C1;
     800        1406 :           if (Diff < 0) {
     801          32 :             Diff = -Diff;
     802          32 :             Opc = ISD::SRL;
     803             :           }
     804             : 
     805             :           SDValue NewSA =
     806        4218 :             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
     807        2812 :           EVT VT = Op.getValueType();
     808        5624 :           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
     809        4218 :                                                    InOp.getOperand(0), NewSA));
     810             :         }
     811             :       }
     812             : 
     813      673052 :       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), Known, TLO, Depth+1))
     814             :         return true;
     815             : 
     816             :       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
     817             :       // are not demanded. This will likely allow the anyext to be folded away.
     818      328062 :       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
     819       20758 :         SDValue InnerOp = InOp.getOperand(0);
     820       20758 :         EVT InnerVT = InnerOp.getValueType();
     821       10379 :         unsigned InnerBits = InnerVT.getSizeInBits();
     822       10660 :         if (ShAmt < InnerBits && NewMask.getActiveBits() <= InnerBits &&
     823          47 :             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
     824           4 :           EVT ShTy = getShiftAmountTy(InnerVT, DL);
     825          16 :           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
     826           0 :             ShTy = InnerVT;
     827             :           SDValue NarrowShl =
     828           4 :             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
     829           4 :                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
     830             :           return
     831          12 :             TLO.CombineTo(Op,
     832           4 :                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
     833           4 :                                           NarrowShl));
     834             :         }
     835             :         // Repeat the SHL optimization above in cases where an extension
     836             :         // intervenes: (shl (anyext (shr x, c1)), c2) to
     837             :         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
     838             :         // aren't demanded (as above) and that the shifted upper c1 bits of
     839             :         // x aren't demanded.
     840       20736 :         if (InOp.hasOneUse() &&
     841       10983 :             InnerOp.getOpcode() == ISD::SRL &&
     842       10997 :             InnerOp.hasOneUse() &&
     843        1244 :             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
     844             :           unsigned InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
     845        2356 :             ->getZExtValue();
     846             :           if (InnerShAmt < ShAmt &&
     847         589 :               InnerShAmt < InnerBits &&
     848        1203 :               NewMask.getActiveBits() <= (InnerBits - InnerShAmt + ShAmt) &&
     849          25 :               NewMask.countTrailingZeros() >= ShAmt) {
     850             :             SDValue NewSA =
     851          38 :               TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
     852          57 :                                   Op.getOperand(1).getValueType());
     853          38 :             EVT VT = Op.getValueType();
     854          19 :             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
     855          38 :                                              InnerOp.getOperand(0));
     856          57 :             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
     857          19 :                                                      NewExt, NewSA));
     858             :           }
     859             :         }
     860             :       }
     861             : 
     862      328039 :       Known.Zero <<= SA->getZExtValue();
     863      328039 :       Known.One  <<= SA->getZExtValue();
     864             :       // low bits known zero.
     865      656078 :       Known.Zero.setLowBits(SA->getZExtValue());
     866             :     }
     867             :     break;
     868      211741 :   case ISD::SRL:
     869      627682 :     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
     870      408400 :       EVT VT = Op.getValueType();
     871      204200 :       unsigned ShAmt = SA->getZExtValue();
     872      204200 :       unsigned VTSize = VT.getSizeInBits();
     873      408400 :       SDValue InOp = Op.getOperand(0);
     874             : 
     875             :       // If the shift count is an invalid immediate, don't do anything.
     876      204200 :       if (ShAmt >= BitWidth)
     877             :         break;
     878             : 
     879      396498 :       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      408396 :       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      408396 :       if (InOp.getOpcode() == ISD::SHL &&
     890        2782 :           isa<ConstantSDNode>(InOp.getOperand(1))) {
     891        3332 :         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
     892        2816 :           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
     893         704 :           unsigned Opc = ISD::SRL;
     894         704 :           int Diff = ShAmt-C1;
     895         704 :           if (Diff < 0) {
     896           0 :             Diff = -Diff;
     897           0 :             Opc = ISD::SHL;
     898             :           }
     899             : 
     900             :           SDValue NewSA =
     901        2112 :             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
     902        2816 :           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
     903        2112 :                                                    InOp.getOperand(0), NewSA));
     904             :         }
     905             :       }
     906             : 
     907             :       // Compute the new bits that are at the top now.
     908      203494 :       if (SimplifyDemandedBits(InOp, InDemandedMask, Known, TLO, Depth+1))
     909             :         return true;
     910             :       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     911      384600 :       Known.Zero.lshrInPlace(ShAmt);
     912      384600 :       Known.One.lshrInPlace(ShAmt);
     913             : 
     914      384600 :       Known.Zero.setHighBits(ShAmt);  // High bits known zero.
     915             :     }
     916             :     break;
     917       30179 :   case ISD::SRA:
     918             :     // If this is an arithmetic shift right and only the low-bit is set, we can
     919             :     // always convert this into a logical shr, even if the shift amount is
     920             :     // variable.  The low bit of the shift cannot be an input sign bit unless
     921             :     // the shift amount is >= the size of the datatype, which is undefined.
     922       30179 :     if (NewMask.isOneValue())
     923         120 :       return TLO.CombineTo(Op,
     924          30 :                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
     925         120 :                                            Op.getOperand(0), Op.getOperand(1)));
     926             : 
     927       88928 :     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
     928       57260 :       EVT VT = Op.getValueType();
     929       28630 :       unsigned ShAmt = SA->getZExtValue();
     930             : 
     931             :       // If the shift count is an invalid immediate, don't do anything.
     932       28630 :       if (ShAmt >= BitWidth)
     933             :         break;
     934             : 
     935       53948 :       APInt InDemandedMask = (NewMask << ShAmt);
     936             : 
     937             :       // If the shift is exact, then it does demand the low bits (and knows that
     938             :       // they are zero).
     939       57260 :       if (Op->getFlags().hasExact())
     940             :         InDemandedMask.setLowBits(ShAmt);
     941             : 
     942             :       // If any of the demanded bits are produced by the sign extension, we also
     943             :       // demand the input sign bit.
     944       28630 :       if (NewMask.countLeadingZeros() < ShAmt)
     945       28304 :         InDemandedMask.setSignBit();
     946             : 
     947       57260 :       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, Known, TLO,
     948             :                                Depth+1))
     949        3312 :         return true;
     950             :       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
     951       51406 :       Known.Zero.lshrInPlace(ShAmt);
     952       51406 :       Known.One.lshrInPlace(ShAmt);
     953             : 
     954             :       // If the input sign bit is known to be zero, or if none of the top bits
     955             :       // are demanded, turn this into an unsigned shift right.
     956       77097 :       if (Known.Zero[BitWidth - ShAmt - 1] ||
     957       25691 :           NewMask.countLeadingZeros() >= ShAmt) {
     958         323 :         SDNodeFlags Flags;
     959         969 :         Flags.setExact(Op->getFlags().hasExact());
     960         323 :         return TLO.CombineTo(Op,
     961         969 :                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
     962         969 :                                              Op.getOperand(1), Flags));
     963             :       }
     964             : 
     965       25380 :       int Log2 = NewMask.exactLogBase2();
     966       25380 :       if (Log2 >= 0) {
     967             :         // The bit must come from the sign.
     968             :         SDValue NewSA =
     969         124 :           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
     970         186 :                               Op.getOperand(1).getValueType());
     971         248 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
     972         186 :                                                  Op.getOperand(0), NewSA));
     973             :       }
     974             : 
     975       50636 :       if (Known.One[BitWidth - ShAmt - 1])
     976             :         // New bits are known one.
     977           2 :         Known.One.setHighBits(ShAmt);
     978             :     }
     979             :     break;
     980       51904 :   case ISD::SIGN_EXTEND_INREG: {
     981      155712 :     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
     982             : 
     983       51904 :     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
     984             :     // If we only care about the highest bit, don't bother shifting right.
     985       51904 :     if (MsbMask == NewMask) {
     986         148 :       unsigned ShAmt = ExVT.getScalarSizeInBits();
     987         296 :       SDValue InOp = Op.getOperand(0);
     988         444 :       unsigned VTBits = Op->getValueType(0).getScalarSizeInBits();
     989             :       bool AlreadySignExtended =
     990         148 :         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
     991             :       // However if the input is already sign extended we expect the sign
     992             :       // extension to be dropped altogether later and do not simplify.
     993         148 :       if (!AlreadySignExtended) {
     994             :         // Compute the correct shift amount type, which must be getShiftAmountTy
     995             :         // for scalar types after legalization.
     996         296 :         EVT ShiftAmtTy = Op.getValueType();
     997         295 :         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
     998           3 :           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
     999             : 
    1000         148 :         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
    1001         148 :                                                ShiftAmtTy);
    1002         592 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
    1003             :                                                  Op.getValueType(), InOp,
    1004         148 :                                                  ShiftAmt));
    1005             :       }
    1006             :     }
    1007             : 
    1008             :     // Sign extension.  Compute the demanded bits in the result that are not
    1009             :     // present in the input.
    1010             :     APInt NewBits =
    1011             :       APInt::getHighBitsSet(BitWidth,
    1012       51756 :                             BitWidth - ExVT.getScalarSizeInBits());
    1013             : 
    1014             :     // If none of the extended bits are demanded, eliminate the sextinreg.
    1015      207024 :     if ((NewBits & NewMask) == 0)
    1016        1317 :       return TLO.CombineTo(Op, Op.getOperand(0));
    1017             : 
    1018             :     APInt InSignBit =
    1019      153951 :       APInt::getSignMask(ExVT.getScalarSizeInBits()).zext(BitWidth);
    1020             :     APInt InputDemandedBits =
    1021      102634 :       APInt::getLowBitsSet(BitWidth,
    1022             :                            ExVT.getScalarSizeInBits()) &
    1023       51317 :       NewMask;
    1024             : 
    1025             :     // Since the sign extended bits are demanded, we know that the sign
    1026             :     // bit is demanded.
    1027       51317 :     InputDemandedBits |= InSignBit;
    1028             : 
    1029      102634 :     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
    1030             :                              Known, TLO, Depth+1))
    1031        2072 :       return true;
    1032             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1033             : 
    1034             :     // If the sign bit of the input is known set or clear, then we know the
    1035             :     // top bits of the result.
    1036             : 
    1037             :     // If the input sign bit is known zero, convert this into a zero extension.
    1038       98492 :     if (Known.Zero.intersects(InSignBit))
    1039           2 :       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
    1040           3 :                                    Op.getOperand(0), dl, ExVT.getScalarType()));
    1041             : 
    1042       98490 :     if (Known.One.intersects(InSignBit)) {    // Input sign bit known set
    1043           4 :       Known.One |= NewBits;
    1044          10 :       Known.Zero &= ~NewBits;
    1045             :     } else {                       // Input sign bit unknown
    1046      246215 :       Known.Zero &= ~NewBits;
    1047      246215 :       Known.One &= ~NewBits;
    1048             :     }
    1049       49245 :     break;
    1050             :   }
    1051        6139 :   case ISD::BUILD_PAIR: {
    1052       18417 :     EVT HalfVT = Op.getOperand(0).getValueType();
    1053        6139 :     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
    1054             : 
    1055       12278 :     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
    1056       12278 :     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
    1057             : 
    1058       12278 :     KnownBits KnownLo, KnownHi;
    1059             : 
    1060       12278 :     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
    1061        1056 :       return true;
    1062             : 
    1063       11984 :     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
    1064             :       return true;
    1065             : 
    1066       25415 :     Known.Zero = KnownLo.Zero.zext(BitWidth) |
    1067       20332 :                 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
    1068             : 
    1069       25415 :     Known.One = KnownLo.One.zext(BitWidth) |
    1070       20332 :                KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
    1071        5083 :     break;
    1072             :   }
    1073      208941 :   case ISD::ZERO_EXTEND: {
    1074      417882 :     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
    1075      208941 :     APInt InMask = NewMask.trunc(OperandBitWidth);
    1076             : 
    1077             :     // If none of the top bits are demanded, convert this into an any_extend.
    1078             :     APInt NewBits =
    1079      626823 :       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
    1080      208941 :     if (!NewBits.intersects(NewMask))
    1081        6025 :       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
    1082             :                                                Op.getValueType(),
    1083        3615 :                                                Op.getOperand(0)));
    1084             : 
    1085      415472 :     if (SimplifyDemandedBits(Op.getOperand(0), InMask, Known, TLO, Depth+1))
    1086             :       return true;
    1087             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1088      207258 :     Known = Known.zext(BitWidth);
    1089      414516 :     Known.Zero |= NewBits;
    1090      207258 :     break;
    1091             :   }
    1092       10781 :   case ISD::SIGN_EXTEND: {
    1093       32343 :     EVT InVT = Op.getOperand(0).getValueType();
    1094       10781 :     unsigned InBits = InVT.getScalarSizeInBits();
    1095       10781 :     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
    1096       10781 :     APInt InSignBit = APInt::getOneBitSet(BitWidth, InBits - 1);
    1097       53905 :     APInt NewBits   = ~InMask & NewMask;
    1098             : 
    1099             :     // If none of the top bits are demanded, convert this into an any_extend.
    1100       10781 :     if (NewBits == 0)
    1101        2440 :       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
    1102             :                                               Op.getValueType(),
    1103        1464 :                                               Op.getOperand(0)));
    1104             : 
    1105             :     // Since some of the sign extended bits are demanded, we know that the sign
    1106             :     // bit is demanded.
    1107       30879 :     APInt InDemandedBits = InMask & NewMask;
    1108       10293 :     InDemandedBits |= InSignBit;
    1109       30879 :     InDemandedBits = InDemandedBits.trunc(InBits);
    1110             : 
    1111       20586 :     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, Known, TLO,
    1112             :                              Depth+1))
    1113             :       return true;
    1114       10238 :     Known = Known.zext(BitWidth);
    1115             : 
    1116             :     // If the sign bit is known zero, convert this to a zero extend.
    1117       20476 :     if (Known.Zero.intersects(InSignBit))
    1118       10540 :       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
    1119             :                                                Op.getValueType(),
    1120        6324 :                                                Op.getOperand(0)));
    1121             : 
    1122             :     // If the sign bit is known one, the top bits match.
    1123       16260 :     if (Known.One.intersects(InSignBit)) {
    1124           0 :       Known.One |= NewBits;
    1125             :       assert((Known.Zero & NewBits) == 0);
    1126             :     } else {   // Otherwise, top bits aren't known.
    1127             :       assert((Known.One & NewBits) == 0);
    1128             :       assert((Known.Zero & NewBits) == 0);
    1129             :     }
    1130        8130 :     break;
    1131             :   }
    1132       27004 :   case ISD::ANY_EXTEND: {
    1133       54008 :     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
    1134       27004 :     APInt InMask = NewMask.trunc(OperandBitWidth);
    1135       54008 :     if (SimplifyDemandedBits(Op.getOperand(0), InMask, Known, TLO, Depth+1))
    1136         872 :       return true;
    1137             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1138       26568 :     Known = Known.zext(BitWidth);
    1139       26568 :     break;
    1140             :   }
    1141      152774 :   case ISD::TRUNCATE: {
    1142             :     // Simplify the input, using demanded bit information, and compute the known
    1143             :     // zero/one bits live out.
    1144      305548 :     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
    1145      152774 :     APInt TruncMask = NewMask.zext(OperandBitWidth);
    1146      305548 :     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, Known, TLO, Depth+1))
    1147       11179 :       return true;
    1148      142914 :     Known = Known.trunc(BitWidth);
    1149             : 
    1150             :     // If the input is only used by this truncate, see if we can shrink it based
    1151             :     // on the known demanded bits.
    1152      393863 :     if (Op.getOperand(0).getNode()->hasOneUse()) {
    1153      216070 :       SDValue In = Op.getOperand(0);
    1154      216070 :       switch (In.getOpcode()) {
    1155      106716 :       default: break;
    1156       34575 :       case ISD::SRL:
    1157             :         // Shrink SRL by a constant if none of the high bits shifted in are
    1158             :         // demanded.
    1159       67755 :         if (TLO.LegalTypes() &&
    1160       66360 :             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
    1161             :           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
    1162             :           // undesirable.
    1163             :           break;
    1164       91332 :         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
    1165             :         if (!ShAmt)
    1166             :           break;
    1167       60724 :         SDValue Shift = In.getOperand(1);
    1168       30362 :         if (TLO.LegalTypes()) {
    1169       29017 :           uint64_t ShVal = ShAmt->getZExtValue();
    1170       58034 :           Shift = TLO.DAG.getConstant(ShVal, dl,
    1171       58034 :                                       getShiftAmountTy(Op.getValueType(), DL));
    1172             :         }
    1173             : 
    1174       30362 :         if (ShAmt->getZExtValue() < BitWidth) {
    1175             :           APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
    1176        3673 :                                                  OperandBitWidth - BitWidth);
    1177        4992 :           HighBits.lshrInPlace(ShAmt->getZExtValue());
    1178        7488 :           HighBits = HighBits.trunc(BitWidth);
    1179             : 
    1180       12480 :           if (!(HighBits & NewMask)) {
    1181             :             // None of the shifted in bits are needed.  Add a truncate of the
    1182             :             // shift input, then shift it.
    1183        1319 :             SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
    1184             :                                                Op.getValueType(),
    1185        3957 :                                                In.getOperand(0));
    1186        5276 :             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
    1187             :                                                      Op.getValueType(),
    1188             :                                                      NewTrunc,
    1189        1319 :                                                      Shift));
    1190             :           }
    1191             :         }
    1192             :         break;
    1193             :       }
    1194             :     }
    1195             : 
    1196             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1197      141595 :     break;
    1198             :   }
    1199       35559 :   case ISD::AssertZext: {
    1200             :     // AssertZext demands all of the high bits, plus any of the low bits
    1201             :     // demanded by its users.
    1202      106677 :     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
    1203             :     APInt InMask = APInt::getLowBitsSet(BitWidth,
    1204       35559 :                                         VT.getSizeInBits());
    1205      284472 :     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
    1206             :                              Known, TLO, Depth+1))
    1207           0 :       return true;
    1208             :     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
    1209             : 
    1210      177795 :     Known.Zero |= ~InMask;
    1211       35559 :     break;
    1212             :   }
    1213       74234 :   case ISD::BITCAST:
    1214             :     // If this is an FP->Int bitcast and if the sign bit is the only
    1215             :     // thing demanded, turn this into a FGETSIGN.
    1216      156931 :     if (!TLO.LegalOperations() &&
    1217      102666 :         !Op.getValueType().isVector() &&
    1218       88806 :         !Op.getOperand(0).getValueType().isVector() &&
    1219      226302 :         NewMask == APInt::getSignMask(Op.getValueSizeInBits()) &&
    1220         124 :         Op.getOperand(0).getValueType().isFloatingPoint()) {
    1221          93 :       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
    1222          93 :       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
    1223          38 :       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
    1224          15 :            Op.getOperand(0).getValueType() != MVT::f128) {
    1225             :         // Cannot eliminate/lower SHL for f128 yet.
    1226          10 :         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
    1227             :         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
    1228             :         // place.  We expect the SHL to be eliminated by other optimizations.
    1229          15 :         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
    1230           5 :         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
    1231           5 :         if (!OpVTLegal && OpVTSizeInBits > 32)
    1232           0 :           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
    1233           5 :         unsigned ShVal = Op.getValueSizeInBits() - 1;
    1234          10 :         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
    1235          20 :         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
    1236             :                                                  Op.getValueType(),
    1237           5 :                                                  Sign, ShAmt));
    1238             :       }
    1239             :     }
    1240             :     break;
    1241     1847527 :   case ISD::ADD:
    1242             :   case ISD::MUL:
    1243             :   case ISD::SUB: {
    1244             :     // Add, Sub, and Mul don't demand any bits in positions beyond that
    1245             :     // of the highest bit demanded of them.
    1246             :     APInt LoMask = APInt::getLowBitsSet(BitWidth,
    1247     3690620 :                                         BitWidth - NewMask.countLeadingZeros());
    1248     5540278 :     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, Known2, TLO, Depth+1) ||
    1249     5536150 :         SimplifyDemandedBits(Op.getOperand(1), LoMask, Known2, TLO, Depth+1) ||
    1250             :         // See if the operation should be performed at a smaller bit width.
    1251     1843399 :         ShrinkDemandedOp(Op, BitWidth, NewMask, TLO)) {
    1252        8868 :       SDNodeFlags Flags = Op.getNode()->getFlags();
    1253        4434 :       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
    1254             :         // Disable the nsw and nuw flags. We can no longer guarantee that we
    1255             :         // won't wrap after simplification.
    1256         301 :         Flags.setNoSignedWrap(false);
    1257         301 :         Flags.setNoUnsignedWrap(false);
    1258         301 :         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(),
    1259         903 :                                         Op.getOperand(0), Op.getOperand(1),
    1260         903 :                                         Flags);
    1261         301 :         return TLO.CombineTo(Op, NewOp);
    1262             :       }
    1263             :       return true;
    1264             :     }
    1265             :     LLVM_FALLTHROUGH;
    1266             :   }
    1267             :   default:
    1268             :     // Just use computeKnownBits to compute output bits.
    1269     2784349 :     TLO.DAG.computeKnownBits(Op, Known, Depth);
    1270     2784349 :     break;
    1271             :   }
    1272             : 
    1273             :   // If we know the value of all of the demanded bits, return this as a
    1274             :   // constant.
    1275    26231784 :   if (NewMask.isSubsetOf(Known.Zero|Known.One)) {
    1276             :     // Avoid folding to a constant if any OpaqueConstant is involved.
    1277        4930 :     const SDNode *N = Op.getNode();
    1278        4930 :     for (SDNodeIterator I = SDNodeIterator::begin(N),
    1279       18458 :          E = SDNodeIterator::end(N); I != E; ++I) {
    1280       17200 :       SDNode *Op = *I;
    1281        5087 :       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
    1282        5087 :         if (C->isOpaque())
    1283             :           return false;
    1284             :     }
    1285        9856 :     return TLO.CombineTo(Op,
    1286        9856 :                          TLO.DAG.getConstant(Known.One, dl, Op.getValueType()));
    1287             :   }
    1288             : 
    1289             :   return false;
    1290             : }
    1291             : 
    1292             : /// Determine which of the bits specified in Mask are known to be either zero or
    1293             : /// one and return them in the Known.
    1294       55949 : void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
    1295             :                                                    KnownBits &Known,
    1296             :                                                    const APInt &DemandedElts,
    1297             :                                                    const SelectionDAG &DAG,
    1298             :                                                    unsigned Depth) const {
    1299             :   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
    1300             :           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
    1301             :           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
    1302             :           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
    1303             :          "Should use MaskedValueIsZero if you don't know whether Op"
    1304             :          " is a target node!");
    1305       55949 :   Known.resetAll();
    1306       55949 : }
    1307             : 
    1308             : /// This method can be implemented by targets that want to expose additional
    1309             : /// information about sign bits to the DAG Combiner.
    1310        1221 : unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
    1311             :                                                          const APInt &,
    1312             :                                                          const SelectionDAG &,
    1313             :                                                          unsigned Depth) const {
    1314             :   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
    1315             :           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
    1316             :           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
    1317             :           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
    1318             :          "Should use ComputeNumSignBits if you don't know whether Op"
    1319             :          " is a target node!");
    1320        1221 :   return 1;
    1321             : }
    1322             : 
    1323             : // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
    1324             : // work with truncating build vectors and vectors with elements of less than
    1325             : // 8 bits.
    1326       76467 : bool TargetLowering::isConstTrueVal(const SDNode *N) const {
    1327       76467 :   if (!N)
    1328             :     return false;
    1329             : 
    1330       76467 :   APInt CVal;
    1331       76467 :   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
    1332       57927 :     CVal = CN->getAPIntValue();
    1333        2528 :   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
    1334        2528 :     auto *CN = BV->getConstantSplatNode();
    1335        2528 :     if (!CN)
    1336             :       return false;
    1337             : 
    1338             :     // If this is a truncating build vector, truncate the splat value.
    1339             :     // Otherwise, we may fail to match the expected values below.
    1340        7179 :     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
    1341        4786 :     CVal = CN->getAPIntValue();
    1342        2393 :     if (BVEltWidth < CVal.getBitWidth())
    1343        1095 :       CVal = CVal.trunc(BVEltWidth);
    1344             :   } else {
    1345             :     return false;
    1346             :   }
    1347             : 
    1348      120640 :   switch (getBooleanContents(N->getValueType(0))) {
    1349         296 :   case UndefinedBooleanContent:
    1350         296 :     return CVal[0];
    1351       55224 :   case ZeroOrOneBooleanContent:
    1352             :     return CVal.isOneValue();
    1353        4800 :   case ZeroOrNegativeOneBooleanContent:
    1354             :     return CVal.isAllOnesValue();
    1355             :   }
    1356             : 
    1357           0 :   llvm_unreachable("Invalid boolean contents");
    1358             : }
    1359             : 
    1360           1 : SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
    1361             :                                         const SDLoc &DL) const {
    1362           1 :   unsigned ElementWidth = VT.getScalarSizeInBits();
    1363             :   APInt TrueInt =
    1364           1 :       getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
    1365             :           ? APInt(ElementWidth, 1)
    1366           2 :           : APInt::getAllOnesValue(ElementWidth);
    1367           2 :   return DAG.getConstant(TrueInt, DL, VT);
    1368             : }
    1369             : 
    1370         408 : bool TargetLowering::isConstFalseVal(const SDNode *N) const {
    1371         408 :   if (!N)
    1372             :     return false;
    1373             : 
    1374           0 :   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
    1375             :   if (!CN) {
    1376           0 :     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
    1377             :     if (!BV)
    1378             :       return false;
    1379             : 
    1380             :     // Only interested in constant splats, we don't care about undef
    1381             :     // elements in identifying boolean constants and getConstantSplatNode
    1382             :     // returns NULL if all ops are undef;
    1383           0 :     CN = BV->getConstantSplatNode();
    1384           0 :     if (!CN)
    1385             :       return false;
    1386             :   }
    1387             : 
    1388         816 :   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
    1389           0 :     return !CN->getAPIntValue()[0];
    1390             : 
    1391         408 :   return CN->isNullValue();
    1392             : }
    1393             : 
    1394           8 : bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
    1395             :                                        bool SExt) const {
    1396          16 :   if (VT == MVT::i1)
    1397           0 :     return N->isOne();
    1398             : 
    1399           8 :   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
    1400           8 :   switch (Cnt) {
    1401           0 :   case TargetLowering::ZeroOrOneBooleanContent:
    1402             :     // An extended value of 1 is always true, unless its original type is i1,
    1403             :     // in which case it will be sign extended to -1.
    1404           0 :     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
    1405           8 :   case TargetLowering::UndefinedBooleanContent:
    1406             :   case TargetLowering::ZeroOrNegativeOneBooleanContent:
    1407          16 :     return N->isAllOnesValue() && SExt;
    1408             :   }
    1409           0 :   llvm_unreachable("Unexpected enumeration.");
    1410             : }
    1411             : 
    1412             : /// This helper function of SimplifySetCC tries to optimize the comparison when
    1413             : /// either operand of the SetCC node is a bitwise-and instruction.
    1414      179722 : SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
    1415             :                                              ISD::CondCode Cond,
    1416             :                                              DAGCombinerInfo &DCI,
    1417             :                                              const SDLoc &DL) const {
    1418             :   // Match these patterns in any of their permutations:
    1419             :   // (X & Y) == Y
    1420             :   // (X & Y) != Y
    1421      359784 :   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
    1422             :     std::swap(N0, N1);
    1423             : 
    1424      359444 :   EVT OpVT = N0.getValueType();
    1425      366189 :   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
    1426        6745 :       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
    1427      172977 :     return SDValue();
    1428             : 
    1429        6745 :   SDValue X, Y;
    1430       20235 :   if (N0.getOperand(0) == N1) {
    1431         536 :     X = N0.getOperand(1);
    1432         536 :     Y = N0.getOperand(0);
    1433       19431 :   } else if (N0.getOperand(1) == N1) {
    1434         604 :     X = N0.getOperand(0);
    1435         604 :     Y = N0.getOperand(1);
    1436             :   } else {
    1437        6175 :     return SDValue();
    1438             :   }
    1439             : 
    1440         570 :   SelectionDAG &DAG = DCI.DAG;
    1441         570 :   SDValue Zero = DAG.getConstant(0, DL, OpVT);
    1442         570 :   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
    1443             :     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
    1444             :     // Note that where Y is variable and is known to have at most one bit set
    1445             :     // (for example, if it is Z & 1) we cannot do this; the expressions are not
    1446             :     // equivalent when Y == 0.
    1447          42 :     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
    1448          84 :     if (DCI.isBeforeLegalizeOps() ||
    1449           0 :         isCondCodeLegal(Cond, N0.getSimpleValueType()))
    1450          42 :       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
    1451        1056 :   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
    1452             :     // If the target supports an 'and-not' or 'and-complement' logic operation,
    1453             :     // try to use that to make a comparison operation more efficient.
    1454             :     // But don't do this transform if the mask is a single bit because there are
    1455             :     // more efficient ways to deal with that case (for example, 'bt' on x86 or
    1456             :     // 'rlwinm' on PPC).
    1457             : 
    1458             :     // Bail out if the compare operand that we want to turn into a zero is
    1459             :     // already a zero (otherwise, infinite loop).
    1460          12 :     auto *YConst = dyn_cast<ConstantSDNode>(Y);
    1461          12 :     if (YConst && YConst->isNullValue())
    1462           0 :       return SDValue();
    1463             : 
    1464             :     // Transform this into: ~X & Y == 0.
    1465          68 :     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
    1466         102 :     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
    1467          34 :     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
    1468             :   }
    1469             : 
    1470         494 :   return SDValue();
    1471             : }
    1472             : 
    1473             : /// Try to simplify a setcc built with the specified operands and cc. If it is
    1474             : /// unable to simplify it, return a null SDValue.
    1475      282929 : SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
    1476             :                                       ISD::CondCode Cond, bool foldBooleans,
    1477             :                                       DAGCombinerInfo &DCI,
    1478             :                                       const SDLoc &dl) const {
    1479      282929 :   SelectionDAG &DAG = DCI.DAG;
    1480             : 
    1481             :   // These setcc operations always fold.
    1482      282929 :   switch (Cond) {
    1483             :   default: break;
    1484           0 :   case ISD::SETFALSE:
    1485           0 :   case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
    1486           0 :   case ISD::SETTRUE:
    1487             :   case ISD::SETTRUE2: {
    1488             :     TargetLowering::BooleanContent Cnt =
    1489           0 :         getBooleanContents(N0->getValueType(0));
    1490             :     return DAG.getConstant(
    1491             :         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
    1492           0 :         VT);
    1493             :   }
    1494             :   }
    1495             : 
    1496             :   // Ensure that the constant occurs on the RHS and fold constant comparisons.
    1497      282929 :   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
    1498      283819 :   if (isa<ConstantSDNode>(N0.getNode()) &&
    1499         890 :       (DCI.isBeforeLegalizeOps() ||
    1500        1106 :        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
    1501         760 :     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
    1502             : 
    1503      471639 :   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
    1504      189470 :     const APInt &C1 = N1C->getAPIntValue();
    1505             : 
    1506             :     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
    1507             :     // equality comparison, then we're just comparing whether X itself is
    1508             :     // zero.
    1509      190830 :     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
    1510      190580 :         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
    1511           0 :         N0.getOperand(1).getOpcode() == ISD::Constant) {
    1512             :       const APInt &ShAmt
    1513           0 :         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
    1514           0 :       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    1515           0 :           ShAmt == Log2_32(N0.getValueSizeInBits())) {
    1516           0 :         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
    1517             :           // (srl (ctlz x), 5) == 0  -> X != 0
    1518             :           // (srl (ctlz x), 5) != 1  -> X != 0
    1519             :           Cond = ISD::SETNE;
    1520             :         } else {
    1521             :           // (srl (ctlz x), 5) != 0  -> X == 0
    1522             :           // (srl (ctlz x), 5) == 1  -> X == 0
    1523           0 :           Cond = ISD::SETEQ;
    1524             :         }
    1525           0 :         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
    1526           0 :         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
    1527           0 :                             Zero, Cond);
    1528             :       }
    1529             :     }
    1530             : 
    1531      189470 :     SDValue CTPOP = N0;
    1532             :     // Look through truncs that don't change the value of a ctpop.
    1533      440247 :     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
    1534        3842 :       CTPOP = N0.getOperand(0);
    1535             : 
    1536      440113 :     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
    1537           8 :         (N0 == CTPOP ||
    1538           8 :          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
    1539           8 :       EVT CTVT = CTPOP.getValueType();
    1540           8 :       SDValue CTOp = CTPOP.getOperand(0);
    1541             : 
    1542             :       // (ctpop x) u< 2 -> (x & x-1) == 0
    1543             :       // (ctpop x) u> 1 -> (x & x-1) != 0
    1544           4 :       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
    1545             :         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
    1546           4 :                                   DAG.getConstant(1, dl, CTVT));
    1547           4 :         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
    1548           4 :         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
    1549           4 :         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
    1550             :       }
    1551             : 
    1552             :       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
    1553             :     }
    1554             : 
    1555             :     // (zext x) == C --> x == (trunc C)
    1556             :     // (sext x) == C --> x == (trunc C)
    1557      341074 :     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    1558      279981 :         DCI.isBeforeLegalize() && N0->hasOneUse()) {
    1559       10432 :       unsigned MinBits = N0.getValueSizeInBits();
    1560       10432 :       SDValue PreExt;
    1561       10432 :       bool Signed = false;
    1562       20864 :       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
    1563             :         // ZExt
    1564         556 :         MinBits = N0->getOperand(0).getValueSizeInBits();
    1565         556 :         PreExt = N0->getOperand(0);
    1566       10154 :       } else if (N0->getOpcode() == ISD::AND) {
    1567             :         // DAGCombine turns costly ZExts into ANDs
    1568        4688 :         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
    1569        4960 :           if ((C->getAPIntValue()+1).isPowerOf2()) {
    1570         970 :             MinBits = C->getAPIntValue().countTrailingOnes();
    1571         970 :             PreExt = N0->getOperand(0);
    1572             :           }
    1573        8306 :       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
    1574             :         // SExt
    1575         284 :         MinBits = N0->getOperand(0).getValueSizeInBits();
    1576         284 :         PreExt = N0->getOperand(0);
    1577         142 :         Signed = true;
    1578        1070 :       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
    1579             :         // ZEXTLOAD / SEXTLOAD
    1580        1070 :         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
    1581           0 :           MinBits = LN0->getMemoryVT().getSizeInBits();
    1582           0 :           PreExt = N0;
    1583        1070 :         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
    1584          96 :           Signed = true;
    1585          96 :           MinBits = LN0->getMemoryVT().getSizeInBits();
    1586          96 :           PreExt = N0;
    1587             :         }
    1588             :       }
    1589             : 
    1590             :       // Figure out how many bits we need to preserve this constant.
    1591       10432 :       unsigned ReqdBits = Signed ?
    1592         238 :         C1.getBitWidth() - C1.getNumSignBits() + 1 :
    1593       10432 :         C1.getActiveBits();
    1594             : 
    1595             :       // Make sure we're not losing bits from the constant.
    1596       10432 :       if (MinBits > 0 &&
    1597       11433 :           MinBits < C1.getBitWidth() &&
    1598             :           MinBits >= ReqdBits) {
    1599         916 :         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
    1600         916 :         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
    1601             :           // Will get folded away.
    1602          76 :           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
    1603          76 :           if (MinBits == 1 && C1 == 1)
    1604             :             // Invert the condition.
    1605           0 :             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
    1606           0 :                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    1607         152 :           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
    1608          76 :           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
    1609             :         }
    1610             : 
    1611             :         // If truncating the setcc operands is not desirable, we can still
    1612             :         // simplify the expression in some cases:
    1613             :         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
    1614             :         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
    1615             :         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
    1616             :         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
    1617             :         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
    1618             :         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
    1619        1680 :         SDValue TopSetCC = N0->getOperand(0);
    1620        1680 :         unsigned N0Opc = N0->getOpcode();
    1621         840 :         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
    1622        2024 :         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
    1623         252 :             TopSetCC.getOpcode() == ISD::SETCC &&
    1624         238 :             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
    1625         127 :             (isConstFalseVal(N1C) ||
    1626          16 :              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
    1627             : 
    1628         167 :           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
    1629           5 :                          (!N1C->isNullValue() && Cond == ISD::SETNE);
    1630             : 
    1631             :           if (!Inverse)
    1632          46 :             return TopSetCC;
    1633             : 
    1634         210 :           ISD::CondCode InvCond = ISD::getSetCCInverse(
    1635             :               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
    1636         280 :               TopSetCC.getOperand(0).getValueType().isInteger());
    1637         140 :           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
    1638         140 :                                       TopSetCC.getOperand(1),
    1639          70 :                                       InvCond);
    1640             :         }
    1641             :       }
    1642             :     }
    1643             : 
    1644             :     // If the LHS is '(and load, const)', the RHS is 0, the test is for
    1645             :     // equality or unsigned, and all 1 bits of the const are in the same
    1646             :     // partial word, see if we can shorten the load.
    1647      290492 :     if (DCI.isBeforeLegalize() &&
    1648      197196 :         !ISD::isSignedIntSetCC(Cond) &&
    1649       98624 :         N0.getOpcode() == ISD::AND && C1 == 0 &&
    1650        5711 :         N0.getNode()->hasOneUse() &&
    1651        5028 :         isa<LoadSDNode>(N0.getOperand(0)) &&
    1652      190291 :         N0.getOperand(0).getNode()->hasOneUse() &&
    1653         310 :         isa<ConstantSDNode>(N0.getOperand(1))) {
    1654         312 :       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
    1655         174 :       APInt bestMask;
    1656         104 :       unsigned bestWidth = 0, bestOffset = 0;
    1657         312 :       if (!Lod->isVolatile() && Lod->isUnindexed()) {
    1658         104 :         unsigned origWidth = N0.getValueSizeInBits();
    1659         104 :         unsigned maskWidth = origWidth;
    1660             :         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
    1661             :         // 8 bits, but have to be careful...
    1662         104 :         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
    1663           0 :           origWidth = Lod->getMemoryVT().getSizeInBits();
    1664             :         const APInt &Mask =
    1665         416 :           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
    1666         195 :         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
    1667         182 :           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
    1668         186 :           for (unsigned offset=0; offset<origWidth/width; offset++) {
    1669         176 :             if (Mask.isSubsetOf(newMask)) {
    1670         162 :               if (DAG.getDataLayout().isLittleEndian())
    1671          63 :                 bestOffset = (uint64_t)offset * (width/8);
    1672             :               else
    1673          18 :                 bestOffset = (origWidth/width - offset - 1) * (width/8);
    1674         243 :               bestMask = Mask.lshr(offset * (width/8) * 8);
    1675          81 :               bestWidth = width;
    1676          81 :               break;
    1677             :             }
    1678          95 :             newMask <<= width;
    1679             :           }
    1680             :         }
    1681             :       }
    1682         104 :       if (bestWidth) {
    1683          35 :         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
    1684           1 :         if (newVT.isRound()) {
    1685         102 :           EVT PtrType = Lod->getOperand(1).getValueType();
    1686          34 :           SDValue Ptr = Lod->getBasePtr();
    1687          34 :           if (bestOffset != 0)
    1688          17 :             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
    1689          34 :                               DAG.getConstant(bestOffset, dl, PtrType));
    1690         102 :           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
    1691             :           SDValue NewLoad = DAG.getLoad(
    1692          68 :               newVT, dl, Lod->getChain(), Ptr,
    1693         136 :               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
    1694             :           return DAG.getSetCC(dl, VT,
    1695             :                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
    1696          68 :                                       DAG.getConstant(bestMask.trunc(bestWidth),
    1697             :                                                       dl, newVT)),
    1698         136 :                               DAG.getConstant(0LL, dl, newVT), Cond);
    1699             :         }
    1700             :       }
    1701             :     }
    1702             : 
    1703             :     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
    1704      378480 :     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
    1705         548 :       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
    1706             : 
    1707             :       // If the comparison constant has bits in the upper part, the
    1708             :       // zero-extended value could never match.
    1709         822 :       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
    1710             :                                               C1.getBitWidth() - InSize))) {
    1711          27 :         switch (Cond) {
    1712           9 :         case ISD::SETUGT:
    1713             :         case ISD::SETUGE:
    1714             :         case ISD::SETEQ:
    1715           9 :           return DAG.getConstant(0, dl, VT);
    1716          12 :         case ISD::SETULT:
    1717             :         case ISD::SETULE:
    1718             :         case ISD::SETNE:
    1719          12 :           return DAG.getConstant(1, dl, VT);
    1720           1 :         case ISD::SETGT:
    1721             :         case ISD::SETGE:
    1722             :           // True if the sign bit of C1 is set.
    1723           1 :           return DAG.getConstant(C1.isNegative(), dl, VT);
    1724           5 :         case ISD::SETLT:
    1725             :         case ISD::SETLE:
    1726             :           // True if the sign bit of C1 isn't set.
    1727           5 :           return DAG.getConstant(C1.isNonNegative(), dl, VT);
    1728             :         default:
    1729             :           break;
    1730             :         }
    1731             :       }
    1732             : 
    1733             :       // Otherwise, we can perform the comparison with the low bits.
    1734             :       switch (Cond) {
    1735         212 :       case ISD::SETEQ:
    1736             :       case ISD::SETNE:
    1737             :       case ISD::SETUGT:
    1738             :       case ISD::SETUGE:
    1739             :       case ISD::SETULT:
    1740             :       case ISD::SETULE: {
    1741         636 :         EVT newVT = N0.getOperand(0).getValueType();
    1742         424 :         if (DCI.isBeforeLegalizeOps() ||
    1743          40 :             (isOperationLegal(ISD::SETCC, newVT) &&
    1744          12 :              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
    1745             :           EVT NewSetCCVT =
    1746         380 :               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
    1747         380 :           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
    1748             : 
    1749         380 :           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
    1750         190 :                                           NewConst, Cond);
    1751         380 :           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
    1752             :         }
    1753          22 :         break;
    1754             :       }
    1755             :       default:
    1756             :         break;   // todo, be more careful with signed comparisons
    1757             :       }
    1758      377932 :     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
    1759             :                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
    1760         132 :       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
    1761          44 :       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
    1762          88 :       EVT ExtDstTy = N0.getValueType();
    1763          44 :       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
    1764             : 
    1765             :       // If the constant doesn't fit into the number of bits for the source of
    1766             :       // the sign extension, it is impossible for both sides to be equal.
    1767          44 :       if (C1.getMinSignedBits() > ExtSrcTyBits)
    1768           2 :         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
    1769             : 
    1770          42 :       SDValue ZextOp;
    1771         126 :       EVT Op0Ty = N0.getOperand(0).getValueType();
    1772          42 :       if (Op0Ty == ExtSrcTy) {
    1773           0 :         ZextOp = N0.getOperand(0);
    1774             :       } else {
    1775          84 :         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
    1776          84 :         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
    1777          84 :                               DAG.getConstant(Imm, dl, Op0Ty));
    1778             :       }
    1779          42 :       if (!DCI.isCalledByLegalizer())
    1780          42 :         DCI.AddToWorklist(ZextOp.getNode());
    1781             :       // Otherwise, make this a use of a zext.
    1782             :       return DAG.getSetCC(dl, VT, ZextOp,
    1783         168 :                           DAG.getConstant(C1 & APInt::getLowBitsSet(
    1784             :                                                               ExtDstTyBits,
    1785             :                                                               ExtSrcTyBits),
    1786             :                                           dl, ExtDstTy),
    1787          42 :                           Cond);
    1788      240771 :     } else if ((N1C->isNullValue() || N1C->isOne()) &&
    1789             :                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
    1790             :       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
    1791      138101 :       if (N0.getOpcode() == ISD::SETCC &&
    1792      138297 :           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
    1793          92 :         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
    1794          92 :         if (TrueWhenTrue)
    1795          28 :           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
    1796             :         // Invert the condition.
    1797         192 :         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
    1798          64 :         CC = ISD::getSetCCInverse(CC,
    1799         256 :                                   N0.getOperand(0).getValueType().isInteger());
    1800         128 :         if (DCI.isBeforeLegalizeOps() ||
    1801           0 :             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
    1802         192 :           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
    1803             :       }
    1804             : 
    1805      275735 :       if ((N0.getOpcode() == ISD::XOR ||
    1806      143591 :            (N0.getOpcode() == ISD::AND &&
    1807       11730 :             N0.getOperand(0).getOpcode() == ISD::XOR &&
    1808         932 :             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
    1809      138683 :           isa<ConstantSDNode>(N0.getOperand(1)) &&
    1810         324 :           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
    1811             :         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
    1812             :         // can only do this if the top bits are known zero.
    1813          47 :         unsigned BitWidth = N0.getValueSizeInBits();
    1814          94 :         if (DAG.MaskedValueIsZero(N0,
    1815          94 :                                   APInt::getHighBitsSet(BitWidth,
    1816             :                                                         BitWidth-1))) {
    1817             :           // Okay, get the un-inverted input value.
    1818          29 :           SDValue Val;
    1819          58 :           if (N0.getOpcode() == ISD::XOR) {
    1820          58 :             Val = N0.getOperand(0);
    1821             :           } else {
    1822             :             assert(N0.getOpcode() == ISD::AND &&
    1823             :                     N0.getOperand(0).getOpcode() == ISD::XOR);
    1824             :             // ((X^1)&1)^1 -> X & 1
    1825           0 :             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
    1826           0 :                               N0.getOperand(0).getOperand(0),
    1827           0 :                               N0.getOperand(1));
    1828             :           }
    1829             : 
    1830             :           return DAG.getSetCC(dl, VT, Val, N1,
    1831          29 :                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    1832             :         }
    1833      137962 :       } else if (N1C->isOne() &&
    1834       10681 :                  (VT == MVT::i1 ||
    1835        9334 :                   getBooleanContents(N0->getValueType(0)) ==
    1836             :                       ZeroOrOneBooleanContent)) {
    1837        5952 :         SDValue Op0 = N0;
    1838       11904 :         if (Op0.getOpcode() == ISD::TRUNCATE)
    1839         682 :           Op0 = Op0.getOperand(0);
    1840             : 
    1841        5956 :         if ((Op0.getOpcode() == ISD::XOR) &&
    1842        5959 :             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
    1843           6 :             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
    1844             :           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
    1845           3 :           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
    1846           9 :           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
    1847        3665 :                               Cond);
    1848             :         }
    1849        5949 :         if (Op0.getOpcode() == ISD::AND &&
    1850        7623 :             isa<ConstantSDNode>(Op0.getOperand(1)) &&
    1851        1608 :             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
    1852             :           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
    1853        1052 :           if (Op0.getValueType().bitsGT(VT))
    1854          36 :             Op0 = DAG.getNode(ISD::AND, dl, VT,
    1855          72 :                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
    1856         144 :                           DAG.getConstant(1, dl, VT));
    1857         980 :           else if (Op0.getValueType().bitsLT(VT))
    1858           1 :             Op0 = DAG.getNode(ISD::AND, dl, VT,
    1859           2 :                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
    1860           4 :                         DAG.getConstant(1, dl, VT));
    1861             : 
    1862             :           return DAG.getSetCC(dl, VT, Op0,
    1863             :                               DAG.getConstant(0, dl, Op0.getValueType()),
    1864        1052 :                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    1865             :         }
    1866       10846 :         if (Op0.getOpcode() == ISD::AssertZext &&
    1867        9447 :             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
    1868             :           return DAG.getSetCC(dl, VT, Op0,
    1869             :                               DAG.getConstant(0, dl, Op0.getValueType()),
    1870        6266 :                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
    1871             :       }
    1872             :     }
    1873             : 
    1874      726118 :     APInt MinVal, MaxVal;
    1875      370392 :     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
    1876      185196 :     if (ISD::isSignedIntSetCC(Cond)) {
    1877       37035 :       MinVal = APInt::getSignedMinValue(OperandBitSize);
    1878       37035 :       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
    1879             :     } else {
    1880      518553 :       MinVal = APInt::getMinValue(OperandBitSize);
    1881      518553 :       MaxVal = APInt::getMaxValue(OperandBitSize);
    1882             :     }
    1883             : 
    1884             :     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
    1885      185196 :     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
    1886             :       // X >= MIN --> true
    1887        3526 :       if (C1 == MinVal)
    1888        3575 :         return DAG.getConstant(1, dl, VT);
    1889             : 
    1890             :       // X >= C0 --> X > (C0 - 1)
    1891       10405 :       APInt C = C1 - 1;
    1892        3464 :       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
    1893        3464 :       if ((DCI.isBeforeLegalizeOps() ||
    1894        6928 :            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
    1895          26 :           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
    1896          26 :                                 isLegalICmpImmediate(C.getSExtValue())))) {
    1897             :         return DAG.getSetCC(dl, VT, N0,
    1898             :                             DAG.getConstant(C, dl, N1.getValueType()),
    1899        6902 :                             NewCC);
    1900             :       }
    1901             :     }
    1902             : 
    1903      181683 :     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
    1904             :       // X <= MAX --> true
    1905        2987 :       if (C1 == MaxVal)
    1906        2948 :           return DAG.getConstant(1, dl, VT);
    1907             : 
    1908             :       // X <= C0 --> X < (C0 + 1)
    1909        8996 :       APInt C = C1 + 1;
    1910        2985 :       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
    1911        2985 :       if ((DCI.isBeforeLegalizeOps() ||
    1912        5970 :            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
    1913          82 :           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
    1914          82 :                                 isLegalICmpImmediate(C.getSExtValue())))) {
    1915             :         return DAG.getSetCC(dl, VT, N0,
    1916             :                             DAG.getConstant(C, dl, N1.getValueType()),
    1917        5888 :                             NewCC);
    1918             :       }
    1919             :     }
    1920             : 
    1921      196686 :     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
    1922          46 :       return DAG.getConstant(0, dl, VT);      // X < MIN --> false
    1923      178704 :     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
    1924           0 :       return DAG.getConstant(1, dl, VT);      // X >= MIN --> true
    1925      192063 :     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
    1926           5 :       return DAG.getConstant(0, dl, VT);      // X > MAX --> false
    1927      178727 :     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
    1928           0 :       return DAG.getConstant(1, dl, VT);      // X <= MAX --> true
    1929             : 
    1930             :     // Canonicalize setgt X, Min --> setne X, Min
    1931      192053 :     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
    1932         139 :       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
    1933             :     // Canonicalize setlt X, Max --> setne X, Max
    1934      196450 :     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
    1935          14 :       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
    1936             : 
    1937             :     // If we have setult X, 1, turn it into seteq X, 0
    1938      589266 :     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
    1939             :       return DAG.getSetCC(dl, VT, N0,
    1940             :                           DAG.getConstant(MinVal, dl, N0.getValueType()),
    1941         320 :                           ISD::SETEQ);
    1942             :     // If we have setugt X, Max-1, turn it into seteq X, Max
    1943      574803 :     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
    1944             :       return DAG.getSetCC(dl, VT, N0,
    1945             :                           DAG.getConstant(MaxVal, dl, N0.getValueType()),
    1946           4 :                           ISD::SETEQ);
    1947             : 
    1948             :     // If we have "setcc X, C0", check to see if we can shrink the immediate
    1949             :     // by changing cc.
    1950             : 
    1951             :     // SETUGT X, SINTMAX  -> SETLT X, 0
    1952      373648 :     if (Cond == ISD::SETUGT &&
    1953      373648 :         C1 == APInt::getSignedMaxValue(OperandBitSize))
    1954             :       return DAG.getSetCC(dl, VT, N0,
    1955             :                           DAG.getConstant(0, dl, N1.getValueType()),
    1956           0 :                           ISD::SETLT);
    1957             : 
    1958             :     // SETULT X, SINTMIN  -> SETGT X, -1
    1959      380642 :     if (Cond == ISD::SETULT &&
    1960      380568 :         C1 == APInt::getSignedMinValue(OperandBitSize)) {
    1961             :       SDValue ConstMinusOne =
    1962         148 :           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
    1963         148 :                           N1.getValueType());
    1964          74 :       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
    1965             :     }
    1966             : 
    1967             :     // Fold bit comparisons when we can.
    1968           0 :     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    1969      294724 :         (VT == N0.getValueType() ||
    1970      522250 :          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
    1971      103899 :         N0.getOpcode() == ISD::AND) {
    1972        9502 :       auto &DL = DAG.getDataLayout();
    1973       12099 :       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
    1974        2597 :         EVT ShiftTy = DCI.isBeforeLegalize()
    1975             :                           ? getPointerTy(DL)
    1976        7155 :                           : getShiftAmountTy(N0.getValueType(), DL);
    1977        2597 :         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
    1978             :           // Perform the xform if the AND RHS is a single bit.
    1979         519 :           if (AndRHS->getAPIntValue().isPowerOf2()) {
    1980             :             return DAG.getNode(ISD::TRUNCATE, dl, VT,
    1981             :                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
    1982         452 :                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
    1983         904 :                                    ShiftTy)));
    1984             :           }
    1985        5990 :         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
    1986             :           // (X & 8) == 8  -->  (X & 8) >> 3
    1987             :           // Perform the xform if C1 is a single bit.
    1988          32 :           if (C1.isPowerOf2()) {
    1989             :             return DAG.getNode(ISD::TRUNCATE, dl, VT,
    1990             :                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
    1991           0 :                                       DAG.getConstant(C1.logBase2(), dl,
    1992           0 :                                                       ShiftTy)));
    1993             :           }
    1994             :         }
    1995             :       }
    1996             :     }
    1997             : 
    1998      356138 :     if (C1.getMinSignedBits() <= 64 &&
    1999      356134 :         !isLegalICmpImmediate(C1.getSExtValue())) {
    2000             :       // (X & -256) == 256 -> (X >> 8) == 1
    2001         351 :       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    2002        1014 :           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
    2003          36 :         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
    2004          12 :           const APInt &AndRHSC = AndRHS->getAPIntValue();
    2005         108 :           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
    2006           8 :             unsigned ShiftBits = AndRHSC.countTrailingZeros();
    2007          16 :             auto &DL = DAG.getDataLayout();
    2008           8 :             EVT ShiftTy = DCI.isBeforeLegalize()
    2009             :                               ? getPointerTy(DL)
    2010          16 :                               : getShiftAmountTy(N0.getValueType(), DL);
    2011          16 :             EVT CmpTy = N0.getValueType();
    2012          16 :             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
    2013             :                                         DAG.getConstant(ShiftBits, dl,
    2014          16 :                                                         ShiftTy));
    2015          16 :             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
    2016           8 :             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
    2017             :           }
    2018             :         }
    2019         956 :       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
    2020         956 :                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
    2021         361 :         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
    2022             :         // X <  0x100000000 -> (X >> 32) <  1
    2023             :         // X >= 0x100000000 -> (X >> 32) >= 1
    2024             :         // X <= 0x0ffffffff -> (X >> 32) <  1
    2025             :         // X >  0x0ffffffff -> (X >> 32) >= 1
    2026             :         unsigned ShiftBits;
    2027         522 :         APInt NewC = C1;
    2028         361 :         ISD::CondCode NewCond = Cond;
    2029         361 :         if (AdjOne) {
    2030         173 :           ShiftBits = C1.countTrailingOnes();
    2031         865 :           NewC = NewC + 1;
    2032         173 :           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
    2033             :         } else {
    2034         188 :           ShiftBits = C1.countTrailingZeros();
    2035             :         }
    2036         361 :         NewC.lshrInPlace(ShiftBits);
    2037         579 :         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
    2038         436 :           isLegalICmpImmediate(NewC.getSExtValue())) {
    2039         400 :           auto &DL = DAG.getDataLayout();
    2040         200 :           EVT ShiftTy = DCI.isBeforeLegalize()
    2041             :                             ? getPointerTy(DL)
    2042         400 :                             : getShiftAmountTy(N0.getValueType(), DL);
    2043         400 :           EVT CmpTy = N0.getValueType();
    2044             :           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
    2045         200 :                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
    2046         200 :           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
    2047         200 :           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
    2048             :         }
    2049             :       }
    2050             :     }
    2051             :   }
    2052             : 
    2053      270562 :   if (isa<ConstantFPSDNode>(N0.getNode())) {
    2054             :     // Constant fold or commute setcc.
    2055          61 :     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
    2056          61 :     if (O.getNode()) return O;
    2057      274460 :   } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
    2058             :     // If the RHS of an FP comparison is a constant, simplify it away in
    2059             :     // some cases.
    2060        7918 :     if (CFP->getValueAPF().isNaN()) {
    2061             :       // If an operand is known to be a nan, we can fold it.
    2062           0 :       switch (ISD::getUnorderedFlavor(Cond)) {
    2063           0 :       default: llvm_unreachable("Unknown flavor!");
    2064           0 :       case 0:  // Known false.
    2065           0 :         return DAG.getConstant(0, dl, VT);
    2066           0 :       case 1:  // Known true.
    2067           0 :         return DAG.getConstant(1, dl, VT);
    2068           0 :       case 2:  // Undefined.
    2069           0 :         return DAG.getUNDEF(VT);
    2070             :       }
    2071             :     }
    2072             : 
    2073             :     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
    2074             :     // constant if knowing that the operand is non-nan is enough.  We prefer to
    2075             :     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
    2076             :     // materialize 0.0.
    2077        3959 :     if (Cond == ISD::SETO || Cond == ISD::SETUO)
    2078          97 :       return DAG.getSetCC(dl, VT, N0, N0, Cond);
    2079             : 
    2080             :     // setcc (fneg x), C -> setcc swap(pred) x, -C
    2081        7724 :     if (N0.getOpcode() == ISD::FNEG) {
    2082          61 :       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
    2083         122 :       if (DCI.isBeforeLegalizeOps() ||
    2084           4 :           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
    2085         122 :         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
    2086         122 :         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
    2087             :       }
    2088             :     }
    2089             : 
    2090             :     // If the condition is not legal, see if we can find an equivalent one
    2091             :     // which is legal.
    2092        7808 :     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
    2093             :       // If the comparison was an awkward floating-point == or != and one of
    2094             :       // the comparison operands is infinity or negative infinity, convert the
    2095             :       // condition to a less-awkward <= or >=.
    2096         412 :       if (CFP->getValueAPF().isInfinity()) {
    2097          28 :         if (CFP->getValueAPF().isNegative()) {
    2098           4 :           if (Cond == ISD::SETOEQ &&
    2099           4 :               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
    2100           2 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
    2101           2 :           if (Cond == ISD::SETUEQ &&
    2102           0 :               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
    2103           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
    2104           2 :           if (Cond == ISD::SETUNE &&
    2105           4 :               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
    2106           2 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
    2107           0 :           if (Cond == ISD::SETONE &&
    2108           0 :               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
    2109           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
    2110             :         } else {
    2111          10 :           if (Cond == ISD::SETOEQ &&
    2112          16 :               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
    2113           8 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
    2114           2 :           if (Cond == ISD::SETUEQ &&
    2115           0 :               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
    2116           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
    2117           2 :           if (Cond == ISD::SETUNE &&
    2118           4 :               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
    2119           2 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
    2120           0 :           if (Cond == ISD::SETONE &&
    2121           0 :               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
    2122           0 :             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
    2123             :         }
    2124             :       }
    2125             :     }
    2126             :   }
    2127             : 
    2128         597 :   if (N0 == N1) {
    2129             :     // The sext(setcc()) => setcc() optimization relies on the appropriate
    2130             :     // constant being emitted.
    2131         597 :     uint64_t EqVal = 0;
    2132        1194 :     switch (getBooleanContents(N0.getValueType())) {
    2133         374 :     case UndefinedBooleanContent:
    2134             :     case ZeroOrOneBooleanContent:
    2135         374 :       EqVal = ISD::isTrueWhenEqual(Cond);
    2136         374 :       break;
    2137         223 :     case ZeroOrNegativeOneBooleanContent:
    2138         223 :       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
    2139             :       break;
    2140             :     }
    2141             : 
    2142             :     // We can always fold X == X for integer setcc's.
    2143        1194 :     if (N0.getValueType().isInteger()) {
    2144          82 :       return DAG.getConstant(EqVal, dl, VT);
    2145             :     }
    2146         515 :     unsigned UOF = ISD::getUnorderedFlavor(Cond);
    2147         515 :     if (UOF == 2)   // FP operators that are undefined on NaNs.
    2148           0 :       return DAG.getConstant(EqVal, dl, VT);
    2149         515 :     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
    2150          19 :       return DAG.getConstant(EqVal, dl, VT);
    2151             :     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
    2152             :     // if it is not already.
    2153         496 :     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
    2154         679 :     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
    2155         180 :           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
    2156          63 :       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
    2157             :   }
    2158             : 
    2159      450309 :   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
    2160      450586 :       N0.getValueType().isInteger()) {
    2161      712199 :     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
    2162      175973 :         N0.getOpcode() == ISD::XOR) {
    2163             :       // Simplify (X+Y) == (X+Z) -->  Y == Z
    2164       12276 :       if (N0.getOpcode() == N1.getOpcode()) {
    2165          64 :         if (N0.getOperand(0) == N1.getOperand(0))
    2166           0 :           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
    2167          64 :         if (N0.getOperand(1) == N1.getOperand(1))
    2168           0 :           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
    2169          32 :         if (isCommutativeBinOp(N0.getOpcode())) {
    2170             :           // If X op Y == Y op X, try other combinations.
    2171          56 :           if (N0.getOperand(0) == N1.getOperand(1))
    2172           0 :             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
    2173           0 :                                 Cond);
    2174          42 :           if (N0.getOperand(1) == N1.getOperand(0))
    2175           0 :             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
    2176           0 :                                 Cond);
    2177             :         }
    2178             :       }
    2179             : 
    2180             :       // If RHS is a legal immediate value for a compare instruction, we need
    2181             :       // to be careful about increasing register pressure needlessly.
    2182        4092 :       bool LegalRHSImm = false;
    2183             : 
    2184        3279 :       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
    2185        8949 :         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
    2186             :           // Turn (X+C1) == C2 --> X == C2-C1
    2187        4826 :           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
    2188          88 :             return DAG.getSetCC(dl, VT, N0.getOperand(0),
    2189         220 :                                 DAG.getConstant(RHSC->getAPIntValue()-
    2190             :                                                 LHSR->getAPIntValue(),
    2191         132 :                                 dl, N0.getValueType()), Cond);
    2192             :           }
    2193             : 
    2194             :           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
    2195        4694 :           if (N0.getOpcode() == ISD::XOR)
    2196             :             // If we know that all of the inverted bits are zero, don't bother
    2197             :             // performing the inversion.
    2198         486 :             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
    2199             :               return
    2200          18 :                 DAG.getSetCC(dl, VT, N0.getOperand(0),
    2201          45 :                              DAG.getConstant(LHSR->getAPIntValue() ^
    2202             :                                                RHSC->getAPIntValue(),
    2203             :                                              dl, N0.getValueType()),
    2204          27 :                              Cond);
    2205             :         }
    2206             : 
    2207             :         // Turn (C1-X) == C2 --> X == C1-C2
    2208        6465 :         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
    2209          26 :           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
    2210             :             return
    2211           0 :               DAG.getSetCC(dl, VT, N0.getOperand(1),
    2212           0 :                            DAG.getConstant(SUBC->getAPIntValue() -
    2213             :                                              RHSC->getAPIntValue(),
    2214             :                                            dl, N0.getValueType()),
    2215           0 :                            Cond);
    2216             :           }
    2217             :         }
    2218             : 
    2219             :         // Could RHSC fold directly into a compare?
    2220        6452 :         if (RHSC->getValueType(0).getSizeInBits() <= 64)
    2221        6452 :           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
    2222             :       }
    2223             : 
    2224             :       // Simplify (X+Z) == X -->  Z == 0
    2225             :       // Don't do this if X is an immediate that can fold into a cmp
    2226             :       // instruction and X+Z has other uses. It could be an induction variable
    2227             :       // chain, and the transform would increase register pressure.
    2228        3226 :       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
    2229        3870 :         if (N0.getOperand(0) == N1)
    2230          50 :           return DAG.getSetCC(dl, VT, N0.getOperand(1),
    2231          75 :                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
    2232        2544 :         if (N0.getOperand(1) == N1) {
    2233          28 :           if (isCommutativeBinOp(N0.getOpcode()))
    2234           4 :             return DAG.getSetCC(dl, VT, N0.getOperand(0),
    2235             :                                 DAG.getConstant(0, dl, N0.getValueType()),
    2236           6 :                                 Cond);
    2237          14 :           if (N0.getNode()->hasOneUse()) {
    2238             :             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
    2239           4 :             auto &DL = DAG.getDataLayout();
    2240             :             // (Z-X) == X  --> Z == X<<1
    2241             :             SDValue SH = DAG.getNode(
    2242             :                 ISD::SHL, dl, N1.getValueType(), N1,
    2243             :                 DAG.getConstant(1, dl,
    2244           6 :                                 getShiftAmountTy(N1.getValueType(), DL)));
    2245           2 :             if (!DCI.isCalledByLegalizer())
    2246           2 :               DCI.AddToWorklist(SH.getNode());
    2247           4 :             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
    2248             :           }
    2249             :         }
    2250             :       }
    2251             :     }
    2252             : 
    2253      716619 :     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
    2254      178553 :         N1.getOpcode() == ISD::XOR) {
    2255             :       // Simplify  X == (X+Z) -->  Z == 0
    2256        8904 :       if (N1.getOperand(0) == N0)
    2257           2 :         return DAG.getSetCC(dl, VT, N1.getOperand(1),
    2258           3 :                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
    2259        5947 :       if (N1.getOperand(1) == N0) {
    2260          26 :         if (isCommutativeBinOp(N1.getOpcode()))
    2261           0 :           return DAG.getSetCC(dl, VT, N1.getOperand(0),
    2262           0 :                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
    2263          14 :         if (N1.getNode()->hasOneUse()) {
    2264             :           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
    2265           2 :           auto &DL = DAG.getDataLayout();
    2266             :           // X == (Z-X)  --> X<<1 == Z
    2267             :           SDValue SH = DAG.getNode(
    2268             :               ISD::SHL, dl, N1.getValueType(), N0,
    2269           3 :               DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
    2270           1 :           if (!DCI.isCalledByLegalizer())
    2271           1 :             DCI.AddToWorklist(SH.getNode());
    2272           2 :           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
    2273             :         }
    2274             :       }
    2275             :     }
    2276             : 
    2277      179722 :     if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
    2278          76 :       return V;
    2279             :   }
    2280             : 
    2281             :   // Fold away ALL boolean setcc's.
    2282      270066 :   SDValue Temp;
    2283      541294 :   if (N0.getValueType() == MVT::i1 && foldBooleans) {
    2284         408 :     switch (Cond) {
    2285           0 :     default: llvm_unreachable("Unknown integer setcc!");
    2286          30 :     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
    2287          60 :       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
    2288          30 :       N0 = DAG.getNOT(dl, Temp, MVT::i1);
    2289          30 :       if (!DCI.isCalledByLegalizer())
    2290          30 :         DCI.AddToWorklist(Temp.getNode());
    2291             :       break;
    2292         342 :     case ISD::SETNE:  // X != Y   -->  (X^Y)
    2293         684 :       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
    2294         342 :       break;
    2295           9 :     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
    2296             :     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
    2297           9 :       Temp = DAG.getNOT(dl, N0, MVT::i1);
    2298          18 :       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
    2299           9 :       if (!DCI.isCalledByLegalizer())
    2300           9 :         DCI.AddToWorklist(Temp.getNode());
    2301             :       break;
    2302          10 :     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
    2303             :     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
    2304          10 :       Temp = DAG.getNOT(dl, N1, MVT::i1);
    2305          20 :       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
    2306          10 :       if (!DCI.isCalledByLegalizer())
    2307          10 :         DCI.AddToWorklist(Temp.getNode());
    2308             :       break;
    2309           8 :     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
    2310             :     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
    2311           8 :       Temp = DAG.getNOT(dl, N0, MVT::i1);
    2312          16 :       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
    2313           8 :       if (!DCI.isCalledByLegalizer())
    2314           8 :         DCI.AddToWorklist(Temp.getNode());
    2315             :       break;
    2316           9 :     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
    2317             :     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
    2318           9 :       Temp = DAG.getNOT(dl, N1, MVT::i1);
    2319          18 :       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
    2320           9 :       break;
    2321             :     }
    2322         408 :     if (VT != MVT::i1) {
    2323           3 :       if (!DCI.isCalledByLegalizer())
    2324           3 :         DCI.AddToWorklist(N0.getNode());
    2325             :       // FIXME: If running after legalize, we probably can't do this.
    2326           3 :       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
    2327             :     }
    2328         408 :     return N0;
    2329             :   }
    2330             : 
    2331             :   // Could not fold it.
    2332      269658 :   return SDValue();
    2333             : }
    2334             : 
    2335             : /// Returns true (and the GlobalValue and the offset) if the node is a
    2336             : /// GlobalAddress + offset.
    2337    19440042 : bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
    2338             :                                     int64_t &Offset) const {
    2339     1959556 :   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
    2340     1959556 :     GA = GASD->getGlobal();
    2341     1959556 :     Offset += GASD->getOffset();
    2342     1959556 :     return true;
    2343             :   }
    2344             : 
    2345    17480486 :   if (N->getOpcode() == ISD::ADD) {
    2346    15892788 :     SDValue N1 = N->getOperand(0);
    2347    15892788 :     SDValue N2 = N->getOperand(1);
    2348     7946394 :     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
    2349      869369 :       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
    2350      869369 :         Offset += V->getSExtValue();
    2351     1738738 :         return true;
    2352             :       }
    2353     6649531 :     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
    2354           0 :       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
    2355           0 :         Offset += V->getSExtValue();
    2356           0 :         return true;
    2357             :       }
    2358             :     }
    2359             :   }
    2360             : 
    2361             :   return false;
    2362             : }
    2363             : 
    2364       12050 : SDValue TargetLowering::PerformDAGCombine(SDNode *N,
    2365             :                                           DAGCombinerInfo &DCI) const {
    2366             :   // Default implementation: no optimization.
    2367       12050 :   return SDValue();
    2368             : }
    2369             : 
    2370             : //===----------------------------------------------------------------------===//
    2371             : //  Inline Assembler Implementation Methods
    2372             : //===----------------------------------------------------------------------===//
    2373             : 
    2374             : TargetLowering::ConstraintType
    2375      434219 : TargetLowering::getConstraintType(StringRef Constraint) const {
    2376      434219 :   unsigned S = Constraint.size();
    2377             : 
    2378      434219 :   if (S == 1) {
    2379       16680 :     switch (Constraint[0]) {
    2380             :     default: break;
    2381             :     case 'r': return C_RegisterClass;
    2382             :     case 'm':    // memory
    2383             :     case 'o':    // offsetable
    2384             :     case 'V':    // not offsetable
    2385             :       return C_Memory;
    2386             :     case 'i':    // Simple Integer or Relocatable Constant
    2387             :     case 'n':    // Simple Integer
    2388             :     case 'E':    // Floating Point Constant
    2389             :     case 'F':    // Floating Point Constant
    2390             :     case 's':    // Relocatable Constant
    2391             :     case 'p':    // Address.
    2392             :     case 'X':    // Allow ANY value.
    2393             :     case 'I':    // Target registers.
    2394             :     case 'J':
    2395             :     case 'K':
    2396             :     case 'L':
    2397             :     case 'M':
    2398             :     case 'N':
    2399             :     case 'O':
    2400             :     case 'P':
    2401             :     case '<':
    2402             :     case '>':
    2403             :       return C_Other;
    2404             :     }
    2405             :   }
    2406             : 
    2407     1278482 :   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
    2408      428977 :     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
    2409             :       return C_Memory;
    2410             :     return C_Register;
    2411             :   }
    2412             :   return C_Unknown;
    2413             : }
    2414             : 
    2415             : /// Try to replace an X constraint, which matches anything, with another that
    2416             : /// has more specific requirements based on the type of the corresponding
    2417             : /// operand.
    2418         117 : const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
    2419         117 :   if (ConstraintVT.isInteger())
    2420             :     return "r";
    2421          39 :   if (ConstraintVT.isFloatingPoint())
    2422             :     return "f";      // works for many targets
    2423           3 :   return nullptr;
    2424             : }
    2425             : 
    2426             : /// Lower the specified operand into the Ops vector.
    2427             : /// If it is invalid, don't add anything to Ops.
    2428         211 : void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
    2429             :                                                   std::string &Constraint,
    2430             :                                                   std::vector<SDValue> &Ops,
    2431             :                                                   SelectionDAG &DAG) const {
    2432             : 
    2433         211 :   if (Constraint.length() > 1) return;
    2434             : 
    2435         211 :   char ConstraintLetter = Constraint[0];
    2436         211 :   switch (ConstraintLetter) {
    2437             :   default: break;
    2438          24 :   case 'X':     // Allows any operand; labels (basic block) use this.
    2439          48 :     if (Op.getOpcode() == ISD::BasicBlock) {
    2440           2 :       Ops.push_back(Op);
    2441           2 :       return;
    2442             :     }
    2443             :     LLVM_FALLTHROUGH;
    2444             :   case 'i':    // Simple Integer or Relocatable Constant
    2445             :   case 'n':    // Simple Integer
    2446             :   case 's': {  // Relocatable Constant
    2447             :     // These operands are interested in values of the form (GV+C), where C may
    2448             :     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
    2449             :     // is possible and fine if either GV or C are missing.
    2450         155 :     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
    2451         155 :     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
    2452             : 
    2453             :     // If we have "(add GV, C)", pull out GV/C
    2454         310 :     if (Op.getOpcode() == ISD::ADD) {
    2455          12 :       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    2456          12 :       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
    2457           4 :       if (!C || !GA) {
    2458           0 :         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
    2459           0 :         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
    2460             :       }
    2461           4 :       if (!C || !GA) {
    2462             :         C = nullptr;
    2463             :         GA = nullptr;
    2464             :       }
    2465             :     }
    2466             : 
    2467             :     // If we find a valid operand, map to the TargetXXX version so that the
    2468             :     // value itself doesn't get selected.
    2469         155 :     if (GA) {   // Either &GV   or   &GV+C
    2470          20 :       if (ConstraintLetter != 'n') {
    2471          19 :         int64_t Offs = GA->getOffset();
    2472          23 :         if (C) Offs += C->getZExtValue();
    2473          38 :         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
    2474          53 :                                                  C ? SDLoc(C) : SDLoc(),
    2475          38 :                                                  Op.getValueType(), Offs));
    2476             :       }
    2477             :       return;
    2478             :     }
    2479         135 :     if (C) {   // just C, no GV.
    2480             :       // Simple constants are not allowed for 's'.
    2481         117 :       if (ConstraintLetter != 's') {
    2482             :         // gcc prints these as sign extended.  Sign extend value to 64 bits
    2483             :         // now; without this it would get ZExt'd later in
    2484             :         // ScheduleDAGSDNodes::EmitNode, which is very generic.
    2485         351 :         Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
    2486         468 :                                             SDLoc(C), MVT::i64));
    2487             :       }
    2488             :       return;
    2489             :     }
    2490             :     break;
    2491             :   }
    2492             :   }
    2493             : }
    2494             : 
    2495             : std::pair<unsigned, const TargetRegisterClass *>
    2496       95532 : TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
    2497             :                                              StringRef Constraint,
    2498             :                                              MVT VT) const {
    2499      190960 :   if (Constraint.empty() || Constraint[0] != '{')
    2500         334 :     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
    2501             :   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
    2502             : 
    2503             :   // Remove the braces from around the name.
    2504      190730 :   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
    2505             : 
    2506       95365 :   std::pair<unsigned, const TargetRegisterClass*> R =
    2507             :     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
    2508             : 
    2509             :   // Figure out which register class contains this reg.
    2510     9149344 :   for (const TargetRegisterClass *RC : RI->regclasses()) {
    2511             :     // If none of the value types for this register class are valid, we
    2512             :     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
    2513     9054803 :     if (!isLegalRC(*RI, *RC))
    2514     1962584 :       continue;
    2515             : 
    2516    94390005 :     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
    2517    80205567 :          I != E; ++I) {
    2518    73605949 :       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
    2519             :         std::pair<unsigned, const TargetRegisterClass*> S =
    2520     1475331 :           std::make_pair(*I, RC);
    2521             : 
    2522             :         // If this register class has the requested value type, return it,
    2523             :         // otherwise keep searching and return the first class found
    2524             :         // if no other is found which explicitly has the requested type.
    2525      983554 :         if (RI->isTypeLegalForClass(*RC, VT))
    2526         824 :           return S;
    2527      490953 :         if (!R.second)
    2528       83567 :           R = S;
    2529             :       }
    2530             :     }
    2531             :   }
    2532             : 
    2533       94541 :   return R;
    2534             : }
    2535             : 
    2536             : //===----------------------------------------------------------------------===//
    2537             : // Constraint Selection.
    2538             : 
    2539             : /// Return true of this is an input operand that is a matching constraint like
    2540             : /// "4".
    2541        2944 : bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
    2542             :   assert(!ConstraintCode.empty() && "No known constraint!");
    2543        5888 :   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
    2544             : }
    2545             : 
    2546             : /// If this is an input matching constraint, this method returns the output
    2547             : /// operand it matches.
    2548         387 : unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
    2549             :   assert(!ConstraintCode.empty() && "No known constraint!");
    2550        1161 :   return atoi(ConstraintCode.c_str());
    2551             : }
    2552             : 
    2553             : /// Split up the constraint string from the inline assembly value into the
    2554             : /// specific constraints and their prefixes, and also tie in the associated
    2555             : /// operand values.
    2556             : /// If this returns an empty vector, and if the constraint string itself
    2557             : /// isn't empty, there was an error parsing.
    2558             : TargetLowering::AsmOperandInfoVector
    2559       24129 : TargetLowering::ParseConstraints(const DataLayout &DL,
    2560             :                                  const TargetRegisterInfo *TRI,
    2561             :                                  ImmutableCallSite CS) const {
    2562             :   /// Information about all of the constraints.
    2563       24129 :   AsmOperandInfoVector ConstraintOperands;
    2564       48258 :   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
    2565       24129 :   unsigned maCount = 0; // Largest number of multiple alternative constraints.
    2566             : 
    2567             :   // Do a prepass over the constraints, canonicalizing them, and building up the
    2568             :   // ConstraintOperands list.
    2569       24129 :   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
    2570       24129 :   unsigned ResNo = 0;   // ResNo - The result number of the next output.
    2571             : 
    2572      285391 :   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
    2573      164746 :     ConstraintOperands.emplace_back(std::move(CI));
    2574      164746 :     AsmOperandInfo &OpInfo = ConstraintOperands.back();
    2575             : 
    2576             :     // Update multiple alternative constraint count.
    2577      329492 :     if (OpInfo.multipleAlternatives.size() > maCount)
    2578         417 :       maCount = OpInfo.multipleAlternatives.size();
    2579             : 
    2580      164746 :     OpInfo.ConstraintVT = MVT::Other;
    2581             : 
    2582             :     // Compute the value type for each operand.
    2583      164746 :     switch (OpInfo.Type) {
    2584       10873 :     case InlineAsm::isOutput:
    2585             :       // Indirect outputs just consume an argument.
    2586       10873 :       if (OpInfo.isIndirect) {
    2587        1438 :         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
    2588         719 :         break;
    2589             :       }
    2590             : 
    2591             :       // The return value of the call is this value.  As such, there is no
    2592             :       // corresponding argument.
    2593             :       assert(!CS.getType()->isVoidTy() &&
    2594             :              "Bad inline asm!");
    2595       11192 :       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
    2596        1038 :         OpInfo.ConstraintVT =
    2597        2076 :             getSimpleValueType(DL, STy->getElementType(ResNo));
    2598             :       } else {
    2599             :         assert(ResNo == 0 && "Asm only has one result!");
    2600       27348 :         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
    2601             :       }
    2602       10154 :       ++ResNo;
    2603       10154 :       break;
    2604        8866 :     case InlineAsm::isInput:
    2605       17732 :       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
    2606        8866 :       break;
    2607             :     case InlineAsm::isClobber:
    2608             :       // Nothing to do.
    2609             :       break;
    2610             :     }
    2611             : 
    2612      164746 :     if (OpInfo.CallOperandVal) {
    2613        9585 :       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
    2614        9585 :       if (OpInfo.isIndirect) {
    2615        1253 :         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
    2616             :         if (!PtrTy)
    2617           0 :           report_fatal_error("Indirect operand for inline asm not a pointer!");
    2618        1253 :         OpTy = PtrTy->getElementType();
    2619             :       }
    2620             : 
    2621             :       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
    2622          42 :       if (StructType *STy = dyn_cast<StructType>(OpTy))
    2623          42 :         if (STy->getNumElements() == 1)
    2624          52 :           OpTy = STy->getElementType(0);
    2625             : 
    2626             :       // If OpTy is not a single value, it may be a struct/union that we
    2627             :       // can tile with integers.
    2628        9585 :       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
    2629          46 :         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
    2630          46 :         switch (BitSize) {
    2631             :         default: break;
    2632          23 :         case 1:
    2633             :         case 8:
    2634             :         case 16:
    2635             :         case 32:
    2636             :         case 64:
    2637             :         case 128:
    2638          23 :           OpInfo.ConstraintVT =
    2639          23 :             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
    2640          23 :           break;
    2641             :         }
    2642        1172 :       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
    2643        2344 :         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
    2644        1172 :         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
    2645             :       } else {
    2646        8367 :         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
    2647             :       }
    2648             :     }
    2649             :   }
    2650             : 
    2651             :   // If we have multiple alternative constraints, select the best alternative.
    2652       24129 :   if (!ConstraintOperands.empty()) {
    2653       22745 :     if (maCount) {
    2654             :       unsigned bestMAIndex = 0;
    2655             :       int bestWeight = -1;
    2656             :       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
    2657             :       int weight = -1;
    2658             :       unsigned maIndex;
    2659             :       // Compute the sums of the weights for each alternative, keeping track
    2660             :       // of the best (highest weight) one so far.
    2661        2193 :       for (maIndex = 0; maIndex < maCount; ++maIndex) {
    2662         888 :         int weightSum = 0;
    2663        4101 :         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
    2664        3213 :             cIndex != eIndex; ++cIndex) {
    2665        5004 :           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
    2666        2502 :           if (OpInfo.Type == InlineAsm::isClobber)
    2667         825 :             continue;
    2668             : 
    2669             :           // If this is an output operand with a matching input operand,
    2670             :           // look up the matching input. If their types mismatch, e.g. one
    2671             :           // is an integer, the other is floating point, or their sizes are
    2672             :           // different, flag it as an maCantMatch.
    2673        1677 :           if (OpInfo.hasMatchingInput()) {
    2674           0 :             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
    2675           0 :             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
    2676           0 :               if ((OpInfo.ConstraintVT.isInteger() !=
    2677           0 :                    Input.ConstraintVT.isInteger()) ||
    2678           0 :                   (OpInfo.ConstraintVT.getSizeInBits() !=
    2679           0 :                    Input.ConstraintVT.getSizeInBits())) {
    2680             :                 weightSum = -1;  // Can't match.
    2681             :                 break;
    2682             :               }
    2683             :             }
    2684             :           }
    2685        1677 :           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
    2686        1677 :           if (weight == -1) {
    2687             :             weightSum = -1;
    2688             :             break;
    2689             :           }
    2690        1500 :           weightSum += weight;
    2691             :         }
    2692             :         // Update best.
    2693         888 :         if (weightSum > bestWeight) {
    2694         570 :           bestWeight = weightSum;
    2695         570 :           bestMAIndex = maIndex;
    2696             :         }
    2697             :       }
    2698             : 
    2699             :       // Now select chosen alternative in each constraint.
    2700        2154 :       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
    2701        1737 :           cIndex != eIndex; ++cIndex) {
    2702        2640 :         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
    2703        1320 :         if (cInfo.Type == InlineAsm::isClobber)
    2704         489 :           continue;
    2705         831 :         cInfo.selectAlternative(bestMAIndex);
    2706             :       }
    2707             :     }
    2708             :   }
    2709             : 
    2710             :   // Check and hook up tied operands, choose constraint code to use.
    2711      213004 :   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
    2712      188875 :       cIndex != eIndex; ++cIndex) {
    2713      329492 :     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
    2714             : 
    2715             :     // If this is an output operand with a matching input operand, look up the
    2716             :     // matching input. If their types mismatch, e.g. one is an integer, the
    2717             :     // other is floating point, or their sizes are different, flag it as an
    2718             :     // error.
    2719      164746 :     if (OpInfo.hasMatchingInput()) {
    2720        1218 :       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
    2721             : 
    2722        1218 :       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
    2723             :         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
    2724             :             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
    2725          78 :                                          OpInfo.ConstraintVT);
    2726             :         std::pair<unsigned, const TargetRegisterClass *> InputRC =
    2727             :             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
    2728          78 :                                          Input.ConstraintVT);
    2729          78 :         if ((OpInfo.ConstraintVT.isInteger() !=
    2730         117 :              Input.ConstraintVT.isInteger()) ||
    2731          39 :             (MatchRC.second != InputRC.second)) {
    2732           0 :           report_fatal_error("Unsupported asm: input constraint"
    2733             :                              " with a matching output constraint of"
    2734             :                              " incompatible type!");
    2735             :         }
    2736             :       }
    2737             :     }
    2738             :   }
    2739             : 
    2740       24129 :   return ConstraintOperands;
    2741             : }
    2742             : 
    2743             : /// Return an integer indicating how general CT is.
    2744             : static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
    2745      145796 :   switch (CT) {
    2746             :   case TargetLowering::C_Other:
    2747             :   case TargetLowering::C_Unknown:
    2748             :     return 0;
    2749      144374 :   case TargetLowering::C_Register:
    2750             :     return 1;
    2751         556 :   case TargetLowering::C_RegisterClass:
    2752             :     return 2;
    2753         238 :   case TargetLowering::C_Memory:
    2754             :     return 3;
    2755             :   }
    2756           0 :   llvm_unreachable("Invalid constraint type");
    2757             : }
    2758             : 
    2759             : /// Examine constraint type and operand type and determine a weight value.
    2760             : /// This object must already have been set up with the operand type
    2761             : /// and the current alternative constraint selected.
    2762             : TargetLowering::ConstraintWeight
    2763        1677 :   TargetLowering::getMultipleConstraintMatchWeight(
    2764             :     AsmOperandInfo &info, int maIndex) const {
    2765             :   InlineAsm::ConstraintCodeVector *rCodes;
    2766        3354 :   if (maIndex >= (int)info.multipleAlternatives.size())
    2767           3 :     rCodes = &info.Codes;
    2768             :   else
    2769        3348 :     rCodes = &info.multipleAlternatives[maIndex].Codes;
    2770        1677 :   ConstraintWeight BestWeight = CW_Invalid;
    2771             : 
    2772             :   // Loop over the options, keeping track of the most general one.
    2773        5244 :   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
    2774             :     ConstraintWeight weight =
    2775        3780 :       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
    2776        1890 :     if (weight > BestWeight)
    2777        1530 :       BestWeight = weight;
    2778             :   }
    2779             : 
    2780        1677 :   return BestWeight;
    2781             : }
    2782             : 
    2783             : /// Examine constraint type and operand type and determine a weight value.
    2784             : /// This object must already have been set up with the operand type
    2785             : /// and the current alternative constraint selected.
    2786             : TargetLowering::ConstraintWeight
    2787        1266 :   TargetLowering::getSingleConstraintMatchWeight(
    2788             :     AsmOperandInfo &info, const char *constraint) const {
    2789        1266 :   ConstraintWeight weight = CW_Invalid;
    2790        1266 :   Value *CallOperandVal = info.CallOperandVal;
    2791             :     // If we don't have a value, we can't do a match,
    2792             :     // but allow it at the lowest weight.
    2793        1266 :   if (!CallOperandVal)
    2794             :     return CW_Default;
    2795             :   // Look at the constraint type.
    2796        1176 :   switch (*constraint) {
    2797         111 :     case 'i': // immediate integer.
    2798             :     case 'n': // immediate integer with a known value.
    2799         222 :       if (isa<ConstantInt>(CallOperandVal))
    2800          69 :         weight = CW_Constant;
    2801             :       break;
    2802           0 :     case 's': // non-explicit intregal immediate.
    2803           0 :       if (isa<GlobalValue>(CallOperandVal))
    2804             :         weight = CW_Constant;
    2805             :       break;
    2806           0 :     case 'E': // immediate float if host format.
    2807             :     case 'F': // immediate float.
    2808           0 :       if (isa<ConstantFP>(CallOperandVal))
    2809           0 :         weight = CW_Constant;
    2810             :       break;
    2811             :     case '<': // memory operand with autodecrement.
    2812             :     case '>': // memory operand with autoincrement.
    2813             :     case 'm': // memory operand.
    2814             :     case 'o': // offsettable memory operand
    2815             :     case 'V': // non-offsettable memory operand
    2816             :       weight = CW_Memory;
    2817             :       break;
    2818         576 :     case 'r': // general register.
    2819             :     case 'g': // general register, memory operand or immediate integer.
    2820             :               // note: Clang converts "g" to "imr".
    2821        1152 :       if (CallOperandVal->getType()->isIntegerTy())
    2822         420 :         weight = CW_Register;
    2823             :       break;
    2824         147 :     case 'X': // any operand.
    2825             :     default:
    2826         147 :       weight = CW_Default;
    2827         147 :       break;
    2828             :   }
    2829             :   return weight;
    2830             : }
    2831             : 
    2832             : /// If there are multiple different constraints that we could pick for this
    2833             : /// operand (e.g. "imr") try to pick the 'best' one.
    2834             : /// This is somewhat tricky: constraints fall into four classes:
    2835             : ///    Other         -> immediates and magic values
    2836             : ///    Register      -> one specific register
    2837             : ///    RegisterClass -> a group of regs
    2838             : ///    Memory        -> memory
    2839             : /// Ideally, we would pick the most specific constraint possible: if we have
    2840             : /// something that fits into a register, we would pick it.  The problem here
    2841             : /// is that if we have something that could either be in a register or in
    2842             : /// memory that use of the register could cause selection of *other*
    2843             : /// operands to fail: they might only succeed if we pick memory.  Because of
    2844             : /// this the heuristic we use is:
    2845             : ///
    2846             : ///  1) If there is an 'other' constraint, and if the operand is valid for
    2847             : ///     that constraint, use it.  This makes us take advantage of 'i'
    2848             : ///     constraints when available.
    2849             : ///  2) Otherwise, pick the most general constraint present.  This prefers
    2850             : ///     'm' over 'r', for example.
    2851             : ///
    2852        9768 : static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
    2853             :                              const TargetLowering &TLI,
    2854             :                              SDValue Op, SelectionDAG *DAG) {
    2855             :   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
    2856        9768 :   unsigned BestIdx = 0;
    2857        9768 :   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
    2858        9768 :   int BestGenerality = -1;
    2859             : 
    2860             :   // Loop over the options, keeping track of the most general one.
    2861      165365 :   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
    2862             :     TargetLowering::ConstraintType CType =
    2863      437691 :       TLI.getConstraintType(OpInfo.Codes[i]);
    2864             : 
    2865             :     // If this is an 'other' constraint, see if the operand is valid for it.
    2866             :     // For example, on X86 we might have an 'rI' constraint.  If the operand
    2867             :     // is an integer in the range [0..31] we want to use I (saving a load
    2868             :     // of a register), otherwise we must use 'r'.
    2869      145897 :     if (CType == TargetLowering::C_Other && Op.getNode()) {
    2870             :       assert(OpInfo.Codes[i].size() == 1 &&
    2871             :              "Unhandled multi-letter 'other' constraint");
    2872         308 :       std::vector<SDValue> ResultOps;
    2873         376 :       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
    2874         188 :                                        ResultOps, *DAG);
    2875         188 :       if (!ResultOps.empty()) {
    2876          68 :         BestType = CType;
    2877          68 :         BestIdx = i;
    2878          68 :         break;
    2879             :       }
    2880             :     }
    2881             : 
    2882             :     // Things with matching constraints can only be registers, per gcc
    2883             :     // documentation.  This mainly affects "g" constraints.
    2884      145862 :     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
    2885          33 :       continue;
    2886             : 
    2887             :     // This constraint letter is more general than the previous one, use it.
    2888      145796 :     int Generality = getConstraintGenerality(CType);
    2889      145796 :     if (Generality > BestGenerality) {
    2890       10167 :       BestType = CType;
    2891       10167 :       BestIdx = i;
    2892       10167 :       BestGenerality = Generality;
    2893             :     }
    2894             :   }
    2895             : 
    2896       29304 :   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
    2897        9768 :   OpInfo.ConstraintType = BestType;
    2898        9768 : }
    2899             : 
    2900             : /// Determines the constraint code and constraint type to use for the specific
    2901             : /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
    2902      213593 : void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
    2903             :                                             SDValue Op,
    2904             :                                             SelectionDAG *DAG) const {
    2905             :   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
    2906             : 
    2907             :   // Single-letter constraints ('r') are very common.
    2908      427186 :   if (OpInfo.Codes.size() == 1) {
    2909      407650 :     OpInfo.ConstraintCode = OpInfo.Codes[0];
    2910      407650 :     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
    2911             :   } else {
    2912        9768 :     ChooseConstraint(OpInfo, *this, Op, DAG);
    2913             :   }
    2914             : 
    2915             :   // 'X' matches anything.
    2916      427186 :   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
    2917             :     // Labels and constants are handled elsewhere ('X' is the only thing
    2918             :     // that matches labels).  For Functions, the type here is the type of
    2919             :     // the result, which is not what we want to look at; leave them alone.
    2920         260 :     Value *v = OpInfo.CallOperandVal;
    2921         980 :     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
    2922             :       OpInfo.CallOperandVal = v;
    2923             :       return;
    2924             :     }
    2925             : 
    2926             :     // Otherwise, try to resolve it to something we know about by looking at
    2927             :     // the actual operand type.
    2928         376 :     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
    2929         370 :       OpInfo.ConstraintCode = Repl;
    2930         370 :       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
    2931             :     }
    2932             :   }
    2933             : }
    2934             : 
    2935             : /// \brief Given an exact SDIV by a constant, create a multiplication
    2936             : /// with the multiplicative inverse of the constant.
    2937         131 : static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
    2938             :                               const SDLoc &dl, SelectionDAG &DAG,
    2939             :                               std::vector<SDNode *> &Created) {
    2940             :   assert(d != 0 && "Division by zero!");
    2941             : 
    2942             :   // Shift the value upfront if it is even, so the LSB is one.
    2943         131 :   unsigned ShAmt = d.countTrailingZeros();
    2944         131 :   if (ShAmt) {
    2945             :     // TODO: For UDIV use SRL instead of SRA.
    2946             :     SDValue Amt =
    2947             :         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
    2948         390 :                                                         DAG.getDataLayout()));
    2949         130 :     SDNodeFlags Flags;
    2950         130 :     Flags.setExact(true);
    2951         260 :     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, Flags);
    2952         260 :     Created.push_back(Op1.getNode());
    2953         130 :     d.ashrInPlace(ShAmt);
    2954             :   }
    2955             : 
    2956             :   // Calculate the multiplicative inverse, using Newton's method.
    2957         393 :   APInt t, xn = d;
    2958        3429 :   while ((t = d*xn) != 1)
    2959        2905 :     xn *= APInt(d.getBitWidth(), 2) - t;
    2960             : 
    2961         262 :   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
    2962         262 :   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
    2963         262 :   Created.push_back(Mul.getNode());
    2964         262 :   return Mul;
    2965             : }
    2966             : 
    2967         128 : SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
    2968             :                                       SelectionDAG &DAG,
    2969             :                                       std::vector<SDNode *> *Created) const {
    2970         128 :   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
    2971         128 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2972         256 :   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
    2973           3 :     return SDValue(N,0); // Lower SDIV as SDIV
    2974         125 :   return SDValue();
    2975             : }
    2976             : 
    2977             : /// \brief Given an ISD::SDIV node expressing a divide by constant,
    2978             : /// return a DAG expression to select that will generate the same value by
    2979             : /// multiplying by a magic number.
    2980             : /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
    2981         674 : SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
    2982             :                                   SelectionDAG &DAG, bool IsAfterLegalization,
    2983             :                                   std::vector<SDNode *> *Created) const {
    2984             :   assert(Created && "No vector to hold sdiv ops.");
    2985             : 
    2986        1348 :   EVT VT = N->getValueType(0);
    2987        1348 :   SDLoc dl(N);
    2988             : 
    2989             :   // Check to see if we can do this.
    2990             :   // FIXME: We should be more aggressive here.
    2991        1304 :   if (!isTypeLegal(VT))
    2992          44 :     return SDValue();
    2993             : 
    2994             :   // If the sdiv has an 'exact' bit we can use a simpler lowering.
    2995        1260 :   if (N->getFlags().hasExact())
    2996         393 :     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
    2997             : 
    2998         499 :   APInt::ms magics = Divisor.magic();
    2999             : 
    3000             :   // Multiply the numerator (operand 0) by the magic value
    3001             :   // FIXME: We should support doing a MUL in a wider type
    3002         499 :   SDValue Q;
    3003         717 :   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
    3004         218 :                             isOperationLegalOrCustom(ISD::MULHS, VT))
    3005         198 :     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
    3006         198 :                     DAG.getConstant(magics.m, dl, VT));
    3007         543 :   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
    3008         143 :                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
    3009         368 :     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
    3010         736 :                               N->getOperand(0),
    3011         736 :                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
    3012             :   else
    3013          32 :     return SDValue();       // No mulhs or equvialent
    3014             :   // If d > 0 and m < 0, add the numerator
    3015         930 :   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
    3016         478 :     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
    3017         478 :     Created->push_back(Q.getNode());
    3018             :   }
    3019             :   // If d < 0 and m > 0, subtract the numerator.
    3020         934 :   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
    3021           0 :     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
    3022           0 :     Created->push_back(Q.getNode());
    3023             :   }
    3024         934 :   auto &DL = DAG.getDataLayout();
    3025             :   // Shift right algebraic if shift value is nonzero
    3026         467 :   if (magics.s > 0) {
    3027         448 :     Q = DAG.getNode(
    3028             :         ISD::SRA, dl, VT, Q,
    3029        1344 :         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
    3030         896 :     Created->push_back(Q.getNode());
    3031             :   }
    3032             :   // Extract the sign bit and add it to the quotient
    3033             :   SDValue T =
    3034             :       DAG.getNode(ISD::SRL, dl, VT, Q,
    3035         467 :                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
    3036        1401 :                                   getShiftAmountTy(Q.getValueType(), DL)));
    3037         934 :   Created->push_back(T.getNode());
    3038         467 :   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
    3039             : }
    3040             : 
    3041             : /// \brief Given an ISD::UDIV node expressing a divide by constant,
    3042             : /// return a DAG expression to select that will generate the same value by
    3043             : /// multiplying by a magic number.
    3044             : /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
    3045         654 : SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
    3046             :                                   SelectionDAG &DAG, bool IsAfterLegalization,
    3047             :                                   std::vector<SDNode *> *Created) const {
    3048             :   assert(Created && "No vector to hold udiv ops.");
    3049             : 
    3050        1308 :   EVT VT = N->getValueType(0);
    3051        1308 :   SDLoc dl(N);
    3052        1308 :   auto &DL = DAG.getDataLayout();
    3053             : 
    3054             :   // Check to see if we can do this.
    3055             :   // FIXME: We should be more aggressive here.
    3056        1268 :   if (!isTypeLegal(VT))
    3057          40 :     return SDValue();
    3058             : 
    3059             :   // FIXME: We should use a narrower constant when the upper
    3060             :   // bits are known to be zero.
    3061         614 :   APInt::mu magics = Divisor.magicu();
    3062             : 
    3063        1228 :   SDValue Q = N->getOperand(0);
    3064             : 
    3065             :   // If the divisor is even, we can avoid using the expensive fixup by shifting
    3066             :   // the divided value upfront.
    3067        1017 :   if (magics.a != 0 && !Divisor[0]) {
    3068          42 :     unsigned Shift = Divisor.countTrailingZeros();
    3069          42 :     Q = DAG.getNode(
    3070             :         ISD::SRL, dl, VT, Q,
    3071         126 :         DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
    3072          84 :     Created->push_back(Q.getNode());
    3073             : 
    3074             :     // Get magic number for the shifted divisor.
    3075         126 :     magics = Divisor.lshr(Shift).magicu(Shift);
    3076             :     assert(magics.a == 0 && "Should use cheap fixup now");
    3077             :   }
    3078             : 
    3079             :   // Multiply the numerator (operand 0) by the magic value
    3080             :   // FIXME: We should support doing a MUL in a wider type
    3081         951 :   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
    3082         337 :                             isOperationLegalOrCustom(ISD::MULHU, VT))
    3083          94 :     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
    3084         783 :   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
    3085         263 :                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
    3086         488 :     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
    3087         488 :                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
    3088             :   else
    3089          32 :     return SDValue();       // No mulhu or equivalent
    3090             : 
    3091        1164 :   Created->push_back(Q.getNode());
    3092             : 
    3093         582 :   if (magics.a == 0) {
    3094             :     assert(magics.s < Divisor.getBitWidth() &&
    3095             :            "We shouldn't generate an undefined shift!");
    3096             :     return DAG.getNode(
    3097             :         ISD::SRL, dl, VT, Q,
    3098         492 :         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
    3099             :   } else {
    3100         672 :     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
    3101         672 :     Created->push_back(NPQ.getNode());
    3102         336 :     NPQ = DAG.getNode(
    3103             :         ISD::SRL, dl, VT, NPQ,
    3104        1008 :         DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
    3105         672 :     Created->push_back(NPQ.getNode());
    3106         336 :     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
    3107         672 :     Created->push_back(NPQ.getNode());
    3108             :     return DAG.getNode(
    3109             :         ISD::SRL, dl, VT, NPQ,
    3110         336 :         DAG.getConstant(magics.s - 1, dl,
    3111        1008 :                         getShiftAmountTy(NPQ.getValueType(), DL)));
    3112             :   }
    3113             : }
    3114             : 
    3115          58 : bool TargetLowering::
    3116             : verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
    3117         116 :   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
    3118           0 :     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
    3119             :                                 "be a constant integer");
    3120           0 :     return true;
    3121             :   }
    3122             : 
    3123             :   return false;
    3124             : }
    3125             : 
    3126             : //===----------------------------------------------------------------------===//
    3127             : // Legalization Utilities
    3128             : //===----------------------------------------------------------------------===//
    3129             : 
    3130         977 : bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
    3131             :                                     SDValue LHS, SDValue RHS,
    3132             :                                     SmallVectorImpl<SDValue> &Result,
    3133             :                                     EVT HiLoVT, SelectionDAG &DAG,
    3134             :                                     MulExpansionKind Kind, SDValue LL,
    3135             :                                     SDValue LH, SDValue RL, SDValue RH) const {
    3136             :   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
    3137             :          Opcode == ISD::SMUL_LOHI);
    3138             : 
    3139         977 :   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
    3140        1954 :                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
    3141         977 :   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
    3142        1954 :                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
    3143         977 :   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
    3144        1954 :                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
    3145         977 :   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
    3146        1954 :                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
    3147             : 
    3148         977 :   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
    3149             :     return false;
    3150             : 
    3151         631 :   unsigned OuterBitSize = VT.getScalarSizeInBits();
    3152         631 :   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
    3153         631 :   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
    3154         631 :   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
    3155             : 
    3156             :   // LL, LH, RL, and RH must be either all NULL or all set to a value.
    3157             :   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
    3158             :          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
    3159             : 
    3160         631 :   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
    3161             :   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
    3162         631 :                           bool Signed) -> bool {
    3163         631 :     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
    3164         904 :       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
    3165         540 :       Hi = SDValue(Lo.getNode(), 1);
    3166         540 :       return true;
    3167             :     }
    3168          91 :     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
    3169         273 :       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
    3170         182 :       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
    3171          91 :       return true;
    3172             :     }
    3173             :     return false;
    3174         631 :   };
    3175             : 
    3176         631 :   SDValue Lo, Hi;
    3177             : 
    3178         631 :   if (!LL.getNode() && !RL.getNode() &&
    3179          37 :       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
    3180          37 :     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
    3181          37 :     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
    3182             :   }
    3183             : 
    3184         631 :   if (!LL.getNode())
    3185             :     return false;
    3186             : 
    3187         631 :   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
    3188         926 :   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
    3189         295 :       DAG.MaskedValueIsZero(RHS, HighMask)) {
    3190             :     // The inputs are both zero-extended.
    3191         294 :     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
    3192         294 :       Result.push_back(Lo);
    3193         294 :       Result.push_back(Hi);
    3194         294 :       if (Opcode != ISD::MUL) {
    3195           0 :         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
    3196           0 :         Result.push_back(Zero);
    3197           0 :         Result.push_back(Zero);
    3198             :       }
    3199             :       return true;
    3200             :     }
    3201             :   }
    3202             : 
    3203         337 :   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
    3204             :       RHSSB > InnerBitSize) {
    3205             :     // The input values are both sign-extended.
    3206             :     // TODO non-MUL case?
    3207         154 :     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
    3208         154 :       Result.push_back(Lo);
    3209         154 :       Result.push_back(Hi);
    3210         154 :       return true;
    3211             :     }
    3212             :   }
    3213             : 
    3214         183 :   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
    3215         366 :   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
    3216         549 :   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
    3217             :     // FIXME getShiftAmountTy does not always return a sensible result when VT
    3218             :     // is an illegal type, and so the type may be too small to fit the shift
    3219             :     // amount. Override it with i32. The shift will have to be legalized.
    3220           0 :     ShiftAmountTy = MVT::i32;
    3221             :   }
    3222         183 :   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
    3223             : 
    3224         197 :   if (!LH.getNode() && !RH.getNode() &&
    3225         197 :       isOperationLegalOrCustom(ISD::SRL, VT) &&
    3226          14 :       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
    3227          14 :     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
    3228          14 :     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
    3229          14 :     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
    3230          14 :     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
    3231             :   }
    3232             : 
    3233         183 :   if (!LH.getNode())
    3234             :     return false;
    3235             : 
    3236         183 :   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
    3237             :     return false;
    3238             : 
    3239         183 :   Result.push_back(Lo);
    3240             : 
    3241         183 :   if (Opcode == ISD::MUL) {
    3242         183 :     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
    3243         183 :     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
    3244         183 :     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
    3245         183 :     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
    3246         183 :     Result.push_back(Hi);
    3247         183 :     return true;
    3248             :   }
    3249             : 
    3250             :   // Compute the full width result.
    3251           0 :   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
    3252           0 :     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
    3253           0 :     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
    3254           0 :     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
    3255           0 :     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
    3256           0 :   };
    3257             : 
    3258           0 :   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
    3259           0 :   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
    3260             :     return false;
    3261             : 
    3262             :   // This is effectively the add part of a multiply-add of half-sized operands,
    3263             :   // so it cannot overflow.
    3264           0 :   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
    3265             : 
    3266           0 :   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
    3267             :     return false;
    3268             : 
    3269           0 :   Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
    3270           0 :                      Merge(Lo, Hi));
    3271             : 
    3272           0 :   SDValue Carry = Next.getValue(1);
    3273           0 :   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
    3274           0 :   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
    3275             : 
    3276           0 :   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
    3277             :     return false;
    3278             : 
    3279           0 :   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
    3280           0 :   Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
    3281           0 :                    Carry);
    3282           0 :   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
    3283             : 
    3284           0 :   if (Opcode == ISD::SMUL_LOHI) {
    3285             :     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
    3286           0 :                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
    3287           0 :     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
    3288             : 
    3289           0 :     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
    3290           0 :                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
    3291           0 :     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
    3292             :   }
    3293             : 
    3294           0 :   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
    3295           0 :   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
    3296           0 :   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
    3297           0 :   return true;
    3298             : }
    3299             : 
    3300         977 : bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
    3301             :                                SelectionDAG &DAG, MulExpansionKind Kind,
    3302             :                                SDValue LL, SDValue LH, SDValue RL,
    3303             :                                SDValue RH) const {
    3304        1954 :   SmallVector<SDValue, 2> Result;
    3305        2931 :   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
    3306        2931 :                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
    3307         977 :                            DAG, Kind, LL, LH, RL, RH);
    3308         977 :   if (Ok) {
    3309             :     assert(Result.size() == 2);
    3310         631 :     Lo = Result[0];
    3311         631 :     Hi = Result[1];
    3312             :   }
    3313        1954 :   return Ok;
    3314             : }
    3315             : 
    3316          74 : bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
    3317             :                                SelectionDAG &DAG) const {
    3318         222 :   EVT VT = Node->getOperand(0).getValueType();
    3319         148 :   EVT NVT = Node->getValueType(0);
    3320         222 :   SDLoc dl(SDValue(Node, 0));
    3321             : 
    3322             :   // FIXME: Only f32 to i64 conversions are supported.
    3323         148 :   if (VT != MVT::f32 || NVT != MVT::i64)
    3324             :     return false;
    3325             : 
    3326             :   // Expand f32 -> i64 conversion
    3327             :   // This algorithm comes from compiler-rt's implementation of fixsfdi:
    3328             :   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
    3329          74 :   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
    3330         148 :                                 VT.getSizeInBits());
    3331          74 :   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
    3332          74 :   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
    3333          74 :   SDValue Bias = DAG.getConstant(127, dl, IntVT);
    3334         222 :   SDValue SignMask = DAG.getConstant(APInt::getSignMask(VT.getSizeInBits()), dl,
    3335          74 :                                      IntVT);
    3336          74 :   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
    3337          74 :   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
    3338             : 
    3339         148 :   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
    3340             : 
    3341         148 :   auto &DL = DAG.getDataLayout();
    3342             :   SDValue ExponentBits = DAG.getNode(
    3343             :       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
    3344         148 :       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
    3345          74 :   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
    3346             : 
    3347             :   SDValue Sign = DAG.getNode(
    3348             :       ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
    3349         148 :       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
    3350          74 :   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
    3351             : 
    3352             :   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
    3353             :       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
    3354         148 :       DAG.getConstant(0x00800000, dl, IntVT));
    3355             : 
    3356          74 :   R = DAG.getZExtOrTrunc(R, dl, NVT);
    3357             : 
    3358          74 :   R = DAG.getSelectCC(
    3359             :       dl, Exponent, ExponentLoBit,
    3360             :       DAG.getNode(ISD::SHL, dl, NVT, R,
    3361             :                   DAG.getZExtOrTrunc(
    3362             :                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
    3363             :                       dl, getShiftAmountTy(IntVT, DL))),
    3364             :       DAG.getNode(ISD::SRL, dl, NVT, R,
    3365             :                   DAG.getZExtOrTrunc(
    3366             :                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
    3367             :                       dl, getShiftAmountTy(IntVT, DL))),
    3368         370 :       ISD::SETGT);
    3369             : 
    3370             :   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
    3371             :       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
    3372         148 :       Sign);
    3373             : 
    3374          74 :   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
    3375          74 :       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
    3376          74 :   return true;
    3377             : }
    3378             : 
    3379        1663 : SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
    3380             :                                             SelectionDAG &DAG) const {
    3381        3326 :   SDLoc SL(LD);
    3382        3326 :   SDValue Chain = LD->getChain();
    3383        1663 :   SDValue BasePTR = LD->getBasePtr();
    3384        1663 :   EVT SrcVT = LD->getMemoryVT();
    3385        1663 :   ISD::LoadExtType ExtType = LD->getExtensionType();
    3386             : 
    3387        1663 :   unsigned NumElem = SrcVT.getVectorNumElements();
    3388             : 
    3389        1663 :   EVT SrcEltVT = SrcVT.getScalarType();
    3390        3326 :   EVT DstEltVT = LD->getValueType(0).getScalarType();
    3391             : 
    3392        1663 :   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
    3393             :   assert(SrcEltVT.isByteSized());
    3394             : 
    3395        3326 :   EVT PtrVT = BasePTR.getValueType();
    3396             : 
    3397        3326 :   SmallVector<SDValue, 8> Vals;
    3398        3326 :   SmallVector<SDValue, 8> LoadChains;
    3399             : 
    3400        8805 :   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
    3401             :     SDValue ScalarLoad =
    3402             :         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
    3403        7142 :                        LD->getPointerInfo().getWithOffset(Idx * Stride),
    3404       21426 :                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
    3405       35710 :                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3406             : 
    3407        7142 :     BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
    3408       14284 :                           DAG.getConstant(Stride, SL, PtrVT));
    3409             : 
    3410       14284 :     Vals.push_back(ScalarLoad.getValue(0));
    3411       14284 :     LoadChains.push_back(ScalarLoad.getValue(1));
    3412             :   }
    3413             : 
    3414        4989 :   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
    3415        3326 :   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
    3416             : 
    3417        4989 :   return DAG.getMergeValues({ Value, NewChain }, SL);
    3418             : }
    3419             : 
    3420             : // FIXME: This relies on each element having a byte size, otherwise the stride
    3421             : // is 0 and just overwrites the same location. ExpandStore currently expects
    3422             : // this broken behavior.
    3423        1480 : SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
    3424             :                                              SelectionDAG &DAG) const {
    3425        2960 :   SDLoc SL(ST);
    3426             : 
    3427        2960 :   SDValue Chain = ST->getChain();
    3428        1480 :   SDValue BasePtr = ST->getBasePtr();
    3429        1480 :   SDValue Value = ST->getValue();
    3430        1480 :   EVT StVT = ST->getMemoryVT();
    3431             : 
    3432             :   // The type of the data we want to save
    3433        2960 :   EVT RegVT = Value.getValueType();
    3434        1480 :   EVT RegSclVT = RegVT.getScalarType();
    3435             : 
    3436             :   // The type of data as saved in memory.
    3437        1480 :   EVT MemSclVT = StVT.getScalarType();
    3438             : 
    3439        2960 :   EVT PtrVT = BasePtr.getValueType();
    3440             : 
    3441             :   // Store Stride in bytes
    3442        1480 :   unsigned Stride = MemSclVT.getSizeInBits() / 8;
    3443        4440 :   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
    3444        1480 :   unsigned NumElem = StVT.getVectorNumElements();
    3445             : 
    3446             :   // Extract each of the elements from the original vector and save them into
    3447             :   // memory individually.
    3448        2960 :   SmallVector<SDValue, 8> Stores;
    3449       11024 :   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
    3450             :     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
    3451        9544 :                               DAG.getConstant(Idx, SL, IdxVT));
    3452             : 
    3453             :     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
    3454        9544 :                               DAG.getConstant(Idx * Stride, SL, PtrVT));
    3455             : 
    3456             :     // This scalar TruncStore may be illegal, but we legalize it later.
    3457             :     SDValue Store = DAG.getTruncStore(
    3458        9544 :         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
    3459       28632 :         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
    3460       47720 :         ST->getMemOperand()->getFlags(), ST->getAAInfo());
    3461             : 
    3462        9544 :     Stores.push_back(Store);
    3463             :   }
    3464             : 
    3465        5920 :   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
    3466             : }
    3467             : 
    3468             : std::pair<SDValue, SDValue>
    3469         886 : TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
    3470             :   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
    3471             :          "unaligned indexed loads not implemented!");
    3472        1772 :   SDValue Chain = LD->getChain();
    3473         886 :   SDValue Ptr = LD->getBasePtr();
    3474        1772 :   EVT VT = LD->getValueType(0);
    3475         886 :   EVT LoadedVT = LD->getMemoryVT();
    3476        1772 :   SDLoc dl(LD);
    3477        1709 :   if (VT.isFloatingPoint() || VT.isVector()) {
    3478          64 :     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
    3479         148 :     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
    3480          42 :       if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
    3481             :         // Scalarize the load and let the individual components be handled.
    3482           0 :         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
    3483           0 :         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
    3484             :       }
    3485             : 
    3486             :       // Expand to a (misaligned) integer load of the same size,
    3487             :       // then bitconvert to floating point or vector.
    3488             :       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
    3489          42 :                                     LD->getMemOperand());
    3490          42 :       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
    3491          42 :       if (LoadedVT != VT)
    3492           0 :         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
    3493           0 :                              ISD::ANY_EXTEND, dl, VT, Result);
    3494             : 
    3495         126 :       return std::make_pair(Result, newLoad.getValue(1));
    3496             :     }
    3497             : 
    3498             :     // Copy the value to a (aligned) stack slot using (unaligned) integer
    3499             :     // loads and stores, then do a (aligned) load from the stack slot.
    3500          22 :     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
    3501          22 :     unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
    3502          22 :     unsigned RegBytes = RegVT.getSizeInBits() / 8;
    3503          22 :     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
    3504             : 
    3505             :     // Make sure the stack slot is also aligned for the register type.
    3506          22 :     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
    3507             : 
    3508          22 :     SmallVector<SDValue, 8> Stores;
    3509          22 :     SDValue StackPtr = StackBase;
    3510          22 :     unsigned Offset = 0;
    3511             : 
    3512          44 :     EVT PtrVT = Ptr.getValueType();
    3513          44 :     EVT StackPtrVT = StackPtr.getValueType();
    3514             : 
    3515          22 :     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
    3516          22 :     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
    3517             : 
    3518             :     // Do all but one copies using the full register width.
    3519          86 :     for (unsigned i = 1; i < NumRegs; i++) {
    3520             :       // Load one integer register's worth from the original location.
    3521             :       SDValue Load = DAG.getLoad(
    3522          21 :           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
    3523          84 :           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
    3524         126 :           LD->getAAInfo());
    3525             :       // Follow the load with a store to the stack slot.  Remember the store.
    3526          21 :       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
    3527          84 :                                     MachinePointerInfo()));
    3528             :       // Increment the pointers.
    3529          21 :       Offset += RegBytes;
    3530          21 :       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
    3531          21 :       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
    3532          42 :                              StackPtrIncrement);
    3533             :     }
    3534             : 
    3535             :     // The last copy may be partial.  Do an extending load.
    3536          22 :     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
    3537          44 :                                   8 * (LoadedBytes - Offset));
    3538             :     SDValue Load =
    3539             :         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
    3540          22 :                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
    3541          66 :                        MinAlign(LD->getAlignment(), Offset),
    3542         132 :                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3543             :     // Follow the load with a store to the stack slot.  Remember the store.
    3544             :     // On big-endian machines this requires a truncating store to ensure
    3545             :     // that the bits end up in the right place.
    3546          22 :     Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
    3547          88 :                                        MachinePointerInfo(), MemVT));
    3548             : 
    3549             :     // The order of the stores doesn't matter - say it with a TokenFactor.
    3550          66 :     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
    3551             : 
    3552             :     // Finally, perform the original load only redirected to the stack slot.
    3553          22 :     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
    3554          88 :                           MachinePointerInfo(), LoadedVT);
    3555             : 
    3556             :     // Callers expect a MERGE_VALUES node.
    3557          22 :     return std::make_pair(Load, TF);
    3558             :   }
    3559             : 
    3560             :   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
    3561             :          "Unaligned load of unsupported type.");
    3562             : 
    3563             :   // Compute the new VT that is half the size of the old one.  This is an
    3564             :   // integer MVT.
    3565         822 :   unsigned NumBits = LoadedVT.getSizeInBits();
    3566             :   EVT NewLoadedVT;
    3567         822 :   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
    3568         822 :   NumBits >>= 1;
    3569             : 
    3570        1644 :   unsigned Alignment = LD->getAlignment();
    3571         822 :   unsigned IncrementSize = NumBits / 8;
    3572         822 :   ISD::LoadExtType HiExtType = LD->getExtensionType();
    3573             : 
    3574             :   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
    3575         822 :   if (HiExtType == ISD::NON_EXTLOAD)
    3576         399 :     HiExtType = ISD::ZEXTLOAD;
    3577             : 
    3578             :   // Load the value in two parts
    3579         822 :   SDValue Lo, Hi;
    3580        1644 :   if (DAG.getDataLayout().isLittleEndian()) {
    3581        1496 :     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
    3582         748 :                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
    3583        2244 :                         LD->getAAInfo());
    3584         748 :     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
    3585        2244 :                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
    3586         748 :     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
    3587         748 :                         LD->getPointerInfo().getWithOffset(IncrementSize),
    3588        1496 :                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
    3589        4488 :                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3590             :   } else {
    3591         148 :     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
    3592          74 :                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
    3593         222 :                         LD->getAAInfo());
    3594          74 :     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
    3595         222 :                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
    3596          74 :     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
    3597          74 :                         LD->getPointerInfo().getWithOffset(IncrementSize),
    3598         148 :                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
    3599         444 :                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
    3600             :   }
    3601             : 
    3602             :   // aggregate the two parts
    3603             :   SDValue ShiftAmount =
    3604             :       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
    3605        2466 :                                                     DAG.getDataLayout()));
    3606         822 :   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
    3607         822 :   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
    3608             : 
    3609             :   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
    3610        3288 :                              Hi.getValue(1));
    3611             : 
    3612             :   return std::make_pair(Result, TF);
    3613             : }
    3614             : 
    3615         925 : SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
    3616             :                                              SelectionDAG &DAG) const {
    3617             :   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
    3618             :          "unaligned indexed stores not implemented!");
    3619        1850 :   SDValue Chain = ST->getChain();
    3620         925 :   SDValue Ptr = ST->getBasePtr();
    3621         925 :   SDValue Val = ST->getValue();
    3622        1850 :   EVT VT = Val.getValueType();
    3623        1850 :   int Alignment = ST->getAlignment();
    3624             : 
    3625        1850 :   SDLoc dl(ST);
    3626        2724 :   if (ST->getMemoryVT().isFloatingPoint() ||
    3627        2673 :       ST->getMemoryVT().isVector()) {
    3628          79 :     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
    3629         135 :     if (isTypeLegal(intVT)) {
    3630          74 :       if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
    3631             :         // Scalarize the store and let the individual components be handled.
    3632          18 :         SDValue Result = scalarizeVectorStore(ST, DAG);
    3633             : 
    3634          18 :         return Result;
    3635             :       }
    3636             :       // Expand to a bitconvert of the value to the integer type of the
    3637             :       // same size, then a (misaligned) int store.
    3638             :       // FIXME: Does not handle truncating floating point stores!
    3639          38 :       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
    3640          76 :       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
    3641          76 :                             Alignment, ST->getMemOperand()->getFlags());
    3642          38 :       return Result;
    3643             :     }
    3644             :     // Do a (aligned) store to a stack slot, then copy from the stack slot
    3645             :     // to the final destination using (unaligned) integer loads and stores.
    3646          23 :     EVT StoredVT = ST->getMemoryVT();
    3647             :     MVT RegVT =
    3648          23 :       getRegisterType(*DAG.getContext(),
    3649          23 :                       EVT::getIntegerVT(*DAG.getContext(),
    3650          69 :                                         StoredVT.getSizeInBits()));
    3651          46 :     EVT PtrVT = Ptr.getValueType();
    3652          23 :     unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
    3653          23 :     unsigned RegBytes = RegVT.getSizeInBits() / 8;
    3654          23 :     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
    3655             : 
    3656             :     // Make sure the stack slot is also aligned for the register type.
    3657          23 :     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
    3658             : 
    3659             :     // Perform the original store, only redirected to the stack slot.
    3660             :     SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
    3661          46 :                                       MachinePointerInfo(), StoredVT);
    3662             : 
    3663          46 :     EVT StackPtrVT = StackPtr.getValueType();
    3664             : 
    3665          23 :     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
    3666          23 :     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
    3667          23 :     SmallVector<SDValue, 8> Stores;
    3668          23 :     unsigned Offset = 0;
    3669             : 
    3670             :     // Do all but one copies using the full register width.
    3671          46 :     for (unsigned i = 1; i < NumRegs; i++) {
    3672             :       // Load one integer register's worth from the stack slot.
    3673             :       SDValue Load =
    3674          69 :           DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
    3675             :       // Store it to the final location.  Remember the store.
    3676          23 :       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
    3677          23 :                                     ST->getPointerInfo().getWithOffset(Offset),
    3678          69 :                                     MinAlign(ST->getAlignment(), Offset),
    3679         138 :                                     ST->getMemOperand()->getFlags()));
    3680             :       // Increment the pointers.
    3681          23 :       Offset += RegBytes;
    3682          23 :       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
    3683          46 :                              StackPtr, StackPtrIncrement);
    3684          23 :       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
    3685             :     }
    3686             : 
    3687             :     // The last store may be partial.  Do a truncating store.  On big-endian
    3688             :     // machines this requires an extending load from the stack slot to ensure
    3689             :     // that the bits are in the right place.
    3690          23 :     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
    3691          46 :                                   8 * (StoredBytes - Offset));
    3692             : 
    3693             :     // Load from the stack slot.
    3694             :     SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
    3695          69 :                                   MachinePointerInfo(), MemVT);
    3696             : 
    3697          23 :     Stores.push_back(
    3698          46 :         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
    3699          23 :                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
    3700          69 :                           MinAlign(ST->getAlignment(), Offset),
    3701         161 :                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
    3702             :     // The order of the stores doesn't matter - say it with a TokenFactor.
    3703          69 :     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
    3704          23 :     return Result;
    3705             :   }
    3706             : 
    3707             :   assert(ST->getMemoryVT().isInteger() &&
    3708             :          !ST->getMemoryVT().isVector() &&
    3709             :          "Unaligned store of unknown type.");
    3710             :   // Get the half-size VT
    3711         846 :   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
    3712         846 :   int NumBits = NewStoredVT.getSizeInBits();
    3713         846 :   int IncrementSize = NumBits / 8;
    3714             : 
    3715             :   // Divide the stored value in two parts.
    3716             :   SDValue ShiftAmount =
    3717             :       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
    3718        2538 :                                                     DAG.getDataLayout()));
    3719         846 :   SDValue Lo = Val;
    3720         846 :   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
    3721             : 
    3722             :   // Store the two parts
    3723         846 :   SDValue Store1, Store2;
    3724         846 :   Store1 = DAG.getTruncStore(Chain, dl,
    3725        1692 :                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
    3726         846 :                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
    3727        1692 :                              ST->getMemOperand()->getFlags());
    3728             : 
    3729        1692 :   EVT PtrVT = Ptr.getValueType();
    3730         846 :   Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
    3731        1692 :                     DAG.getConstant(IncrementSize, dl, PtrVT));
    3732        1692 :   Alignment = MinAlign(Alignment, IncrementSize);
    3733         846 :   Store2 = DAG.getTruncStore(
    3734        1692 :       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
    3735         846 :       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
    3736        4230 :       ST->getMemOperand()->getFlags(), ST->getAAInfo());
    3737             : 
    3738             :   SDValue Result =
    3739        1692 :     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
    3740         846 :   return Result;
    3741             : }
    3742             : 
    3743             : SDValue
    3744          32 : TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
    3745             :                                        const SDLoc &DL, EVT DataVT,
    3746             :                                        SelectionDAG &DAG,
    3747             :                                        bool IsCompressedMemory) const {
    3748          32 :   SDValue Increment;
    3749          64 :   EVT AddrVT = Addr.getValueType();
    3750          64 :   EVT MaskVT = Mask.getValueType();
    3751             :   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
    3752             :          "Incompatible types of Data and Mask");
    3753          32 :   if (IsCompressedMemory) {
    3754             :     // Incrementing the pointer according to number of '1's in the mask.
    3755           8 :     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
    3756           8 :     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
    3757           8 :     if (MaskIntVT.getSizeInBits() < 32) {
    3758          16 :       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
    3759           8 :       MaskIntVT = MVT::i32;
    3760             :     }
    3761             : 
    3762             :     // Count '1's with POPCNT.
    3763           8 :     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
    3764           8 :     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
    3765             :     // Scale is an element size in bytes.
    3766           8 :     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
    3767           8 :                                     AddrVT);
    3768           8 :     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
    3769             :   } else
    3770          24 :     Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT);
    3771             : 
    3772          32 :   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
    3773             : }
    3774             : 
    3775        2206 : static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
    3776             :                                        SDValue Idx,
    3777             :                                        EVT VecVT,
    3778             :                                        const SDLoc &dl) {
    3779         757 :   if (isa<ConstantSDNode>(Idx))
    3780        1449 :     return Idx;
    3781             : 
    3782        1514 :   EVT IdxVT = Idx.getValueType();
    3783         757 :   unsigned NElts = VecVT.getVectorNumElements();
    3784         757 :   if (isPowerOf2_32(NElts)) {
    3785             :     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
    3786        1514 :                                      Log2_32(NElts));
    3787             :     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
    3788         757 :                        DAG.getConstant(Imm, dl, IdxVT));
    3789             :   }
    3790             : 
    3791             :   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
    3792           0 :                      DAG.getConstant(NElts - 1, dl, IdxVT));
    3793             : }
    3794             : 
    3795        2206 : SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
    3796             :                                                 SDValue VecPtr, EVT VecVT,
    3797             :                                                 SDValue Index) const {
    3798        4412 :   SDLoc dl(Index);
    3799             :   // Make sure the index type is big enough to compute in.
    3800        8824 :   Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout()));
    3801             : 
    3802        2206 :   EVT EltVT = VecVT.getVectorElementType();
    3803             : 
    3804             :   // Calculate the element offset and add it to the pointer.
    3805        2206 :   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
    3806             :   assert(EltSize * 8 == EltVT.getSizeInBits() &&
    3807             :          "Converting bits to bytes lost precision");
    3808             : 
    3809        2206 :   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
    3810             : 
    3811        4412 :   EVT IdxVT = Index.getValueType();
    3812             : 
    3813        2206 :   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
    3814        4412 :                       DAG.getConstant(EltSize, dl, IdxVT));
    3815        4412 :   return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr);
    3816             : }
    3817             : 
    3818             : //===----------------------------------------------------------------------===//
    3819             : // Implementation of Emulated TLS Model
    3820             : //===----------------------------------------------------------------------===//
    3821             : 
    3822         200 : SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
    3823             :                                                 SelectionDAG &DAG) const {
    3824             :   // Access to address of TLS varialbe xyz is lowered to a function call:
    3825             :   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
    3826         800 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3827         200 :   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
    3828         400 :   SDLoc dl(GA);
    3829             : 
    3830         400 :   ArgListTy Args;
    3831         200 :   ArgListEntry Entry;
    3832         600 :   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
    3833         200 :   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
    3834         200 :   StringRef EmuTlsVarName(NameString);
    3835         200 :   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
    3836             :   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
    3837         200 :   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
    3838         200 :   Entry.Ty = VoidPtrType;
    3839         200 :   Args.push_back(Entry);
    3840             : 
    3841         200 :   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
    3842             : 
    3843         400 :   TargetLowering::CallLoweringInfo CLI(DAG);
    3844         600 :   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
    3845         200 :   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
    3846         200 :   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    3847             : 
    3848             :   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
    3849             :   // At last for X86 targets, maybe good for other targets too?
    3850         200 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    3851         200 :   MFI.setAdjustsStack(true);  // Is this only for X86 target?
    3852         200 :   MFI.setHasCalls(true);
    3853             : 
    3854             :   assert((GA->getOffset() == 0) &&
    3855             :          "Emulated TLS must have zero offset in GlobalAddressSDNode");
    3856         400 :   return CallResult.first;
    3857             : }
    3858             : 
    3859          25 : SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
    3860             :                                                 SelectionDAG &DAG) const {
    3861             :   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
    3862          25 :   if (!isCtlzFast())
    3863           0 :     return SDValue();
    3864          75 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    3865          25 :   SDLoc dl(Op);
    3866          73 :   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
    3867          23 :     if (C->isNullValue() && CC == ISD::SETEQ) {
    3868          21 :       EVT VT = Op.getOperand(0).getValueType();
    3869          14 :       SDValue Zext = Op.getOperand(0);
    3870           7 :       if (VT.bitsLT(MVT::i32)) {
    3871           0 :         VT = MVT::i32;
    3872           0 :         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
    3873             :       }
    3874          14 :       unsigned Log2b = Log2_32(VT.getSizeInBits());
    3875           7 :       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
    3876             :       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
    3877          14 :                                 DAG.getConstant(Log2b, dl, MVT::i32));
    3878          14 :       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
    3879             :     }
    3880             :   }
    3881          18 :   return SDValue();
    3882             : }

Generated by: LCOV version 1.13