LLVM  mainline
TargetLowering.cpp
Go to the documentation of this file.
00001 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the TargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Target/TargetLowering.h"
00015 #include "llvm/ADT/BitVector.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/CodeGen/Analysis.h"
00018 #include "llvm/CodeGen/MachineFrameInfo.h"
00019 #include "llvm/CodeGen/MachineFunction.h"
00020 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00021 #include "llvm/CodeGen/SelectionDAG.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/GlobalVariable.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/MC/MCAsmInfo.h"
00027 #include "llvm/MC/MCExpr.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/Support/MathExtras.h"
00031 #include "llvm/Target/TargetLoweringObjectFile.h"
00032 #include "llvm/Target/TargetMachine.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include <cctype>
00036 using namespace llvm;
00037 
00038 /// NOTE: The TargetMachine owns TLOF.
00039 TargetLowering::TargetLowering(const TargetMachine &tm)
00040   : TargetLoweringBase(tm) {}
00041 
00042 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
00043   return nullptr;
00044 }
00045 
00046 /// Check whether a given call node is in tail position within its function. If
00047 /// so, it sets Chain to the input chain of the tail call.
00048 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
00049                                           SDValue &Chain) const {
00050   const Function *F = DAG.getMachineFunction().getFunction();
00051 
00052   // Conservatively require the attributes of the call to match those of
00053   // the return. Ignore noalias because it doesn't affect the call sequence.
00054   AttributeSet CallerAttrs = F->getAttributes();
00055   if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
00056       .removeAttribute(Attribute::NoAlias).hasAttributes())
00057     return false;
00058 
00059   // It's not safe to eliminate the sign / zero extension of the return value.
00060   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
00061       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
00062     return false;
00063 
00064   // Check if the only use is a function return node.
00065   return isUsedByReturnOnly(Node, Chain);
00066 }
00067 
00068 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
00069 /// and called function attributes.
00070 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
00071                                                  unsigned AttrIdx) {
00072   isSExt     = CS->paramHasAttr(AttrIdx, Attribute::SExt);
00073   isZExt     = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
00074   isInReg    = CS->paramHasAttr(AttrIdx, Attribute::InReg);
00075   isSRet     = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
00076   isNest     = CS->paramHasAttr(AttrIdx, Attribute::Nest);
00077   isByVal    = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
00078   isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
00079   isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
00080   Alignment  = CS->getParamAlignment(AttrIdx);
00081 }
00082 
00083 /// Generate a libcall taking the given operands as arguments and returning a
00084 /// result of type RetVT.
00085 std::pair<SDValue, SDValue>
00086 TargetLowering::makeLibCall(SelectionDAG &DAG,
00087                             RTLIB::Libcall LC, EVT RetVT,
00088                             const SDValue *Ops, unsigned NumOps,
00089                             bool isSigned, SDLoc dl,
00090                             bool doesNotReturn,
00091                             bool isReturnValueUsed) const {
00092   TargetLowering::ArgListTy Args;
00093   Args.reserve(NumOps);
00094 
00095   TargetLowering::ArgListEntry Entry;
00096   for (unsigned i = 0; i != NumOps; ++i) {
00097     Entry.Node = Ops[i];
00098     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
00099     Entry.isSExt = shouldSignExtendTypeInLibCall(Ops[i].getValueType(), isSigned);
00100     Entry.isZExt = !shouldSignExtendTypeInLibCall(Ops[i].getValueType(), isSigned);
00101     Args.push_back(Entry);
00102   }
00103   if (LC == RTLIB::UNKNOWN_LIBCALL)
00104     report_fatal_error("Unsupported library call operation!");
00105   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy());
00106 
00107   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
00108   TargetLowering::CallLoweringInfo CLI(DAG);
00109   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
00110   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
00111     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
00112     .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
00113     .setSExtResult(signExtend).setZExtResult(!signExtend);
00114   return LowerCallTo(CLI);
00115 }
00116 
00117 
00118 /// SoftenSetCCOperands - Soften the operands of a comparison.  This code is
00119 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
00120 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
00121                                          SDValue &NewLHS, SDValue &NewRHS,
00122                                          ISD::CondCode &CCCode,
00123                                          SDLoc dl) const {
00124   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
00125          && "Unsupported setcc type!");
00126 
00127   // Expand into one or more soft-fp libcall(s).
00128   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
00129   switch (CCCode) {
00130   case ISD::SETEQ:
00131   case ISD::SETOEQ:
00132     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
00133           (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
00134     break;
00135   case ISD::SETNE:
00136   case ISD::SETUNE:
00137     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
00138           (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
00139     break;
00140   case ISD::SETGE:
00141   case ISD::SETOGE:
00142     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
00143           (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
00144     break;
00145   case ISD::SETLT:
00146   case ISD::SETOLT:
00147     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
00148           (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
00149     break;
00150   case ISD::SETLE:
00151   case ISD::SETOLE:
00152     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
00153           (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
00154     break;
00155   case ISD::SETGT:
00156   case ISD::SETOGT:
00157     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
00158           (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
00159     break;
00160   case ISD::SETUO:
00161     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
00162           (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
00163     break;
00164   case ISD::SETO:
00165     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
00166           (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
00167     break;
00168   default:
00169     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
00170           (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
00171     switch (CCCode) {
00172     case ISD::SETONE:
00173       // SETONE = SETOLT | SETOGT
00174       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
00175             (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
00176       // Fallthrough
00177     case ISD::SETUGT:
00178       LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
00179             (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
00180       break;
00181     case ISD::SETUGE:
00182       LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
00183             (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
00184       break;
00185     case ISD::SETULT:
00186       LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
00187             (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
00188       break;
00189     case ISD::SETULE:
00190       LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
00191             (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
00192       break;
00193     case ISD::SETUEQ:
00194       LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
00195             (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
00196       break;
00197     default: llvm_unreachable("Do not know how to soften this setcc!");
00198     }
00199   }
00200 
00201   // Use the target specific return value for comparions lib calls.
00202   EVT RetVT = getCmpLibcallReturnType();
00203   SDValue Ops[2] = { NewLHS, NewRHS };
00204   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/,
00205                        dl).first;
00206   NewRHS = DAG.getConstant(0, RetVT);
00207   CCCode = getCmpLibcallCC(LC1);
00208   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
00209     SDValue Tmp = DAG.getNode(ISD::SETCC, dl,
00210                               getSetCCResultType(*DAG.getContext(), RetVT),
00211                               NewLHS, NewRHS, DAG.getCondCode(CCCode));
00212     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/,
00213                          dl).first;
00214     NewLHS = DAG.getNode(ISD::SETCC, dl,
00215                          getSetCCResultType(*DAG.getContext(), RetVT), NewLHS,
00216                          NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
00217     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
00218     NewRHS = SDValue();
00219   }
00220 }
00221 
00222 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
00223 /// current function.  The returned value is a member of the
00224 /// MachineJumpTableInfo::JTEntryKind enum.
00225 unsigned TargetLowering::getJumpTableEncoding() const {
00226   // In non-pic modes, just use the address of a block.
00227   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
00228     return MachineJumpTableInfo::EK_BlockAddress;
00229 
00230   // In PIC mode, if the target supports a GPRel32 directive, use it.
00231   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
00232     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
00233 
00234   // Otherwise, use a label difference.
00235   return MachineJumpTableInfo::EK_LabelDifference32;
00236 }
00237 
00238 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
00239                                                  SelectionDAG &DAG) const {
00240   // If our PIC model is GP relative, use the global offset table as the base.
00241   unsigned JTEncoding = getJumpTableEncoding();
00242 
00243   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
00244       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
00245     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
00246 
00247   return Table;
00248 }
00249 
00250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
00251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
00252 /// MCExpr.
00253 const MCExpr *
00254 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
00255                                              unsigned JTI,MCContext &Ctx) const{
00256   // The normal PIC reloc base is the label at the start of the jump table.
00257   return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
00258 }
00259 
00260 bool
00261 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
00262   // Assume that everything is safe in static mode.
00263   if (getTargetMachine().getRelocationModel() == Reloc::Static)
00264     return true;
00265 
00266   // In dynamic-no-pic mode, assume that known defined values are safe.
00267   if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
00268       GA &&
00269       !GA->getGlobal()->isDeclaration() &&
00270       !GA->getGlobal()->isWeakForLinker())
00271     return true;
00272 
00273   // Otherwise assume nothing is safe.
00274   return false;
00275 }
00276 
00277 //===----------------------------------------------------------------------===//
00278 //  Optimization Methods
00279 //===----------------------------------------------------------------------===//
00280 
00281 /// ShrinkDemandedConstant - Check to see if the specified operand of the
00282 /// specified instruction is a constant integer.  If so, check to see if there
00283 /// are any bits set in the constant that are not demanded.  If so, shrink the
00284 /// constant and return true.
00285 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
00286                                                         const APInt &Demanded) {
00287   SDLoc dl(Op);
00288 
00289   // FIXME: ISD::SELECT, ISD::SELECT_CC
00290   switch (Op.getOpcode()) {
00291   default: break;
00292   case ISD::XOR:
00293   case ISD::AND:
00294   case ISD::OR: {
00295     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
00296     if (!C) return false;
00297 
00298     if (Op.getOpcode() == ISD::XOR &&
00299         (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
00300       return false;
00301 
00302     // if we can expand it to have all bits set, do it
00303     if (C->getAPIntValue().intersects(~Demanded)) {
00304       EVT VT = Op.getValueType();
00305       SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
00306                                 DAG.getConstant(Demanded &
00307                                                 C->getAPIntValue(),
00308                                                 VT));
00309       return CombineTo(Op, New);
00310     }
00311 
00312     break;
00313   }
00314   }
00315 
00316   return false;
00317 }
00318 
00319 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
00320 /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
00321 /// cast, but it could be generalized for targets with other types of
00322 /// implicit widening casts.
00323 bool
00324 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
00325                                                     unsigned BitWidth,
00326                                                     const APInt &Demanded,
00327                                                     SDLoc dl) {
00328   assert(Op.getNumOperands() == 2 &&
00329          "ShrinkDemandedOp only supports binary operators!");
00330   assert(Op.getNode()->getNumValues() == 1 &&
00331          "ShrinkDemandedOp only supports nodes with one result!");
00332 
00333   // Early return, as this function cannot handle vector types.
00334   if (Op.getValueType().isVector())
00335     return false;
00336 
00337   // Don't do this if the node has another user, which may require the
00338   // full value.
00339   if (!Op.getNode()->hasOneUse())
00340     return false;
00341 
00342   // Search for the smallest integer type with free casts to and from
00343   // Op's type. For expedience, just check power-of-2 integer types.
00344   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00345   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
00346   unsigned SmallVTBits = DemandedSize;
00347   if (!isPowerOf2_32(SmallVTBits))
00348     SmallVTBits = NextPowerOf2(SmallVTBits);
00349   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
00350     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
00351     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
00352         TLI.isZExtFree(SmallVT, Op.getValueType())) {
00353       // We found a type with free casts.
00354       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
00355                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
00356                                           Op.getNode()->getOperand(0)),
00357                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
00358                                           Op.getNode()->getOperand(1)));
00359       bool NeedZext = DemandedSize > SmallVTBits;
00360       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
00361                               dl, Op.getValueType(), X);
00362       return CombineTo(Op, Z);
00363     }
00364   }
00365   return false;
00366 }
00367 
00368 /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
00369 /// DemandedMask bits of the result of Op are ever used downstream.  If we can
00370 /// use this information to simplify Op, create a new simplified DAG node and
00371 /// return true, returning the original and new nodes in Old and New. Otherwise,
00372 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
00373 /// the expression (used to simplify the caller).  The KnownZero/One bits may
00374 /// only be accurate for those bits in the DemandedMask.
00375 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
00376                                           const APInt &DemandedMask,
00377                                           APInt &KnownZero,
00378                                           APInt &KnownOne,
00379                                           TargetLoweringOpt &TLO,
00380                                           unsigned Depth) const {
00381   unsigned BitWidth = DemandedMask.getBitWidth();
00382   assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
00383          "Mask size mismatches value type size!");
00384   APInt NewMask = DemandedMask;
00385   SDLoc dl(Op);
00386 
00387   // Don't know anything.
00388   KnownZero = KnownOne = APInt(BitWidth, 0);
00389 
00390   // Other users may use these bits.
00391   if (!Op.getNode()->hasOneUse()) {
00392     if (Depth != 0) {
00393       // If not at the root, Just compute the KnownZero/KnownOne bits to
00394       // simplify things downstream.
00395       TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
00396       return false;
00397     }
00398     // If this is the root being simplified, allow it to have multiple uses,
00399     // just set the NewMask to all bits.
00400     NewMask = APInt::getAllOnesValue(BitWidth);
00401   } else if (DemandedMask == 0) {
00402     // Not demanding any bits from Op.
00403     if (Op.getOpcode() != ISD::UNDEF)
00404       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
00405     return false;
00406   } else if (Depth == 6) {        // Limit search depth.
00407     return false;
00408   }
00409 
00410   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
00411   switch (Op.getOpcode()) {
00412   case ISD::Constant:
00413     // We know all of the bits for a constant!
00414     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
00415     KnownZero = ~KnownOne;
00416     return false;   // Don't fall through, will infinitely loop.
00417   case ISD::AND:
00418     // If the RHS is a constant, check to see if the LHS would be zero without
00419     // using the bits from the RHS.  Below, we use knowledge about the RHS to
00420     // simplify the LHS, here we're using information from the LHS to simplify
00421     // the RHS.
00422     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00423       APInt LHSZero, LHSOne;
00424       // Do not increment Depth here; that can cause an infinite loop.
00425       TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
00426       // If the LHS already has zeros where RHSC does, this and is dead.
00427       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
00428         return TLO.CombineTo(Op, Op.getOperand(0));
00429       // If any of the set bits in the RHS are known zero on the LHS, shrink
00430       // the constant.
00431       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
00432         return true;
00433     }
00434 
00435     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
00436                              KnownOne, TLO, Depth+1))
00437       return true;
00438     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00439     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
00440                              KnownZero2, KnownOne2, TLO, Depth+1))
00441       return true;
00442     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00443 
00444     // If all of the demanded bits are known one on one side, return the other.
00445     // These bits cannot contribute to the result of the 'and'.
00446     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
00447       return TLO.CombineTo(Op, Op.getOperand(0));
00448     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
00449       return TLO.CombineTo(Op, Op.getOperand(1));
00450     // If all of the demanded bits in the inputs are known zeros, return zero.
00451     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
00452       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
00453     // If the RHS is a constant, see if we can simplify it.
00454     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
00455       return true;
00456     // If the operation can be done in a smaller type, do so.
00457     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
00458       return true;
00459 
00460     // Output known-1 bits are only known if set in both the LHS & RHS.
00461     KnownOne &= KnownOne2;
00462     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00463     KnownZero |= KnownZero2;
00464     break;
00465   case ISD::OR:
00466     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
00467                              KnownOne, TLO, Depth+1))
00468       return true;
00469     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00470     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
00471                              KnownZero2, KnownOne2, TLO, Depth+1))
00472       return true;
00473     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00474 
00475     // If all of the demanded bits are known zero on one side, return the other.
00476     // These bits cannot contribute to the result of the 'or'.
00477     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
00478       return TLO.CombineTo(Op, Op.getOperand(0));
00479     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
00480       return TLO.CombineTo(Op, Op.getOperand(1));
00481     // If all of the potentially set bits on one side are known to be set on
00482     // the other side, just use the 'other' side.
00483     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
00484       return TLO.CombineTo(Op, Op.getOperand(0));
00485     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
00486       return TLO.CombineTo(Op, Op.getOperand(1));
00487     // If the RHS is a constant, see if we can simplify it.
00488     if (TLO.ShrinkDemandedConstant(Op, NewMask))
00489       return true;
00490     // If the operation can be done in a smaller type, do so.
00491     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
00492       return true;
00493 
00494     // Output known-0 bits are only known if clear in both the LHS & RHS.
00495     KnownZero &= KnownZero2;
00496     // Output known-1 are known to be set if set in either the LHS | RHS.
00497     KnownOne |= KnownOne2;
00498     break;
00499   case ISD::XOR:
00500     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
00501                              KnownOne, TLO, Depth+1))
00502       return true;
00503     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00504     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
00505                              KnownOne2, TLO, Depth+1))
00506       return true;
00507     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00508 
00509     // If all of the demanded bits are known zero on one side, return the other.
00510     // These bits cannot contribute to the result of the 'xor'.
00511     if ((KnownZero & NewMask) == NewMask)
00512       return TLO.CombineTo(Op, Op.getOperand(0));
00513     if ((KnownZero2 & NewMask) == NewMask)
00514       return TLO.CombineTo(Op, Op.getOperand(1));
00515     // If the operation can be done in a smaller type, do so.
00516     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
00517       return true;
00518 
00519     // If all of the unknown bits are known to be zero on one side or the other
00520     // (but not both) turn this into an *inclusive* or.
00521     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
00522     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
00523       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
00524                                                Op.getOperand(0),
00525                                                Op.getOperand(1)));
00526 
00527     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00528     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
00529     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00530     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
00531 
00532     // If all of the demanded bits on one side are known, and all of the set
00533     // bits on that side are also known to be set on the other side, turn this
00534     // into an AND, as we know the bits will be cleared.
00535     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
00536     // NB: it is okay if more bits are known than are requested
00537     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
00538       if (KnownOne == KnownOne2) { // set bits are the same on both sides
00539         EVT VT = Op.getValueType();
00540         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
00541         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
00542                                                  Op.getOperand(0), ANDC));
00543       }
00544     }
00545 
00546     // If the RHS is a constant, see if we can simplify it.
00547     // for XOR, we prefer to force bits to 1 if they will make a -1.
00548     // if we can't force bits, try to shrink constant
00549     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00550       APInt Expanded = C->getAPIntValue() | (~NewMask);
00551       // if we can expand it to have all bits set, do it
00552       if (Expanded.isAllOnesValue()) {
00553         if (Expanded != C->getAPIntValue()) {
00554           EVT VT = Op.getValueType();
00555           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
00556                                           TLO.DAG.getConstant(Expanded, VT));
00557           return TLO.CombineTo(Op, New);
00558         }
00559         // if it already has all the bits set, nothing to change
00560         // but don't shrink either!
00561       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
00562         return true;
00563       }
00564     }
00565 
00566     KnownZero = KnownZeroOut;
00567     KnownOne  = KnownOneOut;
00568     break;
00569   case ISD::SELECT:
00570     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
00571                              KnownOne, TLO, Depth+1))
00572       return true;
00573     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
00574                              KnownOne2, TLO, Depth+1))
00575       return true;
00576     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00577     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00578 
00579     // If the operands are constants, see if we can simplify them.
00580     if (TLO.ShrinkDemandedConstant(Op, NewMask))
00581       return true;
00582 
00583     // Only known if known in both the LHS and RHS.
00584     KnownOne &= KnownOne2;
00585     KnownZero &= KnownZero2;
00586     break;
00587   case ISD::SELECT_CC:
00588     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
00589                              KnownOne, TLO, Depth+1))
00590       return true;
00591     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
00592                              KnownOne2, TLO, Depth+1))
00593       return true;
00594     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00595     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00596 
00597     // If the operands are constants, see if we can simplify them.
00598     if (TLO.ShrinkDemandedConstant(Op, NewMask))
00599       return true;
00600 
00601     // Only known if known in both the LHS and RHS.
00602     KnownOne &= KnownOne2;
00603     KnownZero &= KnownZero2;
00604     break;
00605   case ISD::SHL:
00606     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00607       unsigned ShAmt = SA->getZExtValue();
00608       SDValue InOp = Op.getOperand(0);
00609 
00610       // If the shift count is an invalid immediate, don't do anything.
00611       if (ShAmt >= BitWidth)
00612         break;
00613 
00614       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
00615       // single shift.  We can do this if the bottom bits (which are shifted
00616       // out) are never demanded.
00617       if (InOp.getOpcode() == ISD::SRL &&
00618           isa<ConstantSDNode>(InOp.getOperand(1))) {
00619         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
00620           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
00621           unsigned Opc = ISD::SHL;
00622           int Diff = ShAmt-C1;
00623           if (Diff < 0) {
00624             Diff = -Diff;
00625             Opc = ISD::SRL;
00626           }
00627 
00628           SDValue NewSA =
00629             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
00630           EVT VT = Op.getValueType();
00631           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
00632                                                    InOp.getOperand(0), NewSA));
00633         }
00634       }
00635 
00636       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
00637                                KnownZero, KnownOne, TLO, Depth+1))
00638         return true;
00639 
00640       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
00641       // are not demanded. This will likely allow the anyext to be folded away.
00642       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
00643         SDValue InnerOp = InOp.getNode()->getOperand(0);
00644         EVT InnerVT = InnerOp.getValueType();
00645         unsigned InnerBits = InnerVT.getSizeInBits();
00646         if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
00647             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
00648           EVT ShTy = getShiftAmountTy(InnerVT);
00649           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
00650             ShTy = InnerVT;
00651           SDValue NarrowShl =
00652             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
00653                             TLO.DAG.getConstant(ShAmt, ShTy));
00654           return
00655             TLO.CombineTo(Op,
00656                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
00657                                           NarrowShl));
00658         }
00659         // Repeat the SHL optimization above in cases where an extension
00660         // intervenes: (shl (anyext (shr x, c1)), c2) to
00661         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
00662         // aren't demanded (as above) and that the shifted upper c1 bits of
00663         // x aren't demanded.
00664         if (InOp.hasOneUse() &&
00665             InnerOp.getOpcode() == ISD::SRL &&
00666             InnerOp.hasOneUse() &&
00667             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
00668           uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
00669             ->getZExtValue();
00670           if (InnerShAmt < ShAmt &&
00671               InnerShAmt < InnerBits &&
00672               NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
00673               NewMask.trunc(ShAmt) == 0) {
00674             SDValue NewSA =
00675               TLO.DAG.getConstant(ShAmt - InnerShAmt,
00676                                   Op.getOperand(1).getValueType());
00677             EVT VT = Op.getValueType();
00678             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
00679                                              InnerOp.getOperand(0));
00680             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
00681                                                      NewExt, NewSA));
00682           }
00683         }
00684       }
00685 
00686       KnownZero <<= SA->getZExtValue();
00687       KnownOne  <<= SA->getZExtValue();
00688       // low bits known zero.
00689       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
00690     }
00691     break;
00692   case ISD::SRL:
00693     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00694       EVT VT = Op.getValueType();
00695       unsigned ShAmt = SA->getZExtValue();
00696       unsigned VTSize = VT.getSizeInBits();
00697       SDValue InOp = Op.getOperand(0);
00698 
00699       // If the shift count is an invalid immediate, don't do anything.
00700       if (ShAmt >= BitWidth)
00701         break;
00702 
00703       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
00704       // single shift.  We can do this if the top bits (which are shifted out)
00705       // are never demanded.
00706       if (InOp.getOpcode() == ISD::SHL &&
00707           isa<ConstantSDNode>(InOp.getOperand(1))) {
00708         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
00709           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
00710           unsigned Opc = ISD::SRL;
00711           int Diff = ShAmt-C1;
00712           if (Diff < 0) {
00713             Diff = -Diff;
00714             Opc = ISD::SHL;
00715           }
00716 
00717           SDValue NewSA =
00718             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
00719           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
00720                                                    InOp.getOperand(0), NewSA));
00721         }
00722       }
00723 
00724       // Compute the new bits that are at the top now.
00725       if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
00726                                KnownZero, KnownOne, TLO, Depth+1))
00727         return true;
00728       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00729       KnownZero = KnownZero.lshr(ShAmt);
00730       KnownOne  = KnownOne.lshr(ShAmt);
00731 
00732       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
00733       KnownZero |= HighBits;  // High bits known zero.
00734     }
00735     break;
00736   case ISD::SRA:
00737     // If this is an arithmetic shift right and only the low-bit is set, we can
00738     // always convert this into a logical shr, even if the shift amount is
00739     // variable.  The low bit of the shift cannot be an input sign bit unless
00740     // the shift amount is >= the size of the datatype, which is undefined.
00741     if (NewMask == 1)
00742       return TLO.CombineTo(Op,
00743                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
00744                                            Op.getOperand(0), Op.getOperand(1)));
00745 
00746     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00747       EVT VT = Op.getValueType();
00748       unsigned ShAmt = SA->getZExtValue();
00749 
00750       // If the shift count is an invalid immediate, don't do anything.
00751       if (ShAmt >= BitWidth)
00752         break;
00753 
00754       APInt InDemandedMask = (NewMask << ShAmt);
00755 
00756       // If any of the demanded bits are produced by the sign extension, we also
00757       // demand the input sign bit.
00758       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
00759       if (HighBits.intersects(NewMask))
00760         InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
00761 
00762       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
00763                                KnownZero, KnownOne, TLO, Depth+1))
00764         return true;
00765       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00766       KnownZero = KnownZero.lshr(ShAmt);
00767       KnownOne  = KnownOne.lshr(ShAmt);
00768 
00769       // Handle the sign bit, adjusted to where it is now in the mask.
00770       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
00771 
00772       // If the input sign bit is known to be zero, or if none of the top bits
00773       // are demanded, turn this into an unsigned shift right.
00774       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits)
00775         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
00776                                                  Op.getOperand(0),
00777                                                  Op.getOperand(1)));
00778 
00779       int Log2 = NewMask.exactLogBase2();
00780       if (Log2 >= 0) {
00781         // The bit must come from the sign.
00782         SDValue NewSA =
00783           TLO.DAG.getConstant(BitWidth - 1 - Log2,
00784                               Op.getOperand(1).getValueType());
00785         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
00786                                                  Op.getOperand(0), NewSA));
00787       }
00788 
00789       if (KnownOne.intersects(SignBit))
00790         // New bits are known one.
00791         KnownOne |= HighBits;
00792     }
00793     break;
00794   case ISD::SIGN_EXTEND_INREG: {
00795     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
00796 
00797     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
00798     // If we only care about the highest bit, don't bother shifting right.
00799     if (MsbMask == NewMask) {
00800       unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
00801       SDValue InOp = Op.getOperand(0);
00802       unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
00803       bool AlreadySignExtended =
00804         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
00805       // However if the input is already sign extended we expect the sign
00806       // extension to be dropped altogether later and do not simplify.
00807       if (!AlreadySignExtended) {
00808         // Compute the correct shift amount type, which must be getShiftAmountTy
00809         // for scalar types after legalization.
00810         EVT ShiftAmtTy = Op.getValueType();
00811         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
00812           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
00813 
00814         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
00815         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
00816                                                  Op.getValueType(), InOp,
00817                                                  ShiftAmt));
00818       }
00819     }
00820 
00821     // Sign extension.  Compute the demanded bits in the result that are not
00822     // present in the input.
00823     APInt NewBits =
00824       APInt::getHighBitsSet(BitWidth,
00825                             BitWidth - ExVT.getScalarType().getSizeInBits());
00826 
00827     // If none of the extended bits are demanded, eliminate the sextinreg.
00828     if ((NewBits & NewMask) == 0)
00829       return TLO.CombineTo(Op, Op.getOperand(0));
00830 
00831     APInt InSignBit =
00832       APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
00833     APInt InputDemandedBits =
00834       APInt::getLowBitsSet(BitWidth,
00835                            ExVT.getScalarType().getSizeInBits()) &
00836       NewMask;
00837 
00838     // Since the sign extended bits are demanded, we know that the sign
00839     // bit is demanded.
00840     InputDemandedBits |= InSignBit;
00841 
00842     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
00843                              KnownZero, KnownOne, TLO, Depth+1))
00844       return true;
00845     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00846 
00847     // If the sign bit of the input is known set or clear, then we know the
00848     // top bits of the result.
00849 
00850     // If the input sign bit is known zero, convert this into a zero extension.
00851     if (KnownZero.intersects(InSignBit))
00852       return TLO.CombineTo(Op,
00853                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
00854 
00855     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
00856       KnownOne |= NewBits;
00857       KnownZero &= ~NewBits;
00858     } else {                       // Input sign bit unknown
00859       KnownZero &= ~NewBits;
00860       KnownOne &= ~NewBits;
00861     }
00862     break;
00863   }
00864   case ISD::BUILD_PAIR: {
00865     EVT HalfVT = Op.getOperand(0).getValueType();
00866     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
00867 
00868     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
00869     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
00870 
00871     APInt KnownZeroLo, KnownOneLo;
00872     APInt KnownZeroHi, KnownOneHi;
00873 
00874     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
00875                              KnownOneLo, TLO, Depth + 1))
00876       return true;
00877 
00878     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
00879                              KnownOneHi, TLO, Depth + 1))
00880       return true;
00881 
00882     KnownZero = KnownZeroLo.zext(BitWidth) |
00883                 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
00884 
00885     KnownOne = KnownOneLo.zext(BitWidth) |
00886                KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
00887     break;
00888   }
00889   case ISD::ZERO_EXTEND: {
00890     unsigned OperandBitWidth =
00891       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00892     APInt InMask = NewMask.trunc(OperandBitWidth);
00893 
00894     // If none of the top bits are demanded, convert this into an any_extend.
00895     APInt NewBits =
00896       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
00897     if (!NewBits.intersects(NewMask))
00898       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
00899                                                Op.getValueType(),
00900                                                Op.getOperand(0)));
00901 
00902     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
00903                              KnownZero, KnownOne, TLO, Depth+1))
00904       return true;
00905     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00906     KnownZero = KnownZero.zext(BitWidth);
00907     KnownOne = KnownOne.zext(BitWidth);
00908     KnownZero |= NewBits;
00909     break;
00910   }
00911   case ISD::SIGN_EXTEND: {
00912     EVT InVT = Op.getOperand(0).getValueType();
00913     unsigned InBits = InVT.getScalarType().getSizeInBits();
00914     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
00915     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
00916     APInt NewBits   = ~InMask & NewMask;
00917 
00918     // If none of the top bits are demanded, convert this into an any_extend.
00919     if (NewBits == 0)
00920       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
00921                                               Op.getValueType(),
00922                                               Op.getOperand(0)));
00923 
00924     // Since some of the sign extended bits are demanded, we know that the sign
00925     // bit is demanded.
00926     APInt InDemandedBits = InMask & NewMask;
00927     InDemandedBits |= InSignBit;
00928     InDemandedBits = InDemandedBits.trunc(InBits);
00929 
00930     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
00931                              KnownOne, TLO, Depth+1))
00932       return true;
00933     KnownZero = KnownZero.zext(BitWidth);
00934     KnownOne = KnownOne.zext(BitWidth);
00935 
00936     // If the sign bit is known zero, convert this to a zero extend.
00937     if (KnownZero.intersects(InSignBit))
00938       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
00939                                                Op.getValueType(),
00940                                                Op.getOperand(0)));
00941 
00942     // If the sign bit is known one, the top bits match.
00943     if (KnownOne.intersects(InSignBit)) {
00944       KnownOne |= NewBits;
00945       assert((KnownZero & NewBits) == 0);
00946     } else {   // Otherwise, top bits aren't known.
00947       assert((KnownOne & NewBits) == 0);
00948       assert((KnownZero & NewBits) == 0);
00949     }
00950     break;
00951   }
00952   case ISD::ANY_EXTEND: {
00953     unsigned OperandBitWidth =
00954       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00955     APInt InMask = NewMask.trunc(OperandBitWidth);
00956     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
00957                              KnownZero, KnownOne, TLO, Depth+1))
00958       return true;
00959     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00960     KnownZero = KnownZero.zext(BitWidth);
00961     KnownOne = KnownOne.zext(BitWidth);
00962     break;
00963   }
00964   case ISD::TRUNCATE: {
00965     // Simplify the input, using demanded bit information, and compute the known
00966     // zero/one bits live out.
00967     unsigned OperandBitWidth =
00968       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00969     APInt TruncMask = NewMask.zext(OperandBitWidth);
00970     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
00971                              KnownZero, KnownOne, TLO, Depth+1))
00972       return true;
00973     KnownZero = KnownZero.trunc(BitWidth);
00974     KnownOne = KnownOne.trunc(BitWidth);
00975 
00976     // If the input is only used by this truncate, see if we can shrink it based
00977     // on the known demanded bits.
00978     if (Op.getOperand(0).getNode()->hasOneUse()) {
00979       SDValue In = Op.getOperand(0);
00980       switch (In.getOpcode()) {
00981       default: break;
00982       case ISD::SRL:
00983         // Shrink SRL by a constant if none of the high bits shifted in are
00984         // demanded.
00985         if (TLO.LegalTypes() &&
00986             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
00987           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
00988           // undesirable.
00989           break;
00990         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
00991         if (!ShAmt)
00992           break;
00993         SDValue Shift = In.getOperand(1);
00994         if (TLO.LegalTypes()) {
00995           uint64_t ShVal = ShAmt->getZExtValue();
00996           Shift =
00997             TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
00998         }
00999 
01000         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
01001                                                OperandBitWidth - BitWidth);
01002         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
01003 
01004         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
01005           // None of the shifted in bits are needed.  Add a truncate of the
01006           // shift input, then shift it.
01007           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
01008                                              Op.getValueType(),
01009                                              In.getOperand(0));
01010           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
01011                                                    Op.getValueType(),
01012                                                    NewTrunc,
01013                                                    Shift));
01014         }
01015         break;
01016       }
01017     }
01018 
01019     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01020     break;
01021   }
01022   case ISD::AssertZext: {
01023     // AssertZext demands all of the high bits, plus any of the low bits
01024     // demanded by its users.
01025     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
01026     APInt InMask = APInt::getLowBitsSet(BitWidth,
01027                                         VT.getSizeInBits());
01028     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
01029                              KnownZero, KnownOne, TLO, Depth+1))
01030       return true;
01031     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01032 
01033     KnownZero |= ~InMask & NewMask;
01034     break;
01035   }
01036   case ISD::BITCAST:
01037     // If this is an FP->Int bitcast and if the sign bit is the only
01038     // thing demanded, turn this into a FGETSIGN.
01039     if (!TLO.LegalOperations() &&
01040         !Op.getValueType().isVector() &&
01041         !Op.getOperand(0).getValueType().isVector() &&
01042         NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
01043         Op.getOperand(0).getValueType().isFloatingPoint()) {
01044       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
01045       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
01046       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
01047         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
01048         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
01049         // place.  We expect the SHL to be eliminated by other optimizations.
01050         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
01051         unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
01052         if (!OpVTLegal && OpVTSizeInBits > 32)
01053           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
01054         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
01055         SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
01056         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
01057                                                  Op.getValueType(),
01058                                                  Sign, ShAmt));
01059       }
01060     }
01061     break;
01062   case ISD::ADD:
01063   case ISD::MUL:
01064   case ISD::SUB: {
01065     // Add, Sub, and Mul don't demand any bits in positions beyond that
01066     // of the highest bit demanded of them.
01067     APInt LoMask = APInt::getLowBitsSet(BitWidth,
01068                                         BitWidth - NewMask.countLeadingZeros());
01069     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
01070                              KnownOne2, TLO, Depth+1))
01071       return true;
01072     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
01073                              KnownOne2, TLO, Depth+1))
01074       return true;
01075     // See if the operation should be performed at a smaller bit width.
01076     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
01077       return true;
01078   }
01079   // FALL THROUGH
01080   default:
01081     // Just use computeKnownBits to compute output bits.
01082     TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
01083     break;
01084   }
01085 
01086   // If we know the value of all of the demanded bits, return this as a
01087   // constant.
01088   if ((NewMask & (KnownZero|KnownOne)) == NewMask)
01089     return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
01090 
01091   return false;
01092 }
01093 
01094 /// computeKnownBitsForTargetNode - Determine which of the bits specified
01095 /// in Mask are known to be either zero or one and return them in the
01096 /// KnownZero/KnownOne bitsets.
01097 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
01098                                                    APInt &KnownZero,
01099                                                    APInt &KnownOne,
01100                                                    const SelectionDAG &DAG,
01101                                                    unsigned Depth) const {
01102   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
01103           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
01104           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
01105           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
01106          "Should use MaskedValueIsZero if you don't know whether Op"
01107          " is a target node!");
01108   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
01109 }
01110 
01111 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
01112 /// targets that want to expose additional information about sign bits to the
01113 /// DAG Combiner.
01114 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
01115                                                          const SelectionDAG &,
01116                                                          unsigned Depth) const {
01117   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
01118           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
01119           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
01120           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
01121          "Should use ComputeNumSignBits if you don't know whether Op"
01122          " is a target node!");
01123   return 1;
01124 }
01125 
01126 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
01127 /// one bit set. This differs from computeKnownBits in that it doesn't need to
01128 /// determine which bit is set.
01129 ///
01130 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
01131   // A left-shift of a constant one will have exactly one bit set, because
01132   // shifting the bit off the end is undefined.
01133   if (Val.getOpcode() == ISD::SHL)
01134     if (ConstantSDNode *C =
01135          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
01136       if (C->getAPIntValue() == 1)
01137         return true;
01138 
01139   // Similarly, a right-shift of a constant sign-bit will have exactly
01140   // one bit set.
01141   if (Val.getOpcode() == ISD::SRL)
01142     if (ConstantSDNode *C =
01143          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
01144       if (C->getAPIntValue().isSignBit())
01145         return true;
01146 
01147   // More could be done here, though the above checks are enough
01148   // to handle some common cases.
01149 
01150   // Fall back to computeKnownBits to catch other known cases.
01151   EVT OpVT = Val.getValueType();
01152   unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
01153   APInt KnownZero, KnownOne;
01154   DAG.computeKnownBits(Val, KnownZero, KnownOne);
01155   return (KnownZero.countPopulation() == BitWidth - 1) &&
01156          (KnownOne.countPopulation() == 1);
01157 }
01158 
01159 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
01160   if (!N)
01161     return false;
01162 
01163   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
01164   if (!CN) {
01165     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
01166     if (!BV)
01167       return false;
01168 
01169     BitVector UndefElements;
01170     CN = BV->getConstantSplatNode(&UndefElements);
01171     // Only interested in constant splats, and we don't try to handle undef
01172     // elements in identifying boolean constants.
01173     if (!CN || UndefElements.none())
01174       return false;
01175   }
01176 
01177   switch (getBooleanContents(N->getValueType(0))) {
01178   case UndefinedBooleanContent:
01179     return CN->getAPIntValue()[0];
01180   case ZeroOrOneBooleanContent:
01181     return CN->isOne();
01182   case ZeroOrNegativeOneBooleanContent:
01183     return CN->isAllOnesValue();
01184   }
01185 
01186   llvm_unreachable("Invalid boolean contents");
01187 }
01188 
01189 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
01190   if (!N)
01191     return false;
01192 
01193   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
01194   if (!CN) {
01195     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
01196     if (!BV)
01197       return false;
01198 
01199     BitVector UndefElements;
01200     CN = BV->getConstantSplatNode(&UndefElements);
01201     // Only interested in constant splats, and we don't try to handle undef
01202     // elements in identifying boolean constants.
01203     if (!CN || UndefElements.none())
01204       return false;
01205   }
01206 
01207   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
01208     return !CN->getAPIntValue()[0];
01209 
01210   return CN->isNullValue();
01211 }
01212 
01213 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
01214 /// and cc. If it is unable to simplify it, return a null SDValue.
01215 SDValue
01216 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
01217                               ISD::CondCode Cond, bool foldBooleans,
01218                               DAGCombinerInfo &DCI, SDLoc dl) const {
01219   SelectionDAG &DAG = DCI.DAG;
01220 
01221   // These setcc operations always fold.
01222   switch (Cond) {
01223   default: break;
01224   case ISD::SETFALSE:
01225   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
01226   case ISD::SETTRUE:
01227   case ISD::SETTRUE2: {
01228     TargetLowering::BooleanContent Cnt =
01229         getBooleanContents(N0->getValueType(0));
01230     return DAG.getConstant(
01231         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
01232   }
01233   }
01234 
01235   // Ensure that the constant occurs on the RHS, and fold constant
01236   // comparisons.
01237   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
01238   if (isa<ConstantSDNode>(N0.getNode()) &&
01239       (DCI.isBeforeLegalizeOps() ||
01240        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
01241     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
01242 
01243   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
01244     const APInt &C1 = N1C->getAPIntValue();
01245 
01246     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
01247     // equality comparison, then we're just comparing whether X itself is
01248     // zero.
01249     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
01250         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
01251         N0.getOperand(1).getOpcode() == ISD::Constant) {
01252       const APInt &ShAmt
01253         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
01254       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01255           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
01256         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
01257           // (srl (ctlz x), 5) == 0  -> X != 0
01258           // (srl (ctlz x), 5) != 1  -> X != 0
01259           Cond = ISD::SETNE;
01260         } else {
01261           // (srl (ctlz x), 5) != 0  -> X == 0
01262           // (srl (ctlz x), 5) == 1  -> X == 0
01263           Cond = ISD::SETEQ;
01264         }
01265         SDValue Zero = DAG.getConstant(0, N0.getValueType());
01266         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
01267                             Zero, Cond);
01268       }
01269     }
01270 
01271     SDValue CTPOP = N0;
01272     // Look through truncs that don't change the value of a ctpop.
01273     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
01274       CTPOP = N0.getOperand(0);
01275 
01276     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
01277         (N0 == CTPOP || N0.getValueType().getSizeInBits() >
01278                         Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
01279       EVT CTVT = CTPOP.getValueType();
01280       SDValue CTOp = CTPOP.getOperand(0);
01281 
01282       // (ctpop x) u< 2 -> (x & x-1) == 0
01283       // (ctpop x) u> 1 -> (x & x-1) != 0
01284       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
01285         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
01286                                   DAG.getConstant(1, CTVT));
01287         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
01288         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
01289         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
01290       }
01291 
01292       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
01293     }
01294 
01295     // (zext x) == C --> x == (trunc C)
01296     // (sext x) == C --> x == (trunc C)
01297     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01298         DCI.isBeforeLegalize() && N0->hasOneUse()) {
01299       unsigned MinBits = N0.getValueSizeInBits();
01300       SDValue PreExt;
01301       bool Signed = false;
01302       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
01303         // ZExt
01304         MinBits = N0->getOperand(0).getValueSizeInBits();
01305         PreExt = N0->getOperand(0);
01306       } else if (N0->getOpcode() == ISD::AND) {
01307         // DAGCombine turns costly ZExts into ANDs
01308         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
01309           if ((C->getAPIntValue()+1).isPowerOf2()) {
01310             MinBits = C->getAPIntValue().countTrailingOnes();
01311             PreExt = N0->getOperand(0);
01312           }
01313       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
01314         // SExt
01315         MinBits = N0->getOperand(0).getValueSizeInBits();
01316         PreExt = N0->getOperand(0);
01317         Signed = true;
01318       } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
01319         // ZEXTLOAD / SEXTLOAD
01320         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
01321           MinBits = LN0->getMemoryVT().getSizeInBits();
01322           PreExt = N0;
01323         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
01324           Signed = true;
01325           MinBits = LN0->getMemoryVT().getSizeInBits();
01326           PreExt = N0;
01327         }
01328       }
01329 
01330       // Figure out how many bits we need to preserve this constant.
01331       unsigned ReqdBits = Signed ?
01332         C1.getBitWidth() - C1.getNumSignBits() + 1 :
01333         C1.getActiveBits();
01334 
01335       // Make sure we're not losing bits from the constant.
01336       if (MinBits > 0 &&
01337           MinBits < C1.getBitWidth() &&
01338           MinBits >= ReqdBits) {
01339         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
01340         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
01341           // Will get folded away.
01342           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
01343           SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
01344           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
01345         }
01346       }
01347     }
01348 
01349     // If the LHS is '(and load, const)', the RHS is 0,
01350     // the test is for equality or unsigned, and all 1 bits of the const are
01351     // in the same partial word, see if we can shorten the load.
01352     if (DCI.isBeforeLegalize() &&
01353         !ISD::isSignedIntSetCC(Cond) &&
01354         N0.getOpcode() == ISD::AND && C1 == 0 &&
01355         N0.getNode()->hasOneUse() &&
01356         isa<LoadSDNode>(N0.getOperand(0)) &&
01357         N0.getOperand(0).getNode()->hasOneUse() &&
01358         isa<ConstantSDNode>(N0.getOperand(1))) {
01359       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
01360       APInt bestMask;
01361       unsigned bestWidth = 0, bestOffset = 0;
01362       if (!Lod->isVolatile() && Lod->isUnindexed()) {
01363         unsigned origWidth = N0.getValueType().getSizeInBits();
01364         unsigned maskWidth = origWidth;
01365         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
01366         // 8 bits, but have to be careful...
01367         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
01368           origWidth = Lod->getMemoryVT().getSizeInBits();
01369         const APInt &Mask =
01370           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
01371         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
01372           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
01373           for (unsigned offset=0; offset<origWidth/width; offset++) {
01374             if ((newMask & Mask) == Mask) {
01375               if (!getDataLayout()->isLittleEndian())
01376                 bestOffset = (origWidth/width - offset - 1) * (width/8);
01377               else
01378                 bestOffset = (uint64_t)offset * (width/8);
01379               bestMask = Mask.lshr(offset * (width/8) * 8);
01380               bestWidth = width;
01381               break;
01382             }
01383             newMask = newMask << width;
01384           }
01385         }
01386       }
01387       if (bestWidth) {
01388         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
01389         if (newVT.isRound()) {
01390           EVT PtrType = Lod->getOperand(1).getValueType();
01391           SDValue Ptr = Lod->getBasePtr();
01392           if (bestOffset != 0)
01393             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
01394                               DAG.getConstant(bestOffset, PtrType));
01395           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
01396           SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
01397                                 Lod->getPointerInfo().getWithOffset(bestOffset),
01398                                         false, false, false, NewAlign);
01399           return DAG.getSetCC(dl, VT,
01400                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
01401                                       DAG.getConstant(bestMask.trunc(bestWidth),
01402                                                       newVT)),
01403                               DAG.getConstant(0LL, newVT), Cond);
01404         }
01405       }
01406     }
01407 
01408     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
01409     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
01410       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
01411 
01412       // If the comparison constant has bits in the upper part, the
01413       // zero-extended value could never match.
01414       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
01415                                               C1.getBitWidth() - InSize))) {
01416         switch (Cond) {
01417         case ISD::SETUGT:
01418         case ISD::SETUGE:
01419         case ISD::SETEQ: return DAG.getConstant(0, VT);
01420         case ISD::SETULT:
01421         case ISD::SETULE:
01422         case ISD::SETNE: return DAG.getConstant(1, VT);
01423         case ISD::SETGT:
01424         case ISD::SETGE:
01425           // True if the sign bit of C1 is set.
01426           return DAG.getConstant(C1.isNegative(), VT);
01427         case ISD::SETLT:
01428         case ISD::SETLE:
01429           // True if the sign bit of C1 isn't set.
01430           return DAG.getConstant(C1.isNonNegative(), VT);
01431         default:
01432           break;
01433         }
01434       }
01435 
01436       // Otherwise, we can perform the comparison with the low bits.
01437       switch (Cond) {
01438       case ISD::SETEQ:
01439       case ISD::SETNE:
01440       case ISD::SETUGT:
01441       case ISD::SETUGE:
01442       case ISD::SETULT:
01443       case ISD::SETULE: {
01444         EVT newVT = N0.getOperand(0).getValueType();
01445         if (DCI.isBeforeLegalizeOps() ||
01446             (isOperationLegal(ISD::SETCC, newVT) &&
01447              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
01448           EVT NewSetCCVT = getSetCCResultType(*DAG.getContext(), newVT);
01449           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), newVT);
01450 
01451           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
01452                                           NewConst, Cond);
01453           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
01454         }
01455         break;
01456       }
01457       default:
01458         break;   // todo, be more careful with signed comparisons
01459       }
01460     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
01461                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01462       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
01463       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
01464       EVT ExtDstTy = N0.getValueType();
01465       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
01466 
01467       // If the constant doesn't fit into the number of bits for the source of
01468       // the sign extension, it is impossible for both sides to be equal.
01469       if (C1.getMinSignedBits() > ExtSrcTyBits)
01470         return DAG.getConstant(Cond == ISD::SETNE, VT);
01471 
01472       SDValue ZextOp;
01473       EVT Op0Ty = N0.getOperand(0).getValueType();
01474       if (Op0Ty == ExtSrcTy) {
01475         ZextOp = N0.getOperand(0);
01476       } else {
01477         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
01478         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
01479                               DAG.getConstant(Imm, Op0Ty));
01480       }
01481       if (!DCI.isCalledByLegalizer())
01482         DCI.AddToWorklist(ZextOp.getNode());
01483       // Otherwise, make this a use of a zext.
01484       return DAG.getSetCC(dl, VT, ZextOp,
01485                           DAG.getConstant(C1 & APInt::getLowBitsSet(
01486                                                               ExtDstTyBits,
01487                                                               ExtSrcTyBits),
01488                                           ExtDstTy),
01489                           Cond);
01490     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
01491                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01492       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
01493       if (N0.getOpcode() == ISD::SETCC &&
01494           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
01495         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
01496         if (TrueWhenTrue)
01497           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
01498         // Invert the condition.
01499         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
01500         CC = ISD::getSetCCInverse(CC,
01501                                   N0.getOperand(0).getValueType().isInteger());
01502         if (DCI.isBeforeLegalizeOps() ||
01503             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
01504           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
01505       }
01506 
01507       if ((N0.getOpcode() == ISD::XOR ||
01508            (N0.getOpcode() == ISD::AND &&
01509             N0.getOperand(0).getOpcode() == ISD::XOR &&
01510             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
01511           isa<ConstantSDNode>(N0.getOperand(1)) &&
01512           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
01513         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
01514         // can only do this if the top bits are known zero.
01515         unsigned BitWidth = N0.getValueSizeInBits();
01516         if (DAG.MaskedValueIsZero(N0,
01517                                   APInt::getHighBitsSet(BitWidth,
01518                                                         BitWidth-1))) {
01519           // Okay, get the un-inverted input value.
01520           SDValue Val;
01521           if (N0.getOpcode() == ISD::XOR)
01522             Val = N0.getOperand(0);
01523           else {
01524             assert(N0.getOpcode() == ISD::AND &&
01525                     N0.getOperand(0).getOpcode() == ISD::XOR);
01526             // ((X^1)&1)^1 -> X & 1
01527             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
01528                               N0.getOperand(0).getOperand(0),
01529                               N0.getOperand(1));
01530           }
01531 
01532           return DAG.getSetCC(dl, VT, Val, N1,
01533                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01534         }
01535       } else if (N1C->getAPIntValue() == 1 &&
01536                  (VT == MVT::i1 ||
01537                   getBooleanContents(N0->getValueType(0)) ==
01538                       ZeroOrOneBooleanContent)) {
01539         SDValue Op0 = N0;
01540         if (Op0.getOpcode() == ISD::TRUNCATE)
01541           Op0 = Op0.getOperand(0);
01542 
01543         if ((Op0.getOpcode() == ISD::XOR) &&
01544             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
01545             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
01546           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
01547           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
01548           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
01549                               Cond);
01550         }
01551         if (Op0.getOpcode() == ISD::AND &&
01552             isa<ConstantSDNode>(Op0.getOperand(1)) &&
01553             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
01554           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
01555           if (Op0.getValueType().bitsGT(VT))
01556             Op0 = DAG.getNode(ISD::AND, dl, VT,
01557                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
01558                           DAG.getConstant(1, VT));
01559           else if (Op0.getValueType().bitsLT(VT))
01560             Op0 = DAG.getNode(ISD::AND, dl, VT,
01561                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
01562                         DAG.getConstant(1, VT));
01563 
01564           return DAG.getSetCC(dl, VT, Op0,
01565                               DAG.getConstant(0, Op0.getValueType()),
01566                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01567         }
01568         if (Op0.getOpcode() == ISD::AssertZext &&
01569             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
01570           return DAG.getSetCC(dl, VT, Op0,
01571                               DAG.getConstant(0, Op0.getValueType()),
01572                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01573       }
01574     }
01575 
01576     APInt MinVal, MaxVal;
01577     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
01578     if (ISD::isSignedIntSetCC(Cond)) {
01579       MinVal = APInt::getSignedMinValue(OperandBitSize);
01580       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
01581     } else {
01582       MinVal = APInt::getMinValue(OperandBitSize);
01583       MaxVal = APInt::getMaxValue(OperandBitSize);
01584     }
01585 
01586     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
01587     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
01588       if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
01589       // X >= C0 --> X > (C0 - 1)
01590       APInt C = C1 - 1;
01591       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
01592       if ((DCI.isBeforeLegalizeOps() ||
01593            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
01594           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
01595                                 isLegalICmpImmediate(C.getSExtValue())))) {
01596         return DAG.getSetCC(dl, VT, N0,
01597                             DAG.getConstant(C, N1.getValueType()),
01598                             NewCC);
01599       }
01600     }
01601 
01602     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
01603       if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
01604       // X <= C0 --> X < (C0 + 1)
01605       APInt C = C1 + 1;
01606       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
01607       if ((DCI.isBeforeLegalizeOps() ||
01608            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
01609           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
01610                                 isLegalICmpImmediate(C.getSExtValue())))) {
01611         return DAG.getSetCC(dl, VT, N0,
01612                             DAG.getConstant(C, N1.getValueType()),
01613                             NewCC);
01614       }
01615     }
01616 
01617     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
01618       return DAG.getConstant(0, VT);      // X < MIN --> false
01619     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
01620       return DAG.getConstant(1, VT);      // X >= MIN --> true
01621     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
01622       return DAG.getConstant(0, VT);      // X > MAX --> false
01623     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
01624       return DAG.getConstant(1, VT);      // X <= MAX --> true
01625 
01626     // Canonicalize setgt X, Min --> setne X, Min
01627     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
01628       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
01629     // Canonicalize setlt X, Max --> setne X, Max
01630     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
01631       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
01632 
01633     // If we have setult X, 1, turn it into seteq X, 0
01634     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
01635       return DAG.getSetCC(dl, VT, N0,
01636                           DAG.getConstant(MinVal, N0.getValueType()),
01637                           ISD::SETEQ);
01638     // If we have setugt X, Max-1, turn it into seteq X, Max
01639     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
01640       return DAG.getSetCC(dl, VT, N0,
01641                           DAG.getConstant(MaxVal, N0.getValueType()),
01642                           ISD::SETEQ);
01643 
01644     // If we have "setcc X, C0", check to see if we can shrink the immediate
01645     // by changing cc.
01646 
01647     // SETUGT X, SINTMAX  -> SETLT X, 0
01648     if (Cond == ISD::SETUGT &&
01649         C1 == APInt::getSignedMaxValue(OperandBitSize))
01650       return DAG.getSetCC(dl, VT, N0,
01651                           DAG.getConstant(0, N1.getValueType()),
01652                           ISD::SETLT);
01653 
01654     // SETULT X, SINTMIN  -> SETGT X, -1
01655     if (Cond == ISD::SETULT &&
01656         C1 == APInt::getSignedMinValue(OperandBitSize)) {
01657       SDValue ConstMinusOne =
01658           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
01659                           N1.getValueType());
01660       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
01661     }
01662 
01663     // Fold bit comparisons when we can.
01664     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01665         (VT == N0.getValueType() ||
01666          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
01667         N0.getOpcode() == ISD::AND)
01668       if (ConstantSDNode *AndRHS =
01669                   dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01670         EVT ShiftTy = DCI.isBeforeLegalize() ?
01671           getPointerTy() : getShiftAmountTy(N0.getValueType());
01672         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
01673           // Perform the xform if the AND RHS is a single bit.
01674           if (AndRHS->getAPIntValue().isPowerOf2()) {
01675             return DAG.getNode(ISD::TRUNCATE, dl, VT,
01676                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
01677                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
01678           }
01679         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
01680           // (X & 8) == 8  -->  (X & 8) >> 3
01681           // Perform the xform if C1 is a single bit.
01682           if (C1.isPowerOf2()) {
01683             return DAG.getNode(ISD::TRUNCATE, dl, VT,
01684                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
01685                                       DAG.getConstant(C1.logBase2(), ShiftTy)));
01686           }
01687         }
01688       }
01689 
01690     if (C1.getMinSignedBits() <= 64 &&
01691         !isLegalICmpImmediate(C1.getSExtValue())) {
01692       // (X & -256) == 256 -> (X >> 8) == 1
01693       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01694           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
01695         if (ConstantSDNode *AndRHS =
01696             dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01697           const APInt &AndRHSC = AndRHS->getAPIntValue();
01698           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
01699             unsigned ShiftBits = AndRHSC.countTrailingZeros();
01700             EVT ShiftTy = DCI.isBeforeLegalize() ?
01701               getPointerTy() : getShiftAmountTy(N0.getValueType());
01702             EVT CmpTy = N0.getValueType();
01703             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
01704                                         DAG.getConstant(ShiftBits, ShiftTy));
01705             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
01706             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
01707           }
01708         }
01709       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
01710                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
01711         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
01712         // X <  0x100000000 -> (X >> 32) <  1
01713         // X >= 0x100000000 -> (X >> 32) >= 1
01714         // X <= 0x0ffffffff -> (X >> 32) <  1
01715         // X >  0x0ffffffff -> (X >> 32) >= 1
01716         unsigned ShiftBits;
01717         APInt NewC = C1;
01718         ISD::CondCode NewCond = Cond;
01719         if (AdjOne) {
01720           ShiftBits = C1.countTrailingOnes();
01721           NewC = NewC + 1;
01722           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
01723         } else {
01724           ShiftBits = C1.countTrailingZeros();
01725         }
01726         NewC = NewC.lshr(ShiftBits);
01727         if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
01728           EVT ShiftTy = DCI.isBeforeLegalize() ?
01729             getPointerTy() : getShiftAmountTy(N0.getValueType());
01730           EVT CmpTy = N0.getValueType();
01731           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
01732                                       DAG.getConstant(ShiftBits, ShiftTy));
01733           SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
01734           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
01735         }
01736       }
01737     }
01738   }
01739 
01740   if (isa<ConstantFPSDNode>(N0.getNode())) {
01741     // Constant fold or commute setcc.
01742     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
01743     if (O.getNode()) return O;
01744   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
01745     // If the RHS of an FP comparison is a constant, simplify it away in
01746     // some cases.
01747     if (CFP->getValueAPF().isNaN()) {
01748       // If an operand is known to be a nan, we can fold it.
01749       switch (ISD::getUnorderedFlavor(Cond)) {
01750       default: llvm_unreachable("Unknown flavor!");
01751       case 0:  // Known false.
01752         return DAG.getConstant(0, VT);
01753       case 1:  // Known true.
01754         return DAG.getConstant(1, VT);
01755       case 2:  // Undefined.
01756         return DAG.getUNDEF(VT);
01757       }
01758     }
01759 
01760     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
01761     // constant if knowing that the operand is non-nan is enough.  We prefer to
01762     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
01763     // materialize 0.0.
01764     if (Cond == ISD::SETO || Cond == ISD::SETUO)
01765       return DAG.getSetCC(dl, VT, N0, N0, Cond);
01766 
01767     // If the condition is not legal, see if we can find an equivalent one
01768     // which is legal.
01769     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
01770       // If the comparison was an awkward floating-point == or != and one of
01771       // the comparison operands is infinity or negative infinity, convert the
01772       // condition to a less-awkward <= or >=.
01773       if (CFP->getValueAPF().isInfinity()) {
01774         if (CFP->getValueAPF().isNegative()) {
01775           if (Cond == ISD::SETOEQ &&
01776               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
01777             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
01778           if (Cond == ISD::SETUEQ &&
01779               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
01780             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
01781           if (Cond == ISD::SETUNE &&
01782               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
01783             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
01784           if (Cond == ISD::SETONE &&
01785               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
01786             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
01787         } else {
01788           if (Cond == ISD::SETOEQ &&
01789               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
01790             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
01791           if (Cond == ISD::SETUEQ &&
01792               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
01793             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
01794           if (Cond == ISD::SETUNE &&
01795               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
01796             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
01797           if (Cond == ISD::SETONE &&
01798               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
01799             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
01800         }
01801       }
01802     }
01803   }
01804 
01805   if (N0 == N1) {
01806     // The sext(setcc()) => setcc() optimization relies on the appropriate
01807     // constant being emitted.
01808     uint64_t EqVal = 0;
01809     switch (getBooleanContents(N0.getValueType())) {
01810     case UndefinedBooleanContent:
01811     case ZeroOrOneBooleanContent:
01812       EqVal = ISD::isTrueWhenEqual(Cond);
01813       break;
01814     case ZeroOrNegativeOneBooleanContent:
01815       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
01816       break;
01817     }
01818 
01819     // We can always fold X == X for integer setcc's.
01820     if (N0.getValueType().isInteger()) {
01821       return DAG.getConstant(EqVal, VT);
01822     }
01823     unsigned UOF = ISD::getUnorderedFlavor(Cond);
01824     if (UOF == 2)   // FP operators that are undefined on NaNs.
01825       return DAG.getConstant(EqVal, VT);
01826     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
01827       return DAG.getConstant(EqVal, VT);
01828     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
01829     // if it is not already.
01830     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
01831     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
01832           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
01833       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
01834   }
01835 
01836   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01837       N0.getValueType().isInteger()) {
01838     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
01839         N0.getOpcode() == ISD::XOR) {
01840       // Simplify (X+Y) == (X+Z) -->  Y == Z
01841       if (N0.getOpcode() == N1.getOpcode()) {
01842         if (N0.getOperand(0) == N1.getOperand(0))
01843           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
01844         if (N0.getOperand(1) == N1.getOperand(1))
01845           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
01846         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
01847           // If X op Y == Y op X, try other combinations.
01848           if (N0.getOperand(0) == N1.getOperand(1))
01849             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
01850                                 Cond);
01851           if (N0.getOperand(1) == N1.getOperand(0))
01852             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
01853                                 Cond);
01854         }
01855       }
01856 
01857       // If RHS is a legal immediate value for a compare instruction, we need
01858       // to be careful about increasing register pressure needlessly.
01859       bool LegalRHSImm = false;
01860 
01861       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
01862         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01863           // Turn (X+C1) == C2 --> X == C2-C1
01864           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
01865             return DAG.getSetCC(dl, VT, N0.getOperand(0),
01866                                 DAG.getConstant(RHSC->getAPIntValue()-
01867                                                 LHSR->getAPIntValue(),
01868                                 N0.getValueType()), Cond);
01869           }
01870 
01871           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
01872           if (N0.getOpcode() == ISD::XOR)
01873             // If we know that all of the inverted bits are zero, don't bother
01874             // performing the inversion.
01875             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
01876               return
01877                 DAG.getSetCC(dl, VT, N0.getOperand(0),
01878                              DAG.getConstant(LHSR->getAPIntValue() ^
01879                                                RHSC->getAPIntValue(),
01880                                              N0.getValueType()),
01881                              Cond);
01882         }
01883 
01884         // Turn (C1-X) == C2 --> X == C1-C2
01885         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
01886           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
01887             return
01888               DAG.getSetCC(dl, VT, N0.getOperand(1),
01889                            DAG.getConstant(SUBC->getAPIntValue() -
01890                                              RHSC->getAPIntValue(),
01891                                            N0.getValueType()),
01892                            Cond);
01893           }
01894         }
01895 
01896         // Could RHSC fold directly into a compare?
01897         if (RHSC->getValueType(0).getSizeInBits() <= 64)
01898           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
01899       }
01900 
01901       // Simplify (X+Z) == X -->  Z == 0
01902       // Don't do this if X is an immediate that can fold into a cmp
01903       // instruction and X+Z has other uses. It could be an induction variable
01904       // chain, and the transform would increase register pressure.
01905       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
01906         if (N0.getOperand(0) == N1)
01907           return DAG.getSetCC(dl, VT, N0.getOperand(1),
01908                               DAG.getConstant(0, N0.getValueType()), Cond);
01909         if (N0.getOperand(1) == N1) {
01910           if (DAG.isCommutativeBinOp(N0.getOpcode()))
01911             return DAG.getSetCC(dl, VT, N0.getOperand(0),
01912                                 DAG.getConstant(0, N0.getValueType()), Cond);
01913           if (N0.getNode()->hasOneUse()) {
01914             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
01915             // (Z-X) == X  --> Z == X<<1
01916             SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
01917                        DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
01918             if (!DCI.isCalledByLegalizer())
01919               DCI.AddToWorklist(SH.getNode());
01920             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
01921           }
01922         }
01923       }
01924     }
01925 
01926     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
01927         N1.getOpcode() == ISD::XOR) {
01928       // Simplify  X == (X+Z) -->  Z == 0
01929       if (N1.getOperand(0) == N0)
01930         return DAG.getSetCC(dl, VT, N1.getOperand(1),
01931                         DAG.getConstant(0, N1.getValueType()), Cond);
01932       if (N1.getOperand(1) == N0) {
01933         if (DAG.isCommutativeBinOp(N1.getOpcode()))
01934           return DAG.getSetCC(dl, VT, N1.getOperand(0),
01935                           DAG.getConstant(0, N1.getValueType()), Cond);
01936         if (N1.getNode()->hasOneUse()) {
01937           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
01938           // X == (Z-X)  --> X<<1 == Z
01939           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
01940                        DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
01941           if (!DCI.isCalledByLegalizer())
01942             DCI.AddToWorklist(SH.getNode());
01943           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
01944         }
01945       }
01946     }
01947 
01948     // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
01949     // Note that where y is variable and is known to have at most
01950     // one bit set (for example, if it is z&1) we cannot do this;
01951     // the expressions are not equivalent when y==0.
01952     if (N0.getOpcode() == ISD::AND)
01953       if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
01954         if (ValueHasExactlyOneBitSet(N1, DAG)) {
01955           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
01956           if (DCI.isBeforeLegalizeOps() ||
01957               isCondCodeLegal(Cond, N0.getSimpleValueType())) {
01958             SDValue Zero = DAG.getConstant(0, N1.getValueType());
01959             return DAG.getSetCC(dl, VT, N0, Zero, Cond);
01960           }
01961         }
01962       }
01963     if (N1.getOpcode() == ISD::AND)
01964       if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
01965         if (ValueHasExactlyOneBitSet(N0, DAG)) {
01966           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
01967           if (DCI.isBeforeLegalizeOps() ||
01968               isCondCodeLegal(Cond, N1.getSimpleValueType())) {
01969             SDValue Zero = DAG.getConstant(0, N0.getValueType());
01970             return DAG.getSetCC(dl, VT, N1, Zero, Cond);
01971           }
01972         }
01973       }
01974   }
01975 
01976   // Fold away ALL boolean setcc's.
01977   SDValue Temp;
01978   if (N0.getValueType() == MVT::i1 && foldBooleans) {
01979     switch (Cond) {
01980     default: llvm_unreachable("Unknown integer setcc!");
01981     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
01982       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
01983       N0 = DAG.getNOT(dl, Temp, MVT::i1);
01984       if (!DCI.isCalledByLegalizer())
01985         DCI.AddToWorklist(Temp.getNode());
01986       break;
01987     case ISD::SETNE:  // X != Y   -->  (X^Y)
01988       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
01989       break;
01990     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
01991     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
01992       Temp = DAG.getNOT(dl, N0, MVT::i1);
01993       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
01994       if (!DCI.isCalledByLegalizer())
01995         DCI.AddToWorklist(Temp.getNode());
01996       break;
01997     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
01998     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
01999       Temp = DAG.getNOT(dl, N1, MVT::i1);
02000       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
02001       if (!DCI.isCalledByLegalizer())
02002         DCI.AddToWorklist(Temp.getNode());
02003       break;
02004     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
02005     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
02006       Temp = DAG.getNOT(dl, N0, MVT::i1);
02007       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
02008       if (!DCI.isCalledByLegalizer())
02009         DCI.AddToWorklist(Temp.getNode());
02010       break;
02011     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
02012     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
02013       Temp = DAG.getNOT(dl, N1, MVT::i1);
02014       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
02015       break;
02016     }
02017     if (VT != MVT::i1) {
02018       if (!DCI.isCalledByLegalizer())
02019         DCI.AddToWorklist(N0.getNode());
02020       // FIXME: If running after legalize, we probably can't do this.
02021       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
02022     }
02023     return N0;
02024   }
02025 
02026   // Could not fold it.
02027   return SDValue();
02028 }
02029 
02030 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
02031 /// node is a GlobalAddress + offset.
02032 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
02033                                     int64_t &Offset) const {
02034   if (isa<GlobalAddressSDNode>(N)) {
02035     GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
02036     GA = GASD->getGlobal();
02037     Offset += GASD->getOffset();
02038     return true;
02039   }
02040 
02041   if (N->getOpcode() == ISD::ADD) {
02042     SDValue N1 = N->getOperand(0);
02043     SDValue N2 = N->getOperand(1);
02044     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
02045       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
02046       if (V) {
02047         Offset += V->getSExtValue();
02048         return true;
02049       }
02050     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
02051       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
02052       if (V) {
02053         Offset += V->getSExtValue();
02054         return true;
02055       }
02056     }
02057   }
02058 
02059   return false;
02060 }
02061 
02062 
02063 SDValue TargetLowering::
02064 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
02065   // Default implementation: no optimization.
02066   return SDValue();
02067 }
02068 
02069 //===----------------------------------------------------------------------===//
02070 //  Inline Assembler Implementation Methods
02071 //===----------------------------------------------------------------------===//
02072 
02073 
02074 TargetLowering::ConstraintType
02075 TargetLowering::getConstraintType(const std::string &Constraint) const {
02076   unsigned S = Constraint.size();
02077 
02078   if (S == 1) {
02079     switch (Constraint[0]) {
02080     default: break;
02081     case 'r': return C_RegisterClass;
02082     case 'm':    // memory
02083     case 'o':    // offsetable
02084     case 'V':    // not offsetable
02085       return C_Memory;
02086     case 'i':    // Simple Integer or Relocatable Constant
02087     case 'n':    // Simple Integer
02088     case 'E':    // Floating Point Constant
02089     case 'F':    // Floating Point Constant
02090     case 's':    // Relocatable Constant
02091     case 'p':    // Address.
02092     case 'X':    // Allow ANY value.
02093     case 'I':    // Target registers.
02094     case 'J':
02095     case 'K':
02096     case 'L':
02097     case 'M':
02098     case 'N':
02099     case 'O':
02100     case 'P':
02101     case '<':
02102     case '>':
02103       return C_Other;
02104     }
02105   }
02106 
02107   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
02108     if (S == 8 && !Constraint.compare(1, 6, "memory", 6))  // "{memory}"
02109       return C_Memory;
02110     return C_Register;
02111   }
02112   return C_Unknown;
02113 }
02114 
02115 /// LowerXConstraint - try to replace an X constraint, which matches anything,
02116 /// with another that has more specific requirements based on the type of the
02117 /// corresponding operand.
02118 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
02119   if (ConstraintVT.isInteger())
02120     return "r";
02121   if (ConstraintVT.isFloatingPoint())
02122     return "f";      // works for many targets
02123   return nullptr;
02124 }
02125 
02126 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
02127 /// vector.  If it is invalid, don't add anything to Ops.
02128 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
02129                                                   std::string &Constraint,
02130                                                   std::vector<SDValue> &Ops,
02131                                                   SelectionDAG &DAG) const {
02132 
02133   if (Constraint.length() > 1) return;
02134 
02135   char ConstraintLetter = Constraint[0];
02136   switch (ConstraintLetter) {
02137   default: break;
02138   case 'X':     // Allows any operand; labels (basic block) use this.
02139     if (Op.getOpcode() == ISD::BasicBlock) {
02140       Ops.push_back(Op);
02141       return;
02142     }
02143     // fall through
02144   case 'i':    // Simple Integer or Relocatable Constant
02145   case 'n':    // Simple Integer
02146   case 's': {  // Relocatable Constant
02147     // These operands are interested in values of the form (GV+C), where C may
02148     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
02149     // is possible and fine if either GV or C are missing.
02150     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
02151     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
02152 
02153     // If we have "(add GV, C)", pull out GV/C
02154     if (Op.getOpcode() == ISD::ADD) {
02155       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
02156       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
02157       if (!C || !GA) {
02158         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
02159         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
02160       }
02161       if (!C || !GA)
02162         C = nullptr, GA = nullptr;
02163     }
02164 
02165     // If we find a valid operand, map to the TargetXXX version so that the
02166     // value itself doesn't get selected.
02167     if (GA) {   // Either &GV   or   &GV+C
02168       if (ConstraintLetter != 'n') {
02169         int64_t Offs = GA->getOffset();
02170         if (C) Offs += C->getZExtValue();
02171         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
02172                                                  C ? SDLoc(C) : SDLoc(),
02173                                                  Op.getValueType(), Offs));
02174         return;
02175       }
02176     }
02177     if (C) {   // just C, no GV.
02178       // Simple constants are not allowed for 's'.
02179       if (ConstraintLetter != 's') {
02180         // gcc prints these as sign extended.  Sign extend value to 64 bits
02181         // now; without this it would get ZExt'd later in
02182         // ScheduleDAGSDNodes::EmitNode, which is very generic.
02183         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
02184                                             MVT::i64));
02185         return;
02186       }
02187     }
02188     break;
02189   }
02190   }
02191 }
02192 
02193 std::pair<unsigned, const TargetRegisterClass *>
02194 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
02195                                              const std::string &Constraint,
02196                                              MVT VT) const {
02197   if (Constraint.empty() || Constraint[0] != '{')
02198     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
02199   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
02200 
02201   // Remove the braces from around the name.
02202   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
02203 
02204   std::pair<unsigned, const TargetRegisterClass*> R =
02205     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
02206 
02207   // Figure out which register class contains this reg.
02208   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
02209        E = RI->regclass_end(); RCI != E; ++RCI) {
02210     const TargetRegisterClass *RC = *RCI;
02211 
02212     // If none of the value types for this register class are valid, we
02213     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
02214     if (!isLegalRC(RC))
02215       continue;
02216 
02217     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
02218          I != E; ++I) {
02219       if (RegName.equals_lower(RI->getName(*I))) {
02220         std::pair<unsigned, const TargetRegisterClass*> S =
02221           std::make_pair(*I, RC);
02222 
02223         // If this register class has the requested value type, return it,
02224         // otherwise keep searching and return the first class found
02225         // if no other is found which explicitly has the requested type.
02226         if (RC->hasType(VT))
02227           return S;
02228         else if (!R.second)
02229           R = S;
02230       }
02231     }
02232   }
02233 
02234   return R;
02235 }
02236 
02237 //===----------------------------------------------------------------------===//
02238 // Constraint Selection.
02239 
02240 /// isMatchingInputConstraint - Return true of this is an input operand that is
02241 /// a matching constraint like "4".
02242 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
02243   assert(!ConstraintCode.empty() && "No known constraint!");
02244   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
02245 }
02246 
02247 /// getMatchedOperand - If this is an input matching constraint, this method
02248 /// returns the output operand it matches.
02249 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
02250   assert(!ConstraintCode.empty() && "No known constraint!");
02251   return atoi(ConstraintCode.c_str());
02252 }
02253 
02254 
02255 /// ParseConstraints - Split up the constraint string from the inline
02256 /// assembly value into the specific constraints and their prefixes,
02257 /// and also tie in the associated operand values.
02258 /// If this returns an empty vector, and if the constraint string itself
02259 /// isn't empty, there was an error parsing.
02260 TargetLowering::AsmOperandInfoVector
02261 TargetLowering::ParseConstraints(const TargetRegisterInfo *TRI,
02262                                  ImmutableCallSite CS) const {
02263   /// ConstraintOperands - Information about all of the constraints.
02264   AsmOperandInfoVector ConstraintOperands;
02265   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
02266   unsigned maCount = 0; // Largest number of multiple alternative constraints.
02267 
02268   // Do a prepass over the constraints, canonicalizing them, and building up the
02269   // ConstraintOperands list.
02270   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
02271   unsigned ResNo = 0;   // ResNo - The result number of the next output.
02272 
02273   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
02274     ConstraintOperands.emplace_back(std::move(CI));
02275     AsmOperandInfo &OpInfo = ConstraintOperands.back();
02276 
02277     // Update multiple alternative constraint count.
02278     if (OpInfo.multipleAlternatives.size() > maCount)
02279       maCount = OpInfo.multipleAlternatives.size();
02280 
02281     OpInfo.ConstraintVT = MVT::Other;
02282 
02283     // Compute the value type for each operand.
02284     switch (OpInfo.Type) {
02285     case InlineAsm::isOutput:
02286       // Indirect outputs just consume an argument.
02287       if (OpInfo.isIndirect) {
02288         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
02289         break;
02290       }
02291 
02292       // The return value of the call is this value.  As such, there is no
02293       // corresponding argument.
02294       assert(!CS.getType()->isVoidTy() &&
02295              "Bad inline asm!");
02296       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
02297         OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
02298       } else {
02299         assert(ResNo == 0 && "Asm only has one result!");
02300         OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
02301       }
02302       ++ResNo;
02303       break;
02304     case InlineAsm::isInput:
02305       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
02306       break;
02307     case InlineAsm::isClobber:
02308       // Nothing to do.
02309       break;
02310     }
02311 
02312     if (OpInfo.CallOperandVal) {
02313       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
02314       if (OpInfo.isIndirect) {
02315         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
02316         if (!PtrTy)
02317           report_fatal_error("Indirect operand for inline asm not a pointer!");
02318         OpTy = PtrTy->getElementType();
02319       }
02320 
02321       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
02322       if (StructType *STy = dyn_cast<StructType>(OpTy))
02323         if (STy->getNumElements() == 1)
02324           OpTy = STy->getElementType(0);
02325 
02326       // If OpTy is not a single value, it may be a struct/union that we
02327       // can tile with integers.
02328       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
02329         unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy);
02330         switch (BitSize) {
02331         default: break;
02332         case 1:
02333         case 8:
02334         case 16:
02335         case 32:
02336         case 64:
02337         case 128:
02338           OpInfo.ConstraintVT =
02339             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
02340           break;
02341         }
02342       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
02343         unsigned PtrSize
02344           = getDataLayout()->getPointerSizeInBits(PT->getAddressSpace());
02345         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
02346       } else {
02347         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
02348       }
02349     }
02350   }
02351 
02352   // If we have multiple alternative constraints, select the best alternative.
02353   if (!ConstraintOperands.empty()) {
02354     if (maCount) {
02355       unsigned bestMAIndex = 0;
02356       int bestWeight = -1;
02357       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
02358       int weight = -1;
02359       unsigned maIndex;
02360       // Compute the sums of the weights for each alternative, keeping track
02361       // of the best (highest weight) one so far.
02362       for (maIndex = 0; maIndex < maCount; ++maIndex) {
02363         int weightSum = 0;
02364         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02365             cIndex != eIndex; ++cIndex) {
02366           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
02367           if (OpInfo.Type == InlineAsm::isClobber)
02368             continue;
02369 
02370           // If this is an output operand with a matching input operand,
02371           // look up the matching input. If their types mismatch, e.g. one
02372           // is an integer, the other is floating point, or their sizes are
02373           // different, flag it as an maCantMatch.
02374           if (OpInfo.hasMatchingInput()) {
02375             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
02376             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
02377               if ((OpInfo.ConstraintVT.isInteger() !=
02378                    Input.ConstraintVT.isInteger()) ||
02379                   (OpInfo.ConstraintVT.getSizeInBits() !=
02380                    Input.ConstraintVT.getSizeInBits())) {
02381                 weightSum = -1;  // Can't match.
02382                 break;
02383               }
02384             }
02385           }
02386           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
02387           if (weight == -1) {
02388             weightSum = -1;
02389             break;
02390           }
02391           weightSum += weight;
02392         }
02393         // Update best.
02394         if (weightSum > bestWeight) {
02395           bestWeight = weightSum;
02396           bestMAIndex = maIndex;
02397         }
02398       }
02399 
02400       // Now select chosen alternative in each constraint.
02401       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02402           cIndex != eIndex; ++cIndex) {
02403         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
02404         if (cInfo.Type == InlineAsm::isClobber)
02405           continue;
02406         cInfo.selectAlternative(bestMAIndex);
02407       }
02408     }
02409   }
02410 
02411   // Check and hook up tied operands, choose constraint code to use.
02412   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02413       cIndex != eIndex; ++cIndex) {
02414     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
02415 
02416     // If this is an output operand with a matching input operand, look up the
02417     // matching input. If their types mismatch, e.g. one is an integer, the
02418     // other is floating point, or their sizes are different, flag it as an
02419     // error.
02420     if (OpInfo.hasMatchingInput()) {
02421       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
02422 
02423       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
02424         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
02425             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
02426                                          OpInfo.ConstraintVT);
02427         std::pair<unsigned, const TargetRegisterClass *> InputRC =
02428             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
02429                                          Input.ConstraintVT);
02430         if ((OpInfo.ConstraintVT.isInteger() !=
02431              Input.ConstraintVT.isInteger()) ||
02432             (MatchRC.second != InputRC.second)) {
02433           report_fatal_error("Unsupported asm: input constraint"
02434                              " with a matching output constraint of"
02435                              " incompatible type!");
02436         }
02437       }
02438 
02439     }
02440   }
02441 
02442   return ConstraintOperands;
02443 }
02444 
02445 
02446 /// getConstraintGenerality - Return an integer indicating how general CT
02447 /// is.
02448 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
02449   switch (CT) {
02450   case TargetLowering::C_Other:
02451   case TargetLowering::C_Unknown:
02452     return 0;
02453   case TargetLowering::C_Register:
02454     return 1;
02455   case TargetLowering::C_RegisterClass:
02456     return 2;
02457   case TargetLowering::C_Memory:
02458     return 3;
02459   }
02460   llvm_unreachable("Invalid constraint type");
02461 }
02462 
02463 /// Examine constraint type and operand type and determine a weight value.
02464 /// This object must already have been set up with the operand type
02465 /// and the current alternative constraint selected.
02466 TargetLowering::ConstraintWeight
02467   TargetLowering::getMultipleConstraintMatchWeight(
02468     AsmOperandInfo &info, int maIndex) const {
02469   InlineAsm::ConstraintCodeVector *rCodes;
02470   if (maIndex >= (int)info.multipleAlternatives.size())
02471     rCodes = &info.Codes;
02472   else
02473     rCodes = &info.multipleAlternatives[maIndex].Codes;
02474   ConstraintWeight BestWeight = CW_Invalid;
02475 
02476   // Loop over the options, keeping track of the most general one.
02477   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
02478     ConstraintWeight weight =
02479       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
02480     if (weight > BestWeight)
02481       BestWeight = weight;
02482   }
02483 
02484   return BestWeight;
02485 }
02486 
02487 /// Examine constraint type and operand type and determine a weight value.
02488 /// This object must already have been set up with the operand type
02489 /// and the current alternative constraint selected.
02490 TargetLowering::ConstraintWeight
02491   TargetLowering::getSingleConstraintMatchWeight(
02492     AsmOperandInfo &info, const char *constraint) const {
02493   ConstraintWeight weight = CW_Invalid;
02494   Value *CallOperandVal = info.CallOperandVal;
02495     // If we don't have a value, we can't do a match,
02496     // but allow it at the lowest weight.
02497   if (!CallOperandVal)
02498     return CW_Default;
02499   // Look at the constraint type.
02500   switch (*constraint) {
02501     case 'i': // immediate integer.
02502     case 'n': // immediate integer with a known value.
02503       if (isa<ConstantInt>(CallOperandVal))
02504         weight = CW_Constant;
02505       break;
02506     case 's': // non-explicit intregal immediate.
02507       if (isa<GlobalValue>(CallOperandVal))
02508         weight = CW_Constant;
02509       break;
02510     case 'E': // immediate float if host format.
02511     case 'F': // immediate float.
02512       if (isa<ConstantFP>(CallOperandVal))
02513         weight = CW_Constant;
02514       break;
02515     case '<': // memory operand with autodecrement.
02516     case '>': // memory operand with autoincrement.
02517     case 'm': // memory operand.
02518     case 'o': // offsettable memory operand
02519     case 'V': // non-offsettable memory operand
02520       weight = CW_Memory;
02521       break;
02522     case 'r': // general register.
02523     case 'g': // general register, memory operand or immediate integer.
02524               // note: Clang converts "g" to "imr".
02525       if (CallOperandVal->getType()->isIntegerTy())
02526         weight = CW_Register;
02527       break;
02528     case 'X': // any operand.
02529     default:
02530       weight = CW_Default;
02531       break;
02532   }
02533   return weight;
02534 }
02535 
02536 /// ChooseConstraint - If there are multiple different constraints that we
02537 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
02538 /// This is somewhat tricky: constraints fall into four classes:
02539 ///    Other         -> immediates and magic values
02540 ///    Register      -> one specific register
02541 ///    RegisterClass -> a group of regs
02542 ///    Memory        -> memory
02543 /// Ideally, we would pick the most specific constraint possible: if we have
02544 /// something that fits into a register, we would pick it.  The problem here
02545 /// is that if we have something that could either be in a register or in
02546 /// memory that use of the register could cause selection of *other*
02547 /// operands to fail: they might only succeed if we pick memory.  Because of
02548 /// this the heuristic we use is:
02549 ///
02550 ///  1) If there is an 'other' constraint, and if the operand is valid for
02551 ///     that constraint, use it.  This makes us take advantage of 'i'
02552 ///     constraints when available.
02553 ///  2) Otherwise, pick the most general constraint present.  This prefers
02554 ///     'm' over 'r', for example.
02555 ///
02556 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
02557                              const TargetLowering &TLI,
02558                              SDValue Op, SelectionDAG *DAG) {
02559   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
02560   unsigned BestIdx = 0;
02561   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
02562   int BestGenerality = -1;
02563 
02564   // Loop over the options, keeping track of the most general one.
02565   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
02566     TargetLowering::ConstraintType CType =
02567       TLI.getConstraintType(OpInfo.Codes[i]);
02568 
02569     // If this is an 'other' constraint, see if the operand is valid for it.
02570     // For example, on X86 we might have an 'rI' constraint.  If the operand
02571     // is an integer in the range [0..31] we want to use I (saving a load
02572     // of a register), otherwise we must use 'r'.
02573     if (CType == TargetLowering::C_Other && Op.getNode()) {
02574       assert(OpInfo.Codes[i].size() == 1 &&
02575              "Unhandled multi-letter 'other' constraint");
02576       std::vector<SDValue> ResultOps;
02577       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
02578                                        ResultOps, *DAG);
02579       if (!ResultOps.empty()) {
02580         BestType = CType;
02581         BestIdx = i;
02582         break;
02583       }
02584     }
02585 
02586     // Things with matching constraints can only be registers, per gcc
02587     // documentation.  This mainly affects "g" constraints.
02588     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
02589       continue;
02590 
02591     // This constraint letter is more general than the previous one, use it.
02592     int Generality = getConstraintGenerality(CType);
02593     if (Generality > BestGenerality) {
02594       BestType = CType;
02595       BestIdx = i;
02596       BestGenerality = Generality;
02597     }
02598   }
02599 
02600   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
02601   OpInfo.ConstraintType = BestType;
02602 }
02603 
02604 /// ComputeConstraintToUse - Determines the constraint code and constraint
02605 /// type to use for the specific AsmOperandInfo, setting
02606 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
02607 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
02608                                             SDValue Op,
02609                                             SelectionDAG *DAG) const {
02610   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
02611 
02612   // Single-letter constraints ('r') are very common.
02613   if (OpInfo.Codes.size() == 1) {
02614     OpInfo.ConstraintCode = OpInfo.Codes[0];
02615     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
02616   } else {
02617     ChooseConstraint(OpInfo, *this, Op, DAG);
02618   }
02619 
02620   // 'X' matches anything.
02621   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
02622     // Labels and constants are handled elsewhere ('X' is the only thing
02623     // that matches labels).  For Functions, the type here is the type of
02624     // the result, which is not what we want to look at; leave them alone.
02625     Value *v = OpInfo.CallOperandVal;
02626     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
02627       OpInfo.CallOperandVal = v;
02628       return;
02629     }
02630 
02631     // Otherwise, try to resolve it to something we know about by looking at
02632     // the actual operand type.
02633     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
02634       OpInfo.ConstraintCode = Repl;
02635       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
02636     }
02637   }
02638 }
02639 
02640 /// \brief Given an exact SDIV by a constant, create a multiplication
02641 /// with the multiplicative inverse of the constant.
02642 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
02643                                        SelectionDAG &DAG) const {
02644   ConstantSDNode *C = cast<ConstantSDNode>(Op2);
02645   APInt d = C->getAPIntValue();
02646   assert(d != 0 && "Division by zero!");
02647 
02648   // Shift the value upfront if it is even, so the LSB is one.
02649   unsigned ShAmt = d.countTrailingZeros();
02650   if (ShAmt) {
02651     // TODO: For UDIV use SRL instead of SRA.
02652     SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
02653     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, false, false,
02654                       true);
02655     d = d.ashr(ShAmt);
02656   }
02657 
02658   // Calculate the multiplicative inverse, using Newton's method.
02659   APInt t, xn = d;
02660   while ((t = d*xn) != 1)
02661     xn *= APInt(d.getBitWidth(), 2) - t;
02662 
02663   Op2 = DAG.getConstant(xn, Op1.getValueType());
02664   return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
02665 }
02666 
02667 /// \brief Given an ISD::SDIV node expressing a divide by constant,
02668 /// return a DAG expression to select that will generate the same value by
02669 /// multiplying by a magic number.
02670 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
02671 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
02672                                   SelectionDAG &DAG, bool IsAfterLegalization,
02673                                   std::vector<SDNode *> *Created) const {
02674   assert(Created && "No vector to hold sdiv ops.");
02675 
02676   EVT VT = N->getValueType(0);
02677   SDLoc dl(N);
02678 
02679   // Check to see if we can do this.
02680   // FIXME: We should be more aggressive here.
02681   if (!isTypeLegal(VT))
02682     return SDValue();
02683 
02684   APInt::ms magics = Divisor.magic();
02685 
02686   // Multiply the numerator (operand 0) by the magic value
02687   // FIXME: We should support doing a MUL in a wider type
02688   SDValue Q;
02689   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
02690                             isOperationLegalOrCustom(ISD::MULHS, VT))
02691     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
02692                     DAG.getConstant(magics.m, VT));
02693   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
02694                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
02695     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
02696                               N->getOperand(0),
02697                               DAG.getConstant(magics.m, VT)).getNode(), 1);
02698   else
02699     return SDValue();       // No mulhs or equvialent
02700   // If d > 0 and m < 0, add the numerator
02701   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
02702     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
02703     Created->push_back(Q.getNode());
02704   }
02705   // If d < 0 and m > 0, subtract the numerator.
02706   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
02707     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
02708     Created->push_back(Q.getNode());
02709   }
02710   // Shift right algebraic if shift value is nonzero
02711   if (magics.s > 0) {
02712     Q = DAG.getNode(ISD::SRA, dl, VT, Q,
02713                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
02714     Created->push_back(Q.getNode());
02715   }
02716   // Extract the sign bit and add it to the quotient
02717   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q,
02718                           DAG.getConstant(VT.getScalarSizeInBits() - 1,
02719                                           getShiftAmountTy(Q.getValueType())));
02720   Created->push_back(T.getNode());
02721   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
02722 }
02723 
02724 /// \brief Given an ISD::UDIV node expressing a divide by constant,
02725 /// return a DAG expression to select that will generate the same value by
02726 /// multiplying by a magic number.
02727 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
02728 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
02729                                   SelectionDAG &DAG, bool IsAfterLegalization,
02730                                   std::vector<SDNode *> *Created) const {
02731   assert(Created && "No vector to hold udiv ops.");
02732 
02733   EVT VT = N->getValueType(0);
02734   SDLoc dl(N);
02735 
02736   // Check to see if we can do this.
02737   // FIXME: We should be more aggressive here.
02738   if (!isTypeLegal(VT))
02739     return SDValue();
02740 
02741   // FIXME: We should use a narrower constant when the upper
02742   // bits are known to be zero.
02743   APInt::mu magics = Divisor.magicu();
02744 
02745   SDValue Q = N->getOperand(0);
02746 
02747   // If the divisor is even, we can avoid using the expensive fixup by shifting
02748   // the divided value upfront.
02749   if (magics.a != 0 && !Divisor[0]) {
02750     unsigned Shift = Divisor.countTrailingZeros();
02751     Q = DAG.getNode(ISD::SRL, dl, VT, Q,
02752                     DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
02753     Created->push_back(Q.getNode());
02754 
02755     // Get magic number for the shifted divisor.
02756     magics = Divisor.lshr(Shift).magicu(Shift);
02757     assert(magics.a == 0 && "Should use cheap fixup now");
02758   }
02759 
02760   // Multiply the numerator (operand 0) by the magic value
02761   // FIXME: We should support doing a MUL in a wider type
02762   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
02763                             isOperationLegalOrCustom(ISD::MULHU, VT))
02764     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
02765   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
02766                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
02767     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
02768                             DAG.getConstant(magics.m, VT)).getNode(), 1);
02769   else
02770     return SDValue();       // No mulhu or equvialent
02771 
02772   Created->push_back(Q.getNode());
02773 
02774   if (magics.a == 0) {
02775     assert(magics.s < Divisor.getBitWidth() &&
02776            "We shouldn't generate an undefined shift!");
02777     return DAG.getNode(ISD::SRL, dl, VT, Q,
02778                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
02779   } else {
02780     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
02781     Created->push_back(NPQ.getNode());
02782     NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
02783                       DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
02784     Created->push_back(NPQ.getNode());
02785     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
02786     Created->push_back(NPQ.getNode());
02787     return DAG.getNode(ISD::SRL, dl, VT, NPQ,
02788              DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
02789   }
02790 }
02791 
02792 bool TargetLowering::
02793 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
02794   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
02795     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
02796                                 "be a constant integer");
02797     return true;
02798   }
02799 
02800   return false;
02801 }
02802 
02803 //===----------------------------------------------------------------------===//
02804 // Legalization Utilities
02805 //===----------------------------------------------------------------------===//
02806 
02807 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
02808                                SelectionDAG &DAG, SDValue LL, SDValue LH,
02809                                SDValue RL, SDValue RH) const {
02810   EVT VT = N->getValueType(0);
02811   SDLoc dl(N);
02812 
02813   bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
02814   bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
02815   bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
02816   bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
02817   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
02818     unsigned OuterBitSize = VT.getSizeInBits();
02819     unsigned InnerBitSize = HiLoVT.getSizeInBits();
02820     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
02821     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
02822 
02823     // LL, LH, RL, and RH must be either all NULL or all set to a value.
02824     assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
02825            (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
02826 
02827     if (!LL.getNode() && !RL.getNode() &&
02828         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
02829       LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
02830       RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
02831     }
02832 
02833     if (!LL.getNode())
02834       return false;
02835 
02836     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
02837     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
02838         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
02839       // The inputs are both zero-extended.
02840       if (HasUMUL_LOHI) {
02841         // We can emit a umul_lohi.
02842         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
02843                          RL);
02844         Hi = SDValue(Lo.getNode(), 1);
02845         return true;
02846       }
02847       if (HasMULHU) {
02848         // We can emit a mulhu+mul.
02849         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02850         Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
02851         return true;
02852       }
02853     }
02854     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
02855       // The input values are both sign-extended.
02856       if (HasSMUL_LOHI) {
02857         // We can emit a smul_lohi.
02858         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
02859                          RL);
02860         Hi = SDValue(Lo.getNode(), 1);
02861         return true;
02862       }
02863       if (HasMULHS) {
02864         // We can emit a mulhs+mul.
02865         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02866         Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
02867         return true;
02868       }
02869     }
02870 
02871     if (!LH.getNode() && !RH.getNode() &&
02872         isOperationLegalOrCustom(ISD::SRL, VT) &&
02873         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
02874       unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
02875       SDValue Shift = DAG.getConstant(ShiftAmt, getShiftAmountTy(VT));
02876       LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
02877       LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
02878       RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
02879       RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
02880     }
02881 
02882     if (!LH.getNode())
02883       return false;
02884 
02885     if (HasUMUL_LOHI) {
02886       // Lo,Hi = umul LHS, RHS.
02887       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
02888                                      DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
02889       Lo = UMulLOHI;
02890       Hi = UMulLOHI.getValue(1);
02891       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
02892       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
02893       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
02894       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
02895       return true;
02896     }
02897     if (HasMULHU) {
02898       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02899       Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
02900       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
02901       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
02902       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
02903       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
02904       return true;
02905     }
02906   }
02907   return false;
02908 }
02909 
02910 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
02911                                SelectionDAG &DAG) const {
02912   EVT VT = Node->getOperand(0).getValueType();
02913   EVT NVT = Node->getValueType(0);
02914   SDLoc dl(SDValue(Node, 0));
02915 
02916   // FIXME: Only f32 to i64 conversions are supported.
02917   if (VT != MVT::f32 || NVT != MVT::i64)
02918     return false;
02919 
02920   // Expand f32 -> i64 conversion
02921   // This algorithm comes from compiler-rt's implementation of fixsfdi:
02922   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
02923   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
02924                                 VT.getSizeInBits());
02925   SDValue ExponentMask = DAG.getConstant(0x7F800000, IntVT);
02926   SDValue ExponentLoBit = DAG.getConstant(23, IntVT);
02927   SDValue Bias = DAG.getConstant(127, IntVT);
02928   SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()),
02929                                      IntVT);
02930   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, IntVT);
02931   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, IntVT);
02932 
02933   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
02934 
02935   SDValue ExponentBits = DAG.getNode(ISD::SRL, dl, IntVT,
02936       DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
02937       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT)));
02938   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
02939 
02940   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
02941       DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
02942       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT)));
02943   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
02944 
02945   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
02946       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
02947       DAG.getConstant(0x00800000, IntVT));
02948 
02949   R = DAG.getZExtOrTrunc(R, dl, NVT);
02950 
02951 
02952   R = DAG.getSelectCC(dl, Exponent, ExponentLoBit,
02953      DAG.getNode(ISD::SHL, dl, NVT, R,
02954                  DAG.getZExtOrTrunc(
02955                     DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
02956                     dl, getShiftAmountTy(IntVT))),
02957      DAG.getNode(ISD::SRL, dl, NVT, R,
02958                  DAG.getZExtOrTrunc(
02959                     DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
02960                     dl, getShiftAmountTy(IntVT))),
02961      ISD::SETGT);
02962 
02963   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
02964       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
02965       Sign);
02966 
02967   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, IntVT),
02968       DAG.getConstant(0, NVT), Ret, ISD::SETLT);
02969   return true;
02970 }