LLVM API Documentation

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