LCOV - code coverage report
Current view: top level - lib/CodeGen/SelectionDAG - TargetLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1693 1794 94.4 %
Date: 2018-07-13 00:08:38 Functions: 58 60 96.7 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13