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 == NewMask) {
00797       unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
00798       SDValue InOp = Op.getOperand(0);
00799       unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
00800       bool AlreadySignExtended =
00801         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
00802       // However if the input is already sign extended we expect the sign
00803       // extension to be dropped altogether later and do not simplify.
00804       if (!AlreadySignExtended) {
00805         // Compute the correct shift amount type, which must be getShiftAmountTy
00806         // for scalar types after legalization.
00807         EVT ShiftAmtTy = Op.getValueType();
00808         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
00809           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
00810 
00811         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
00812         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
00813                                                  Op.getValueType(), InOp,
00814                                                  ShiftAmt));
00815       }
00816     }
00817 
00818     // Sign extension.  Compute the demanded bits in the result that are not
00819     // present in the input.
00820     APInt NewBits =
00821       APInt::getHighBitsSet(BitWidth,
00822                             BitWidth - ExVT.getScalarType().getSizeInBits());
00823 
00824     // If none of the extended bits are demanded, eliminate the sextinreg.
00825     if ((NewBits & NewMask) == 0)
00826       return TLO.CombineTo(Op, Op.getOperand(0));
00827 
00828     APInt InSignBit =
00829       APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
00830     APInt InputDemandedBits =
00831       APInt::getLowBitsSet(BitWidth,
00832                            ExVT.getScalarType().getSizeInBits()) &
00833       NewMask;
00834 
00835     // Since the sign extended bits are demanded, we know that the sign
00836     // bit is demanded.
00837     InputDemandedBits |= InSignBit;
00838 
00839     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
00840                              KnownZero, KnownOne, TLO, Depth+1))
00841       return true;
00842     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00843 
00844     // If the sign bit of the input is known set or clear, then we know the
00845     // top bits of the result.
00846 
00847     // If the input sign bit is known zero, convert this into a zero extension.
00848     if (KnownZero.intersects(InSignBit))
00849       return TLO.CombineTo(Op,
00850                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
00851 
00852     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
00853       KnownOne |= NewBits;
00854       KnownZero &= ~NewBits;
00855     } else {                       // Input sign bit unknown
00856       KnownZero &= ~NewBits;
00857       KnownOne &= ~NewBits;
00858     }
00859     break;
00860   }
00861   case ISD::BUILD_PAIR: {
00862     EVT HalfVT = Op.getOperand(0).getValueType();
00863     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
00864 
00865     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
00866     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
00867 
00868     APInt KnownZeroLo, KnownOneLo;
00869     APInt KnownZeroHi, KnownOneHi;
00870 
00871     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
00872                              KnownOneLo, TLO, Depth + 1))
00873       return true;
00874 
00875     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
00876                              KnownOneHi, TLO, Depth + 1))
00877       return true;
00878 
00879     KnownZero = KnownZeroLo.zext(BitWidth) |
00880                 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
00881 
00882     KnownOne = KnownOneLo.zext(BitWidth) |
00883                KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
00884     break;
00885   }
00886   case ISD::ZERO_EXTEND: {
00887     unsigned OperandBitWidth =
00888       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00889     APInt InMask = NewMask.trunc(OperandBitWidth);
00890 
00891     // If none of the top bits are demanded, convert this into an any_extend.
00892     APInt NewBits =
00893       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
00894     if (!NewBits.intersects(NewMask))
00895       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
00896                                                Op.getValueType(),
00897                                                Op.getOperand(0)));
00898 
00899     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
00900                              KnownZero, KnownOne, TLO, Depth+1))
00901       return true;
00902     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00903     KnownZero = KnownZero.zext(BitWidth);
00904     KnownOne = KnownOne.zext(BitWidth);
00905     KnownZero |= NewBits;
00906     break;
00907   }
00908   case ISD::SIGN_EXTEND: {
00909     EVT InVT = Op.getOperand(0).getValueType();
00910     unsigned InBits = InVT.getScalarType().getSizeInBits();
00911     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
00912     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
00913     APInt NewBits   = ~InMask & NewMask;
00914 
00915     // If none of the top bits are demanded, convert this into an any_extend.
00916     if (NewBits == 0)
00917       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
00918                                               Op.getValueType(),
00919                                               Op.getOperand(0)));
00920 
00921     // Since some of the sign extended bits are demanded, we know that the sign
00922     // bit is demanded.
00923     APInt InDemandedBits = InMask & NewMask;
00924     InDemandedBits |= InSignBit;
00925     InDemandedBits = InDemandedBits.trunc(InBits);
00926 
00927     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
00928                              KnownOne, TLO, Depth+1))
00929       return true;
00930     KnownZero = KnownZero.zext(BitWidth);
00931     KnownOne = KnownOne.zext(BitWidth);
00932 
00933     // If the sign bit is known zero, convert this to a zero extend.
00934     if (KnownZero.intersects(InSignBit))
00935       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
00936                                                Op.getValueType(),
00937                                                Op.getOperand(0)));
00938 
00939     // If the sign bit is known one, the top bits match.
00940     if (KnownOne.intersects(InSignBit)) {
00941       KnownOne |= NewBits;
00942       assert((KnownZero & NewBits) == 0);
00943     } else {   // Otherwise, top bits aren't known.
00944       assert((KnownOne & NewBits) == 0);
00945       assert((KnownZero & NewBits) == 0);
00946     }
00947     break;
00948   }
00949   case ISD::ANY_EXTEND: {
00950     unsigned OperandBitWidth =
00951       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00952     APInt InMask = NewMask.trunc(OperandBitWidth);
00953     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
00954                              KnownZero, KnownOne, TLO, Depth+1))
00955       return true;
00956     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00957     KnownZero = KnownZero.zext(BitWidth);
00958     KnownOne = KnownOne.zext(BitWidth);
00959     break;
00960   }
00961   case ISD::TRUNCATE: {
00962     // Simplify the input, using demanded bit information, and compute the known
00963     // zero/one bits live out.
00964     unsigned OperandBitWidth =
00965       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00966     APInt TruncMask = NewMask.zext(OperandBitWidth);
00967     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
00968                              KnownZero, KnownOne, TLO, Depth+1))
00969       return true;
00970     KnownZero = KnownZero.trunc(BitWidth);
00971     KnownOne = KnownOne.trunc(BitWidth);
00972 
00973     // If the input is only used by this truncate, see if we can shrink it based
00974     // on the known demanded bits.
00975     if (Op.getOperand(0).getNode()->hasOneUse()) {
00976       SDValue In = Op.getOperand(0);
00977       switch (In.getOpcode()) {
00978       default: break;
00979       case ISD::SRL:
00980         // Shrink SRL by a constant if none of the high bits shifted in are
00981         // demanded.
00982         if (TLO.LegalTypes() &&
00983             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
00984           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
00985           // undesirable.
00986           break;
00987         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
00988         if (!ShAmt)
00989           break;
00990         SDValue Shift = In.getOperand(1);
00991         if (TLO.LegalTypes()) {
00992           uint64_t ShVal = ShAmt->getZExtValue();
00993           Shift =
00994             TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
00995         }
00996 
00997         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
00998                                                OperandBitWidth - BitWidth);
00999         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
01000 
01001         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
01002           // None of the shifted in bits are needed.  Add a truncate of the
01003           // shift input, then shift it.
01004           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
01005                                              Op.getValueType(),
01006                                              In.getOperand(0));
01007           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
01008                                                    Op.getValueType(),
01009                                                    NewTrunc,
01010                                                    Shift));
01011         }
01012         break;
01013       }
01014     }
01015 
01016     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01017     break;
01018   }
01019   case ISD::AssertZext: {
01020     // AssertZext demands all of the high bits, plus any of the low bits
01021     // demanded by its users.
01022     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
01023     APInt InMask = APInt::getLowBitsSet(BitWidth,
01024                                         VT.getSizeInBits());
01025     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
01026                              KnownZero, KnownOne, TLO, Depth+1))
01027       return true;
01028     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01029 
01030     KnownZero |= ~InMask & NewMask;
01031     break;
01032   }
01033   case ISD::BITCAST:
01034     // If this is an FP->Int bitcast and if the sign bit is the only
01035     // thing demanded, turn this into a FGETSIGN.
01036     if (!TLO.LegalOperations() &&
01037         !Op.getValueType().isVector() &&
01038         !Op.getOperand(0).getValueType().isVector() &&
01039         NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
01040         Op.getOperand(0).getValueType().isFloatingPoint()) {
01041       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
01042       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
01043       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
01044         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
01045         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
01046         // place.  We expect the SHL to be eliminated by other optimizations.
01047         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
01048         unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
01049         if (!OpVTLegal && OpVTSizeInBits > 32)
01050           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
01051         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
01052         SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
01053         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
01054                                                  Op.getValueType(),
01055                                                  Sign, ShAmt));
01056       }
01057     }
01058     break;
01059   case ISD::ADD:
01060   case ISD::MUL:
01061   case ISD::SUB: {
01062     // Add, Sub, and Mul don't demand any bits in positions beyond that
01063     // of the highest bit demanded of them.
01064     APInt LoMask = APInt::getLowBitsSet(BitWidth,
01065                                         BitWidth - NewMask.countLeadingZeros());
01066     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
01067                              KnownOne2, TLO, Depth+1))
01068       return true;
01069     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
01070                              KnownOne2, TLO, Depth+1))
01071       return true;
01072     // See if the operation should be performed at a smaller bit width.
01073     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
01074       return true;
01075   }
01076   // FALL THROUGH
01077   default:
01078     // Just use computeKnownBits to compute output bits.
01079     TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
01080     break;
01081   }
01082 
01083   // If we know the value of all of the demanded bits, return this as a
01084   // constant.
01085   if ((NewMask & (KnownZero|KnownOne)) == NewMask)
01086     return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
01087 
01088   return false;
01089 }
01090 
01091 /// computeKnownBitsForTargetNode - Determine which of the bits specified
01092 /// in Mask are known to be either zero or one and return them in the
01093 /// KnownZero/KnownOne bitsets.
01094 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
01095                                                    APInt &KnownZero,
01096                                                    APInt &KnownOne,
01097                                                    const SelectionDAG &DAG,
01098                                                    unsigned Depth) const {
01099   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
01100           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
01101           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
01102           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
01103          "Should use MaskedValueIsZero if you don't know whether Op"
01104          " is a target node!");
01105   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
01106 }
01107 
01108 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
01109 /// targets that want to expose additional information about sign bits to the
01110 /// DAG Combiner.
01111 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
01112                                                          const SelectionDAG &,
01113                                                          unsigned Depth) const {
01114   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
01115           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
01116           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
01117           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
01118          "Should use ComputeNumSignBits if you don't know whether Op"
01119          " is a target node!");
01120   return 1;
01121 }
01122 
01123 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
01124 /// one bit set. This differs from computeKnownBits in that it doesn't need to
01125 /// determine which bit is set.
01126 ///
01127 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
01128   // A left-shift of a constant one will have exactly one bit set, because
01129   // shifting the bit off the end is undefined.
01130   if (Val.getOpcode() == ISD::SHL)
01131     if (ConstantSDNode *C =
01132          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
01133       if (C->getAPIntValue() == 1)
01134         return true;
01135 
01136   // Similarly, a right-shift of a constant sign-bit will have exactly
01137   // one bit set.
01138   if (Val.getOpcode() == ISD::SRL)
01139     if (ConstantSDNode *C =
01140          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
01141       if (C->getAPIntValue().isSignBit())
01142         return true;
01143 
01144   // More could be done here, though the above checks are enough
01145   // to handle some common cases.
01146 
01147   // Fall back to computeKnownBits to catch other known cases.
01148   EVT OpVT = Val.getValueType();
01149   unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
01150   APInt KnownZero, KnownOne;
01151   DAG.computeKnownBits(Val, KnownZero, KnownOne);
01152   return (KnownZero.countPopulation() == BitWidth - 1) &&
01153          (KnownOne.countPopulation() == 1);
01154 }
01155 
01156 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
01157   if (!N)
01158     return false;
01159 
01160   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
01161   if (!CN) {
01162     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
01163     if (!BV)
01164       return false;
01165 
01166     BitVector UndefElements;
01167     CN = BV->getConstantSplatNode(&UndefElements);
01168     // Only interested in constant splats, and we don't try to handle undef
01169     // elements in identifying boolean constants.
01170     if (!CN || UndefElements.none())
01171       return false;
01172   }
01173 
01174   switch (getBooleanContents(N->getValueType(0))) {
01175   case UndefinedBooleanContent:
01176     return CN->getAPIntValue()[0];
01177   case ZeroOrOneBooleanContent:
01178     return CN->isOne();
01179   case ZeroOrNegativeOneBooleanContent:
01180     return CN->isAllOnesValue();
01181   }
01182 
01183   llvm_unreachable("Invalid boolean contents");
01184 }
01185 
01186 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
01187   if (!N)
01188     return false;
01189 
01190   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
01191   if (!CN) {
01192     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
01193     if (!BV)
01194       return false;
01195 
01196     BitVector UndefElements;
01197     CN = BV->getConstantSplatNode(&UndefElements);
01198     // Only interested in constant splats, and we don't try to handle undef
01199     // elements in identifying boolean constants.
01200     if (!CN || UndefElements.none())
01201       return false;
01202   }
01203 
01204   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
01205     return !CN->getAPIntValue()[0];
01206 
01207   return CN->isNullValue();
01208 }
01209 
01210 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
01211 /// and cc. If it is unable to simplify it, return a null SDValue.
01212 SDValue
01213 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
01214                               ISD::CondCode Cond, bool foldBooleans,
01215                               DAGCombinerInfo &DCI, SDLoc dl) const {
01216   SelectionDAG &DAG = DCI.DAG;
01217 
01218   // These setcc operations always fold.
01219   switch (Cond) {
01220   default: break;
01221   case ISD::SETFALSE:
01222   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
01223   case ISD::SETTRUE:
01224   case ISD::SETTRUE2: {
01225     TargetLowering::BooleanContent Cnt =
01226         getBooleanContents(N0->getValueType(0));
01227     return DAG.getConstant(
01228         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
01229   }
01230   }
01231 
01232   // Ensure that the constant occurs on the RHS, and fold constant
01233   // comparisons.
01234   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
01235   if (isa<ConstantSDNode>(N0.getNode()) &&
01236       (DCI.isBeforeLegalizeOps() ||
01237        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
01238     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
01239 
01240   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
01241     const APInt &C1 = N1C->getAPIntValue();
01242 
01243     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
01244     // equality comparison, then we're just comparing whether X itself is
01245     // zero.
01246     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
01247         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
01248         N0.getOperand(1).getOpcode() == ISD::Constant) {
01249       const APInt &ShAmt
01250         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
01251       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01252           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
01253         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
01254           // (srl (ctlz x), 5) == 0  -> X != 0
01255           // (srl (ctlz x), 5) != 1  -> X != 0
01256           Cond = ISD::SETNE;
01257         } else {
01258           // (srl (ctlz x), 5) != 0  -> X == 0
01259           // (srl (ctlz x), 5) == 1  -> X == 0
01260           Cond = ISD::SETEQ;
01261         }
01262         SDValue Zero = DAG.getConstant(0, N0.getValueType());
01263         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
01264                             Zero, Cond);
01265       }
01266     }
01267 
01268     SDValue CTPOP = N0;
01269     // Look through truncs that don't change the value of a ctpop.
01270     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
01271       CTPOP = N0.getOperand(0);
01272 
01273     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
01274         (N0 == CTPOP || N0.getValueType().getSizeInBits() >
01275                         Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
01276       EVT CTVT = CTPOP.getValueType();
01277       SDValue CTOp = CTPOP.getOperand(0);
01278 
01279       // (ctpop x) u< 2 -> (x & x-1) == 0
01280       // (ctpop x) u> 1 -> (x & x-1) != 0
01281       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
01282         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
01283                                   DAG.getConstant(1, CTVT));
01284         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
01285         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
01286         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
01287       }
01288 
01289       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
01290     }
01291 
01292     // (zext x) == C --> x == (trunc C)
01293     // (sext x) == C --> x == (trunc C)
01294     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01295         DCI.isBeforeLegalize() && N0->hasOneUse()) {
01296       unsigned MinBits = N0.getValueSizeInBits();
01297       SDValue PreExt;
01298       bool Signed = false;
01299       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
01300         // ZExt
01301         MinBits = N0->getOperand(0).getValueSizeInBits();
01302         PreExt = N0->getOperand(0);
01303       } else if (N0->getOpcode() == ISD::AND) {
01304         // DAGCombine turns costly ZExts into ANDs
01305         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
01306           if ((C->getAPIntValue()+1).isPowerOf2()) {
01307             MinBits = C->getAPIntValue().countTrailingOnes();
01308             PreExt = N0->getOperand(0);
01309           }
01310       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
01311         // SExt
01312         MinBits = N0->getOperand(0).getValueSizeInBits();
01313         PreExt = N0->getOperand(0);
01314         Signed = true;
01315       } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
01316         // ZEXTLOAD / SEXTLOAD
01317         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
01318           MinBits = LN0->getMemoryVT().getSizeInBits();
01319           PreExt = N0;
01320         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
01321           Signed = true;
01322           MinBits = LN0->getMemoryVT().getSizeInBits();
01323           PreExt = N0;
01324         }
01325       }
01326 
01327       // Figure out how many bits we need to preserve this constant.
01328       unsigned ReqdBits = Signed ?
01329         C1.getBitWidth() - C1.getNumSignBits() + 1 :
01330         C1.getActiveBits();
01331 
01332       // Make sure we're not losing bits from the constant.
01333       if (MinBits > 0 &&
01334           MinBits < C1.getBitWidth() &&
01335           MinBits >= ReqdBits) {
01336         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
01337         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
01338           // Will get folded away.
01339           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
01340           SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
01341           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
01342         }
01343       }
01344     }
01345 
01346     // If the LHS is '(and load, const)', the RHS is 0,
01347     // the test is for equality or unsigned, and all 1 bits of the const are
01348     // in the same partial word, see if we can shorten the load.
01349     if (DCI.isBeforeLegalize() &&
01350         !ISD::isSignedIntSetCC(Cond) &&
01351         N0.getOpcode() == ISD::AND && C1 == 0 &&
01352         N0.getNode()->hasOneUse() &&
01353         isa<LoadSDNode>(N0.getOperand(0)) &&
01354         N0.getOperand(0).getNode()->hasOneUse() &&
01355         isa<ConstantSDNode>(N0.getOperand(1))) {
01356       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
01357       APInt bestMask;
01358       unsigned bestWidth = 0, bestOffset = 0;
01359       if (!Lod->isVolatile() && Lod->isUnindexed()) {
01360         unsigned origWidth = N0.getValueType().getSizeInBits();
01361         unsigned maskWidth = origWidth;
01362         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
01363         // 8 bits, but have to be careful...
01364         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
01365           origWidth = Lod->getMemoryVT().getSizeInBits();
01366         const APInt &Mask =
01367           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
01368         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
01369           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
01370           for (unsigned offset=0; offset<origWidth/width; offset++) {
01371             if ((newMask & Mask) == Mask) {
01372               if (!getDataLayout()->isLittleEndian())
01373                 bestOffset = (origWidth/width - offset - 1) * (width/8);
01374               else
01375                 bestOffset = (uint64_t)offset * (width/8);
01376               bestMask = Mask.lshr(offset * (width/8) * 8);
01377               bestWidth = width;
01378               break;
01379             }
01380             newMask = newMask << width;
01381           }
01382         }
01383       }
01384       if (bestWidth) {
01385         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
01386         if (newVT.isRound()) {
01387           EVT PtrType = Lod->getOperand(1).getValueType();
01388           SDValue Ptr = Lod->getBasePtr();
01389           if (bestOffset != 0)
01390             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
01391                               DAG.getConstant(bestOffset, PtrType));
01392           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
01393           SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
01394                                 Lod->getPointerInfo().getWithOffset(bestOffset),
01395                                         false, false, false, NewAlign);
01396           return DAG.getSetCC(dl, VT,
01397                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
01398                                       DAG.getConstant(bestMask.trunc(bestWidth),
01399                                                       newVT)),
01400                               DAG.getConstant(0LL, newVT), Cond);
01401         }
01402       }
01403     }
01404 
01405     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
01406     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
01407       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
01408 
01409       // If the comparison constant has bits in the upper part, the
01410       // zero-extended value could never match.
01411       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
01412                                               C1.getBitWidth() - InSize))) {
01413         switch (Cond) {
01414         case ISD::SETUGT:
01415         case ISD::SETUGE:
01416         case ISD::SETEQ: return DAG.getConstant(0, VT);
01417         case ISD::SETULT:
01418         case ISD::SETULE:
01419         case ISD::SETNE: return DAG.getConstant(1, VT);
01420         case ISD::SETGT:
01421         case ISD::SETGE:
01422           // True if the sign bit of C1 is set.
01423           return DAG.getConstant(C1.isNegative(), VT);
01424         case ISD::SETLT:
01425         case ISD::SETLE:
01426           // True if the sign bit of C1 isn't set.
01427           return DAG.getConstant(C1.isNonNegative(), VT);
01428         default:
01429           break;
01430         }
01431       }
01432 
01433       // Otherwise, we can perform the comparison with the low bits.
01434       switch (Cond) {
01435       case ISD::SETEQ:
01436       case ISD::SETNE:
01437       case ISD::SETUGT:
01438       case ISD::SETUGE:
01439       case ISD::SETULT:
01440       case ISD::SETULE: {
01441         EVT newVT = N0.getOperand(0).getValueType();
01442         if (DCI.isBeforeLegalizeOps() ||
01443             (isOperationLegal(ISD::SETCC, newVT) &&
01444              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
01445           EVT NewSetCCVT = getSetCCResultType(*DAG.getContext(), newVT);
01446           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), newVT);
01447 
01448           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
01449                                           NewConst, Cond);
01450           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
01451         }
01452         break;
01453       }
01454       default:
01455         break;   // todo, be more careful with signed comparisons
01456       }
01457     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
01458                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01459       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
01460       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
01461       EVT ExtDstTy = N0.getValueType();
01462       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
01463 
01464       // If the constant doesn't fit into the number of bits for the source of
01465       // the sign extension, it is impossible for both sides to be equal.
01466       if (C1.getMinSignedBits() > ExtSrcTyBits)
01467         return DAG.getConstant(Cond == ISD::SETNE, VT);
01468 
01469       SDValue ZextOp;
01470       EVT Op0Ty = N0.getOperand(0).getValueType();
01471       if (Op0Ty == ExtSrcTy) {
01472         ZextOp = N0.getOperand(0);
01473       } else {
01474         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
01475         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
01476                               DAG.getConstant(Imm, Op0Ty));
01477       }
01478       if (!DCI.isCalledByLegalizer())
01479         DCI.AddToWorklist(ZextOp.getNode());
01480       // Otherwise, make this a use of a zext.
01481       return DAG.getSetCC(dl, VT, ZextOp,
01482                           DAG.getConstant(C1 & APInt::getLowBitsSet(
01483                                                               ExtDstTyBits,
01484                                                               ExtSrcTyBits),
01485                                           ExtDstTy),
01486                           Cond);
01487     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
01488                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01489       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
01490       if (N0.getOpcode() == ISD::SETCC &&
01491           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
01492         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
01493         if (TrueWhenTrue)
01494           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
01495         // Invert the condition.
01496         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
01497         CC = ISD::getSetCCInverse(CC,
01498                                   N0.getOperand(0).getValueType().isInteger());
01499         if (DCI.isBeforeLegalizeOps() ||
01500             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
01501           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
01502       }
01503 
01504       if ((N0.getOpcode() == ISD::XOR ||
01505            (N0.getOpcode() == ISD::AND &&
01506             N0.getOperand(0).getOpcode() == ISD::XOR &&
01507             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
01508           isa<ConstantSDNode>(N0.getOperand(1)) &&
01509           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
01510         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
01511         // can only do this if the top bits are known zero.
01512         unsigned BitWidth = N0.getValueSizeInBits();
01513         if (DAG.MaskedValueIsZero(N0,
01514                                   APInt::getHighBitsSet(BitWidth,
01515                                                         BitWidth-1))) {
01516           // Okay, get the un-inverted input value.
01517           SDValue Val;
01518           if (N0.getOpcode() == ISD::XOR)
01519             Val = N0.getOperand(0);
01520           else {
01521             assert(N0.getOpcode() == ISD::AND &&
01522                     N0.getOperand(0).getOpcode() == ISD::XOR);
01523             // ((X^1)&1)^1 -> X & 1
01524             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
01525                               N0.getOperand(0).getOperand(0),
01526                               N0.getOperand(1));
01527           }
01528 
01529           return DAG.getSetCC(dl, VT, Val, N1,
01530                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01531         }
01532       } else if (N1C->getAPIntValue() == 1 &&
01533                  (VT == MVT::i1 ||
01534                   getBooleanContents(N0->getValueType(0)) ==
01535                       ZeroOrOneBooleanContent)) {
01536         SDValue Op0 = N0;
01537         if (Op0.getOpcode() == ISD::TRUNCATE)
01538           Op0 = Op0.getOperand(0);
01539 
01540         if ((Op0.getOpcode() == ISD::XOR) &&
01541             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
01542             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
01543           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
01544           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
01545           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
01546                               Cond);
01547         }
01548         if (Op0.getOpcode() == ISD::AND &&
01549             isa<ConstantSDNode>(Op0.getOperand(1)) &&
01550             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
01551           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
01552           if (Op0.getValueType().bitsGT(VT))
01553             Op0 = DAG.getNode(ISD::AND, dl, VT,
01554                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
01555                           DAG.getConstant(1, VT));
01556           else if (Op0.getValueType().bitsLT(VT))
01557             Op0 = DAG.getNode(ISD::AND, dl, VT,
01558                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
01559                         DAG.getConstant(1, VT));
01560 
01561           return DAG.getSetCC(dl, VT, Op0,
01562                               DAG.getConstant(0, Op0.getValueType()),
01563                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01564         }
01565         if (Op0.getOpcode() == ISD::AssertZext &&
01566             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
01567           return DAG.getSetCC(dl, VT, Op0,
01568                               DAG.getConstant(0, Op0.getValueType()),
01569                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01570       }
01571     }
01572 
01573     APInt MinVal, MaxVal;
01574     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
01575     if (ISD::isSignedIntSetCC(Cond)) {
01576       MinVal = APInt::getSignedMinValue(OperandBitSize);
01577       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
01578     } else {
01579       MinVal = APInt::getMinValue(OperandBitSize);
01580       MaxVal = APInt::getMaxValue(OperandBitSize);
01581     }
01582 
01583     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
01584     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
01585       if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
01586       // X >= C0 --> X > (C0 - 1)
01587       APInt C = C1 - 1;
01588       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
01589       if ((DCI.isBeforeLegalizeOps() ||
01590            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
01591           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
01592                                 isLegalICmpImmediate(C.getSExtValue())))) {
01593         return DAG.getSetCC(dl, VT, N0,
01594                             DAG.getConstant(C, N1.getValueType()),
01595                             NewCC);
01596       }
01597     }
01598 
01599     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
01600       if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
01601       // X <= C0 --> X < (C0 + 1)
01602       APInt C = C1 + 1;
01603       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
01604       if ((DCI.isBeforeLegalizeOps() ||
01605            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
01606           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
01607                                 isLegalICmpImmediate(C.getSExtValue())))) {
01608         return DAG.getSetCC(dl, VT, N0,
01609                             DAG.getConstant(C, N1.getValueType()),
01610                             NewCC);
01611       }
01612     }
01613 
01614     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
01615       return DAG.getConstant(0, VT);      // X < MIN --> false
01616     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
01617       return DAG.getConstant(1, VT);      // X >= MIN --> true
01618     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
01619       return DAG.getConstant(0, VT);      // X > MAX --> false
01620     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
01621       return DAG.getConstant(1, VT);      // X <= MAX --> true
01622 
01623     // Canonicalize setgt X, Min --> setne X, Min
01624     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
01625       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
01626     // Canonicalize setlt X, Max --> setne X, Max
01627     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
01628       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
01629 
01630     // If we have setult X, 1, turn it into seteq X, 0
01631     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
01632       return DAG.getSetCC(dl, VT, N0,
01633                           DAG.getConstant(MinVal, N0.getValueType()),
01634                           ISD::SETEQ);
01635     // If we have setugt X, Max-1, turn it into seteq X, Max
01636     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
01637       return DAG.getSetCC(dl, VT, N0,
01638                           DAG.getConstant(MaxVal, N0.getValueType()),
01639                           ISD::SETEQ);
01640 
01641     // If we have "setcc X, C0", check to see if we can shrink the immediate
01642     // by changing cc.
01643 
01644     // SETUGT X, SINTMAX  -> SETLT X, 0
01645     if (Cond == ISD::SETUGT &&
01646         C1 == APInt::getSignedMaxValue(OperandBitSize))
01647       return DAG.getSetCC(dl, VT, N0,
01648                           DAG.getConstant(0, N1.getValueType()),
01649                           ISD::SETLT);
01650 
01651     // SETULT X, SINTMIN  -> SETGT X, -1
01652     if (Cond == ISD::SETULT &&
01653         C1 == APInt::getSignedMinValue(OperandBitSize)) {
01654       SDValue ConstMinusOne =
01655           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
01656                           N1.getValueType());
01657       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
01658     }
01659 
01660     // Fold bit comparisons when we can.
01661     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01662         (VT == N0.getValueType() ||
01663          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
01664         N0.getOpcode() == ISD::AND)
01665       if (ConstantSDNode *AndRHS =
01666                   dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01667         EVT ShiftTy = DCI.isBeforeLegalize() ?
01668           getPointerTy() : getShiftAmountTy(N0.getValueType());
01669         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
01670           // Perform the xform if the AND RHS is a single bit.
01671           if (AndRHS->getAPIntValue().isPowerOf2()) {
01672             return DAG.getNode(ISD::TRUNCATE, dl, VT,
01673                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
01674                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
01675           }
01676         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
01677           // (X & 8) == 8  -->  (X & 8) >> 3
01678           // Perform the xform if C1 is a single bit.
01679           if (C1.isPowerOf2()) {
01680             return DAG.getNode(ISD::TRUNCATE, dl, VT,
01681                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
01682                                       DAG.getConstant(C1.logBase2(), ShiftTy)));
01683           }
01684         }
01685       }
01686 
01687     if (C1.getMinSignedBits() <= 64 &&
01688         !isLegalICmpImmediate(C1.getSExtValue())) {
01689       // (X & -256) == 256 -> (X >> 8) == 1
01690       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01691           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
01692         if (ConstantSDNode *AndRHS =
01693             dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01694           const APInt &AndRHSC = AndRHS->getAPIntValue();
01695           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
01696             unsigned ShiftBits = AndRHSC.countTrailingZeros();
01697             EVT ShiftTy = DCI.isBeforeLegalize() ?
01698               getPointerTy() : getShiftAmountTy(N0.getValueType());
01699             EVT CmpTy = N0.getValueType();
01700             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
01701                                         DAG.getConstant(ShiftBits, ShiftTy));
01702             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
01703             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
01704           }
01705         }
01706       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
01707                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
01708         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
01709         // X <  0x100000000 -> (X >> 32) <  1
01710         // X >= 0x100000000 -> (X >> 32) >= 1
01711         // X <= 0x0ffffffff -> (X >> 32) <  1
01712         // X >  0x0ffffffff -> (X >> 32) >= 1
01713         unsigned ShiftBits;
01714         APInt NewC = C1;
01715         ISD::CondCode NewCond = Cond;
01716         if (AdjOne) {
01717           ShiftBits = C1.countTrailingOnes();
01718           NewC = NewC + 1;
01719           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
01720         } else {
01721           ShiftBits = C1.countTrailingZeros();
01722         }
01723         NewC = NewC.lshr(ShiftBits);
01724         if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
01725           EVT ShiftTy = DCI.isBeforeLegalize() ?
01726             getPointerTy() : getShiftAmountTy(N0.getValueType());
01727           EVT CmpTy = N0.getValueType();
01728           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
01729                                       DAG.getConstant(ShiftBits, ShiftTy));
01730           SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
01731           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
01732         }
01733       }
01734     }
01735   }
01736 
01737   if (isa<ConstantFPSDNode>(N0.getNode())) {
01738     // Constant fold or commute setcc.
01739     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
01740     if (O.getNode()) return O;
01741   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
01742     // If the RHS of an FP comparison is a constant, simplify it away in
01743     // some cases.
01744     if (CFP->getValueAPF().isNaN()) {
01745       // If an operand is known to be a nan, we can fold it.
01746       switch (ISD::getUnorderedFlavor(Cond)) {
01747       default: llvm_unreachable("Unknown flavor!");
01748       case 0:  // Known false.
01749         return DAG.getConstant(0, VT);
01750       case 1:  // Known true.
01751         return DAG.getConstant(1, VT);
01752       case 2:  // Undefined.
01753         return DAG.getUNDEF(VT);
01754       }
01755     }
01756 
01757     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
01758     // constant if knowing that the operand is non-nan is enough.  We prefer to
01759     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
01760     // materialize 0.0.
01761     if (Cond == ISD::SETO || Cond == ISD::SETUO)
01762       return DAG.getSetCC(dl, VT, N0, N0, Cond);
01763 
01764     // If the condition is not legal, see if we can find an equivalent one
01765     // which is legal.
01766     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
01767       // If the comparison was an awkward floating-point == or != and one of
01768       // the comparison operands is infinity or negative infinity, convert the
01769       // condition to a less-awkward <= or >=.
01770       if (CFP->getValueAPF().isInfinity()) {
01771         if (CFP->getValueAPF().isNegative()) {
01772           if (Cond == ISD::SETOEQ &&
01773               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
01774             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
01775           if (Cond == ISD::SETUEQ &&
01776               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
01777             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
01778           if (Cond == ISD::SETUNE &&
01779               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
01780             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
01781           if (Cond == ISD::SETONE &&
01782               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
01783             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
01784         } else {
01785           if (Cond == ISD::SETOEQ &&
01786               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
01787             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
01788           if (Cond == ISD::SETUEQ &&
01789               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
01790             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
01791           if (Cond == ISD::SETUNE &&
01792               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
01793             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
01794           if (Cond == ISD::SETONE &&
01795               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
01796             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
01797         }
01798       }
01799     }
01800   }
01801 
01802   if (N0 == N1) {
01803     // The sext(setcc()) => setcc() optimization relies on the appropriate
01804     // constant being emitted.
01805     uint64_t EqVal = 0;
01806     switch (getBooleanContents(N0.getValueType())) {
01807     case UndefinedBooleanContent:
01808     case ZeroOrOneBooleanContent:
01809       EqVal = ISD::isTrueWhenEqual(Cond);
01810       break;
01811     case ZeroOrNegativeOneBooleanContent:
01812       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
01813       break;
01814     }
01815 
01816     // We can always fold X == X for integer setcc's.
01817     if (N0.getValueType().isInteger()) {
01818       return DAG.getConstant(EqVal, VT);
01819     }
01820     unsigned UOF = ISD::getUnorderedFlavor(Cond);
01821     if (UOF == 2)   // FP operators that are undefined on NaNs.
01822       return DAG.getConstant(EqVal, VT);
01823     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
01824       return DAG.getConstant(EqVal, VT);
01825     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
01826     // if it is not already.
01827     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
01828     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
01829           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
01830       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
01831   }
01832 
01833   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01834       N0.getValueType().isInteger()) {
01835     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
01836         N0.getOpcode() == ISD::XOR) {
01837       // Simplify (X+Y) == (X+Z) -->  Y == Z
01838       if (N0.getOpcode() == N1.getOpcode()) {
01839         if (N0.getOperand(0) == N1.getOperand(0))
01840           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
01841         if (N0.getOperand(1) == N1.getOperand(1))
01842           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
01843         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
01844           // If X op Y == Y op X, try other combinations.
01845           if (N0.getOperand(0) == N1.getOperand(1))
01846             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
01847                                 Cond);
01848           if (N0.getOperand(1) == N1.getOperand(0))
01849             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
01850                                 Cond);
01851         }
01852       }
01853 
01854       // If RHS is a legal immediate value for a compare instruction, we need
01855       // to be careful about increasing register pressure needlessly.
01856       bool LegalRHSImm = false;
01857 
01858       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
01859         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01860           // Turn (X+C1) == C2 --> X == C2-C1
01861           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
01862             return DAG.getSetCC(dl, VT, N0.getOperand(0),
01863                                 DAG.getConstant(RHSC->getAPIntValue()-
01864                                                 LHSR->getAPIntValue(),
01865                                 N0.getValueType()), Cond);
01866           }
01867 
01868           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
01869           if (N0.getOpcode() == ISD::XOR)
01870             // If we know that all of the inverted bits are zero, don't bother
01871             // performing the inversion.
01872             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
01873               return
01874                 DAG.getSetCC(dl, VT, N0.getOperand(0),
01875                              DAG.getConstant(LHSR->getAPIntValue() ^
01876                                                RHSC->getAPIntValue(),
01877                                              N0.getValueType()),
01878                              Cond);
01879         }
01880 
01881         // Turn (C1-X) == C2 --> X == C1-C2
01882         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
01883           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
01884             return
01885               DAG.getSetCC(dl, VT, N0.getOperand(1),
01886                            DAG.getConstant(SUBC->getAPIntValue() -
01887                                              RHSC->getAPIntValue(),
01888                                            N0.getValueType()),
01889                            Cond);
01890           }
01891         }
01892 
01893         // Could RHSC fold directly into a compare?
01894         if (RHSC->getValueType(0).getSizeInBits() <= 64)
01895           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
01896       }
01897 
01898       // Simplify (X+Z) == X -->  Z == 0
01899       // Don't do this if X is an immediate that can fold into a cmp
01900       // instruction and X+Z has other uses. It could be an induction variable
01901       // chain, and the transform would increase register pressure.
01902       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
01903         if (N0.getOperand(0) == N1)
01904           return DAG.getSetCC(dl, VT, N0.getOperand(1),
01905                               DAG.getConstant(0, N0.getValueType()), Cond);
01906         if (N0.getOperand(1) == N1) {
01907           if (DAG.isCommutativeBinOp(N0.getOpcode()))
01908             return DAG.getSetCC(dl, VT, N0.getOperand(0),
01909                                 DAG.getConstant(0, N0.getValueType()), Cond);
01910           if (N0.getNode()->hasOneUse()) {
01911             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
01912             // (Z-X) == X  --> Z == X<<1
01913             SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
01914                        DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
01915             if (!DCI.isCalledByLegalizer())
01916               DCI.AddToWorklist(SH.getNode());
01917             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
01918           }
01919         }
01920       }
01921     }
01922 
01923     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
01924         N1.getOpcode() == ISD::XOR) {
01925       // Simplify  X == (X+Z) -->  Z == 0
01926       if (N1.getOperand(0) == N0)
01927         return DAG.getSetCC(dl, VT, N1.getOperand(1),
01928                         DAG.getConstant(0, N1.getValueType()), Cond);
01929       if (N1.getOperand(1) == N0) {
01930         if (DAG.isCommutativeBinOp(N1.getOpcode()))
01931           return DAG.getSetCC(dl, VT, N1.getOperand(0),
01932                           DAG.getConstant(0, N1.getValueType()), Cond);
01933         if (N1.getNode()->hasOneUse()) {
01934           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
01935           // X == (Z-X)  --> X<<1 == Z
01936           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
01937                        DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
01938           if (!DCI.isCalledByLegalizer())
01939             DCI.AddToWorklist(SH.getNode());
01940           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
01941         }
01942       }
01943     }
01944 
01945     // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
01946     // Note that where y is variable and is known to have at most
01947     // one bit set (for example, if it is z&1) we cannot do this;
01948     // the expressions are not equivalent when y==0.
01949     if (N0.getOpcode() == ISD::AND)
01950       if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
01951         if (ValueHasExactlyOneBitSet(N1, DAG)) {
01952           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
01953           if (DCI.isBeforeLegalizeOps() ||
01954               isCondCodeLegal(Cond, N0.getSimpleValueType())) {
01955             SDValue Zero = DAG.getConstant(0, N1.getValueType());
01956             return DAG.getSetCC(dl, VT, N0, Zero, Cond);
01957           }
01958         }
01959       }
01960     if (N1.getOpcode() == ISD::AND)
01961       if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
01962         if (ValueHasExactlyOneBitSet(N0, DAG)) {
01963           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
01964           if (DCI.isBeforeLegalizeOps() ||
01965               isCondCodeLegal(Cond, N1.getSimpleValueType())) {
01966             SDValue Zero = DAG.getConstant(0, N0.getValueType());
01967             return DAG.getSetCC(dl, VT, N1, Zero, Cond);
01968           }
01969         }
01970       }
01971   }
01972 
01973   // Fold away ALL boolean setcc's.
01974   SDValue Temp;
01975   if (N0.getValueType() == MVT::i1 && foldBooleans) {
01976     switch (Cond) {
01977     default: llvm_unreachable("Unknown integer setcc!");
01978     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
01979       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
01980       N0 = DAG.getNOT(dl, Temp, MVT::i1);
01981       if (!DCI.isCalledByLegalizer())
01982         DCI.AddToWorklist(Temp.getNode());
01983       break;
01984     case ISD::SETNE:  // X != Y   -->  (X^Y)
01985       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
01986       break;
01987     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
01988     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
01989       Temp = DAG.getNOT(dl, N0, MVT::i1);
01990       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
01991       if (!DCI.isCalledByLegalizer())
01992         DCI.AddToWorklist(Temp.getNode());
01993       break;
01994     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
01995     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
01996       Temp = DAG.getNOT(dl, N1, MVT::i1);
01997       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
01998       if (!DCI.isCalledByLegalizer())
01999         DCI.AddToWorklist(Temp.getNode());
02000       break;
02001     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
02002     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
02003       Temp = DAG.getNOT(dl, N0, MVT::i1);
02004       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
02005       if (!DCI.isCalledByLegalizer())
02006         DCI.AddToWorklist(Temp.getNode());
02007       break;
02008     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
02009     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
02010       Temp = DAG.getNOT(dl, N1, MVT::i1);
02011       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
02012       break;
02013     }
02014     if (VT != MVT::i1) {
02015       if (!DCI.isCalledByLegalizer())
02016         DCI.AddToWorklist(N0.getNode());
02017       // FIXME: If running after legalize, we probably can't do this.
02018       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
02019     }
02020     return N0;
02021   }
02022 
02023   // Could not fold it.
02024   return SDValue();
02025 }
02026 
02027 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
02028 /// node is a GlobalAddress + offset.
02029 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
02030                                     int64_t &Offset) const {
02031   if (isa<GlobalAddressSDNode>(N)) {
02032     GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
02033     GA = GASD->getGlobal();
02034     Offset += GASD->getOffset();
02035     return true;
02036   }
02037 
02038   if (N->getOpcode() == ISD::ADD) {
02039     SDValue N1 = N->getOperand(0);
02040     SDValue N2 = N->getOperand(1);
02041     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
02042       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
02043       if (V) {
02044         Offset += V->getSExtValue();
02045         return true;
02046       }
02047     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
02048       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
02049       if (V) {
02050         Offset += V->getSExtValue();
02051         return true;
02052       }
02053     }
02054   }
02055 
02056   return false;
02057 }
02058 
02059 
02060 SDValue TargetLowering::
02061 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
02062   // Default implementation: no optimization.
02063   return SDValue();
02064 }
02065 
02066 //===----------------------------------------------------------------------===//
02067 //  Inline Assembler Implementation Methods
02068 //===----------------------------------------------------------------------===//
02069 
02070 
02071 TargetLowering::ConstraintType
02072 TargetLowering::getConstraintType(const std::string &Constraint) const {
02073   unsigned S = Constraint.size();
02074 
02075   if (S == 1) {
02076     switch (Constraint[0]) {
02077     default: break;
02078     case 'r': return C_RegisterClass;
02079     case 'm':    // memory
02080     case 'o':    // offsetable
02081     case 'V':    // not offsetable
02082       return C_Memory;
02083     case 'i':    // Simple Integer or Relocatable Constant
02084     case 'n':    // Simple Integer
02085     case 'E':    // Floating Point Constant
02086     case 'F':    // Floating Point Constant
02087     case 's':    // Relocatable Constant
02088     case 'p':    // Address.
02089     case 'X':    // Allow ANY value.
02090     case 'I':    // Target registers.
02091     case 'J':
02092     case 'K':
02093     case 'L':
02094     case 'M':
02095     case 'N':
02096     case 'O':
02097     case 'P':
02098     case '<':
02099     case '>':
02100       return C_Other;
02101     }
02102   }
02103 
02104   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
02105     if (S == 8 && !Constraint.compare(1, 6, "memory", 6))  // "{memory}"
02106       return C_Memory;
02107     return C_Register;
02108   }
02109   return C_Unknown;
02110 }
02111 
02112 /// LowerXConstraint - try to replace an X constraint, which matches anything,
02113 /// with another that has more specific requirements based on the type of the
02114 /// corresponding operand.
02115 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
02116   if (ConstraintVT.isInteger())
02117     return "r";
02118   if (ConstraintVT.isFloatingPoint())
02119     return "f";      // works for many targets
02120   return nullptr;
02121 }
02122 
02123 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
02124 /// vector.  If it is invalid, don't add anything to Ops.
02125 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
02126                                                   std::string &Constraint,
02127                                                   std::vector<SDValue> &Ops,
02128                                                   SelectionDAG &DAG) const {
02129 
02130   if (Constraint.length() > 1) return;
02131 
02132   char ConstraintLetter = Constraint[0];
02133   switch (ConstraintLetter) {
02134   default: break;
02135   case 'X':     // Allows any operand; labels (basic block) use this.
02136     if (Op.getOpcode() == ISD::BasicBlock) {
02137       Ops.push_back(Op);
02138       return;
02139     }
02140     // fall through
02141   case 'i':    // Simple Integer or Relocatable Constant
02142   case 'n':    // Simple Integer
02143   case 's': {  // Relocatable Constant
02144     // These operands are interested in values of the form (GV+C), where C may
02145     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
02146     // is possible and fine if either GV or C are missing.
02147     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
02148     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
02149 
02150     // If we have "(add GV, C)", pull out GV/C
02151     if (Op.getOpcode() == ISD::ADD) {
02152       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
02153       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
02154       if (!C || !GA) {
02155         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
02156         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
02157       }
02158       if (!C || !GA)
02159         C = nullptr, GA = nullptr;
02160     }
02161 
02162     // If we find a valid operand, map to the TargetXXX version so that the
02163     // value itself doesn't get selected.
02164     if (GA) {   // Either &GV   or   &GV+C
02165       if (ConstraintLetter != 'n') {
02166         int64_t Offs = GA->getOffset();
02167         if (C) Offs += C->getZExtValue();
02168         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
02169                                                  C ? SDLoc(C) : SDLoc(),
02170                                                  Op.getValueType(), Offs));
02171         return;
02172       }
02173     }
02174     if (C) {   // just C, no GV.
02175       // Simple constants are not allowed for 's'.
02176       if (ConstraintLetter != 's') {
02177         // gcc prints these as sign extended.  Sign extend value to 64 bits
02178         // now; without this it would get ZExt'd later in
02179         // ScheduleDAGSDNodes::EmitNode, which is very generic.
02180         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
02181                                             MVT::i64));
02182         return;
02183       }
02184     }
02185     break;
02186   }
02187   }
02188 }
02189 
02190 std::pair<unsigned, const TargetRegisterClass *>
02191 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
02192                                              const std::string &Constraint,
02193                                              MVT VT) const {
02194   if (Constraint.empty() || Constraint[0] != '{')
02195     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
02196   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
02197 
02198   // Remove the braces from around the name.
02199   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
02200 
02201   std::pair<unsigned, const TargetRegisterClass*> R =
02202     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
02203 
02204   // Figure out which register class contains this reg.
02205   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
02206        E = RI->regclass_end(); RCI != E; ++RCI) {
02207     const TargetRegisterClass *RC = *RCI;
02208 
02209     // If none of the value types for this register class are valid, we
02210     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
02211     if (!isLegalRC(RC))
02212       continue;
02213 
02214     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
02215          I != E; ++I) {
02216       if (RegName.equals_lower(RI->getName(*I))) {
02217         std::pair<unsigned, const TargetRegisterClass*> S =
02218           std::make_pair(*I, RC);
02219 
02220         // If this register class has the requested value type, return it,
02221         // otherwise keep searching and return the first class found
02222         // if no other is found which explicitly has the requested type.
02223         if (RC->hasType(VT))
02224           return S;
02225         else if (!R.second)
02226           R = S;
02227       }
02228     }
02229   }
02230 
02231   return R;
02232 }
02233 
02234 //===----------------------------------------------------------------------===//
02235 // Constraint Selection.
02236 
02237 /// isMatchingInputConstraint - Return true of this is an input operand that is
02238 /// a matching constraint like "4".
02239 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
02240   assert(!ConstraintCode.empty() && "No known constraint!");
02241   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
02242 }
02243 
02244 /// getMatchedOperand - If this is an input matching constraint, this method
02245 /// returns the output operand it matches.
02246 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
02247   assert(!ConstraintCode.empty() && "No known constraint!");
02248   return atoi(ConstraintCode.c_str());
02249 }
02250 
02251 
02252 /// ParseConstraints - Split up the constraint string from the inline
02253 /// assembly value into the specific constraints and their prefixes,
02254 /// and also tie in the associated operand values.
02255 /// If this returns an empty vector, and if the constraint string itself
02256 /// isn't empty, there was an error parsing.
02257 TargetLowering::AsmOperandInfoVector
02258 TargetLowering::ParseConstraints(const TargetRegisterInfo *TRI,
02259                                  ImmutableCallSite CS) const {
02260   /// ConstraintOperands - Information about all of the constraints.
02261   AsmOperandInfoVector ConstraintOperands;
02262   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
02263   unsigned maCount = 0; // Largest number of multiple alternative constraints.
02264 
02265   // Do a prepass over the constraints, canonicalizing them, and building up the
02266   // ConstraintOperands list.
02267   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
02268   unsigned ResNo = 0;   // ResNo - The result number of the next output.
02269 
02270   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
02271     ConstraintOperands.emplace_back(std::move(CI));
02272     AsmOperandInfo &OpInfo = ConstraintOperands.back();
02273 
02274     // Update multiple alternative constraint count.
02275     if (OpInfo.multipleAlternatives.size() > maCount)
02276       maCount = OpInfo.multipleAlternatives.size();
02277 
02278     OpInfo.ConstraintVT = MVT::Other;
02279 
02280     // Compute the value type for each operand.
02281     switch (OpInfo.Type) {
02282     case InlineAsm::isOutput:
02283       // Indirect outputs just consume an argument.
02284       if (OpInfo.isIndirect) {
02285         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
02286         break;
02287       }
02288 
02289       // The return value of the call is this value.  As such, there is no
02290       // corresponding argument.
02291       assert(!CS.getType()->isVoidTy() &&
02292              "Bad inline asm!");
02293       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
02294         OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
02295       } else {
02296         assert(ResNo == 0 && "Asm only has one result!");
02297         OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
02298       }
02299       ++ResNo;
02300       break;
02301     case InlineAsm::isInput:
02302       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
02303       break;
02304     case InlineAsm::isClobber:
02305       // Nothing to do.
02306       break;
02307     }
02308 
02309     if (OpInfo.CallOperandVal) {
02310       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
02311       if (OpInfo.isIndirect) {
02312         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
02313         if (!PtrTy)
02314           report_fatal_error("Indirect operand for inline asm not a pointer!");
02315         OpTy = PtrTy->getElementType();
02316       }
02317 
02318       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
02319       if (StructType *STy = dyn_cast<StructType>(OpTy))
02320         if (STy->getNumElements() == 1)
02321           OpTy = STy->getElementType(0);
02322 
02323       // If OpTy is not a single value, it may be a struct/union that we
02324       // can tile with integers.
02325       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
02326         unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy);
02327         switch (BitSize) {
02328         default: break;
02329         case 1:
02330         case 8:
02331         case 16:
02332         case 32:
02333         case 64:
02334         case 128:
02335           OpInfo.ConstraintVT =
02336             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
02337           break;
02338         }
02339       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
02340         unsigned PtrSize
02341           = getDataLayout()->getPointerSizeInBits(PT->getAddressSpace());
02342         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
02343       } else {
02344         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
02345       }
02346     }
02347   }
02348 
02349   // If we have multiple alternative constraints, select the best alternative.
02350   if (!ConstraintOperands.empty()) {
02351     if (maCount) {
02352       unsigned bestMAIndex = 0;
02353       int bestWeight = -1;
02354       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
02355       int weight = -1;
02356       unsigned maIndex;
02357       // Compute the sums of the weights for each alternative, keeping track
02358       // of the best (highest weight) one so far.
02359       for (maIndex = 0; maIndex < maCount; ++maIndex) {
02360         int weightSum = 0;
02361         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02362             cIndex != eIndex; ++cIndex) {
02363           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
02364           if (OpInfo.Type == InlineAsm::isClobber)
02365             continue;
02366 
02367           // If this is an output operand with a matching input operand,
02368           // look up the matching input. If their types mismatch, e.g. one
02369           // is an integer, the other is floating point, or their sizes are
02370           // different, flag it as an maCantMatch.
02371           if (OpInfo.hasMatchingInput()) {
02372             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
02373             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
02374               if ((OpInfo.ConstraintVT.isInteger() !=
02375                    Input.ConstraintVT.isInteger()) ||
02376                   (OpInfo.ConstraintVT.getSizeInBits() !=
02377                    Input.ConstraintVT.getSizeInBits())) {
02378                 weightSum = -1;  // Can't match.
02379                 break;
02380               }
02381             }
02382           }
02383           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
02384           if (weight == -1) {
02385             weightSum = -1;
02386             break;
02387           }
02388           weightSum += weight;
02389         }
02390         // Update best.
02391         if (weightSum > bestWeight) {
02392           bestWeight = weightSum;
02393           bestMAIndex = maIndex;
02394         }
02395       }
02396 
02397       // Now select chosen alternative in each constraint.
02398       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02399           cIndex != eIndex; ++cIndex) {
02400         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
02401         if (cInfo.Type == InlineAsm::isClobber)
02402           continue;
02403         cInfo.selectAlternative(bestMAIndex);
02404       }
02405     }
02406   }
02407 
02408   // Check and hook up tied operands, choose constraint code to use.
02409   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02410       cIndex != eIndex; ++cIndex) {
02411     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
02412 
02413     // If this is an output operand with a matching input operand, look up the
02414     // matching input. If their types mismatch, e.g. one is an integer, the
02415     // other is floating point, or their sizes are different, flag it as an
02416     // error.
02417     if (OpInfo.hasMatchingInput()) {
02418       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
02419 
02420       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
02421         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
02422             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
02423                                          OpInfo.ConstraintVT);
02424         std::pair<unsigned, const TargetRegisterClass *> InputRC =
02425             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
02426                                          Input.ConstraintVT);
02427         if ((OpInfo.ConstraintVT.isInteger() !=
02428              Input.ConstraintVT.isInteger()) ||
02429             (MatchRC.second != InputRC.second)) {
02430           report_fatal_error("Unsupported asm: input constraint"
02431                              " with a matching output constraint of"
02432                              " incompatible type!");
02433         }
02434       }
02435 
02436     }
02437   }
02438 
02439   return ConstraintOperands;
02440 }
02441 
02442 
02443 /// getConstraintGenerality - Return an integer indicating how general CT
02444 /// is.
02445 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
02446   switch (CT) {
02447   case TargetLowering::C_Other:
02448   case TargetLowering::C_Unknown:
02449     return 0;
02450   case TargetLowering::C_Register:
02451     return 1;
02452   case TargetLowering::C_RegisterClass:
02453     return 2;
02454   case TargetLowering::C_Memory:
02455     return 3;
02456   }
02457   llvm_unreachable("Invalid constraint type");
02458 }
02459 
02460 /// Examine constraint type and operand type and determine a weight value.
02461 /// This object must already have been set up with the operand type
02462 /// and the current alternative constraint selected.
02463 TargetLowering::ConstraintWeight
02464   TargetLowering::getMultipleConstraintMatchWeight(
02465     AsmOperandInfo &info, int maIndex) const {
02466   InlineAsm::ConstraintCodeVector *rCodes;
02467   if (maIndex >= (int)info.multipleAlternatives.size())
02468     rCodes = &info.Codes;
02469   else
02470     rCodes = &info.multipleAlternatives[maIndex].Codes;
02471   ConstraintWeight BestWeight = CW_Invalid;
02472 
02473   // Loop over the options, keeping track of the most general one.
02474   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
02475     ConstraintWeight weight =
02476       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
02477     if (weight > BestWeight)
02478       BestWeight = weight;
02479   }
02480 
02481   return BestWeight;
02482 }
02483 
02484 /// Examine constraint type and operand type and determine a weight value.
02485 /// This object must already have been set up with the operand type
02486 /// and the current alternative constraint selected.
02487 TargetLowering::ConstraintWeight
02488   TargetLowering::getSingleConstraintMatchWeight(
02489     AsmOperandInfo &info, const char *constraint) const {
02490   ConstraintWeight weight = CW_Invalid;
02491   Value *CallOperandVal = info.CallOperandVal;
02492     // If we don't have a value, we can't do a match,
02493     // but allow it at the lowest weight.
02494   if (!CallOperandVal)
02495     return CW_Default;
02496   // Look at the constraint type.
02497   switch (*constraint) {
02498     case 'i': // immediate integer.
02499     case 'n': // immediate integer with a known value.
02500       if (isa<ConstantInt>(CallOperandVal))
02501         weight = CW_Constant;
02502       break;
02503     case 's': // non-explicit intregal immediate.
02504       if (isa<GlobalValue>(CallOperandVal))
02505         weight = CW_Constant;
02506       break;
02507     case 'E': // immediate float if host format.
02508     case 'F': // immediate float.
02509       if (isa<ConstantFP>(CallOperandVal))
02510         weight = CW_Constant;
02511       break;
02512     case '<': // memory operand with autodecrement.
02513     case '>': // memory operand with autoincrement.
02514     case 'm': // memory operand.
02515     case 'o': // offsettable memory operand
02516     case 'V': // non-offsettable memory operand
02517       weight = CW_Memory;
02518       break;
02519     case 'r': // general register.
02520     case 'g': // general register, memory operand or immediate integer.
02521               // note: Clang converts "g" to "imr".
02522       if (CallOperandVal->getType()->isIntegerTy())
02523         weight = CW_Register;
02524       break;
02525     case 'X': // any operand.
02526     default:
02527       weight = CW_Default;
02528       break;
02529   }
02530   return weight;
02531 }
02532 
02533 /// ChooseConstraint - If there are multiple different constraints that we
02534 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
02535 /// This is somewhat tricky: constraints fall into four classes:
02536 ///    Other         -> immediates and magic values
02537 ///    Register      -> one specific register
02538 ///    RegisterClass -> a group of regs
02539 ///    Memory        -> memory
02540 /// Ideally, we would pick the most specific constraint possible: if we have
02541 /// something that fits into a register, we would pick it.  The problem here
02542 /// is that if we have something that could either be in a register or in
02543 /// memory that use of the register could cause selection of *other*
02544 /// operands to fail: they might only succeed if we pick memory.  Because of
02545 /// this the heuristic we use is:
02546 ///
02547 ///  1) If there is an 'other' constraint, and if the operand is valid for
02548 ///     that constraint, use it.  This makes us take advantage of 'i'
02549 ///     constraints when available.
02550 ///  2) Otherwise, pick the most general constraint present.  This prefers
02551 ///     'm' over 'r', for example.
02552 ///
02553 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
02554                              const TargetLowering &TLI,
02555                              SDValue Op, SelectionDAG *DAG) {
02556   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
02557   unsigned BestIdx = 0;
02558   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
02559   int BestGenerality = -1;
02560 
02561   // Loop over the options, keeping track of the most general one.
02562   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
02563     TargetLowering::ConstraintType CType =
02564       TLI.getConstraintType(OpInfo.Codes[i]);
02565 
02566     // If this is an 'other' constraint, see if the operand is valid for it.
02567     // For example, on X86 we might have an 'rI' constraint.  If the operand
02568     // is an integer in the range [0..31] we want to use I (saving a load
02569     // of a register), otherwise we must use 'r'.
02570     if (CType == TargetLowering::C_Other && Op.getNode()) {
02571       assert(OpInfo.Codes[i].size() == 1 &&
02572              "Unhandled multi-letter 'other' constraint");
02573       std::vector<SDValue> ResultOps;
02574       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
02575                                        ResultOps, *DAG);
02576       if (!ResultOps.empty()) {
02577         BestType = CType;
02578         BestIdx = i;
02579         break;
02580       }
02581     }
02582 
02583     // Things with matching constraints can only be registers, per gcc
02584     // documentation.  This mainly affects "g" constraints.
02585     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
02586       continue;
02587 
02588     // This constraint letter is more general than the previous one, use it.
02589     int Generality = getConstraintGenerality(CType);
02590     if (Generality > BestGenerality) {
02591       BestType = CType;
02592       BestIdx = i;
02593       BestGenerality = Generality;
02594     }
02595   }
02596 
02597   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
02598   OpInfo.ConstraintType = BestType;
02599 }
02600 
02601 /// ComputeConstraintToUse - Determines the constraint code and constraint
02602 /// type to use for the specific AsmOperandInfo, setting
02603 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
02604 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
02605                                             SDValue Op,
02606                                             SelectionDAG *DAG) const {
02607   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
02608 
02609   // Single-letter constraints ('r') are very common.
02610   if (OpInfo.Codes.size() == 1) {
02611     OpInfo.ConstraintCode = OpInfo.Codes[0];
02612     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
02613   } else {
02614     ChooseConstraint(OpInfo, *this, Op, DAG);
02615   }
02616 
02617   // 'X' matches anything.
02618   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
02619     // Labels and constants are handled elsewhere ('X' is the only thing
02620     // that matches labels).  For Functions, the type here is the type of
02621     // the result, which is not what we want to look at; leave them alone.
02622     Value *v = OpInfo.CallOperandVal;
02623     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
02624       OpInfo.CallOperandVal = v;
02625       return;
02626     }
02627 
02628     // Otherwise, try to resolve it to something we know about by looking at
02629     // the actual operand type.
02630     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
02631       OpInfo.ConstraintCode = Repl;
02632       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
02633     }
02634   }
02635 }
02636 
02637 /// \brief Given an exact SDIV by a constant, create a multiplication
02638 /// with the multiplicative inverse of the constant.
02639 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
02640                                        SelectionDAG &DAG) const {
02641   ConstantSDNode *C = cast<ConstantSDNode>(Op2);
02642   APInt d = C->getAPIntValue();
02643   assert(d != 0 && "Division by zero!");
02644 
02645   // Shift the value upfront if it is even, so the LSB is one.
02646   unsigned ShAmt = d.countTrailingZeros();
02647   if (ShAmt) {
02648     // TODO: For UDIV use SRL instead of SRA.
02649     SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
02650     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, false, false,
02651                       true);
02652     d = d.ashr(ShAmt);
02653   }
02654 
02655   // Calculate the multiplicative inverse, using Newton's method.
02656   APInt t, xn = d;
02657   while ((t = d*xn) != 1)
02658     xn *= APInt(d.getBitWidth(), 2) - t;
02659 
02660   Op2 = DAG.getConstant(xn, Op1.getValueType());
02661   return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
02662 }
02663 
02664 /// \brief Given an ISD::SDIV node expressing a divide by constant,
02665 /// return a DAG expression to select that will generate the same value by
02666 /// multiplying by a magic number.
02667 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
02668 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
02669                                   SelectionDAG &DAG, bool IsAfterLegalization,
02670                                   std::vector<SDNode *> *Created) const {
02671   assert(Created && "No vector to hold sdiv ops.");
02672 
02673   EVT VT = N->getValueType(0);
02674   SDLoc dl(N);
02675 
02676   // Check to see if we can do this.
02677   // FIXME: We should be more aggressive here.
02678   if (!isTypeLegal(VT))
02679     return SDValue();
02680 
02681   APInt::ms magics = Divisor.magic();
02682 
02683   // Multiply the numerator (operand 0) by the magic value
02684   // FIXME: We should support doing a MUL in a wider type
02685   SDValue Q;
02686   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
02687                             isOperationLegalOrCustom(ISD::MULHS, VT))
02688     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
02689                     DAG.getConstant(magics.m, VT));
02690   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
02691                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
02692     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
02693                               N->getOperand(0),
02694                               DAG.getConstant(magics.m, VT)).getNode(), 1);
02695   else
02696     return SDValue();       // No mulhs or equvialent
02697   // If d > 0 and m < 0, add the numerator
02698   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
02699     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
02700     Created->push_back(Q.getNode());
02701   }
02702   // If d < 0 and m > 0, subtract the numerator.
02703   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
02704     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
02705     Created->push_back(Q.getNode());
02706   }
02707   // Shift right algebraic if shift value is nonzero
02708   if (magics.s > 0) {
02709     Q = DAG.getNode(ISD::SRA, dl, VT, Q,
02710                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
02711     Created->push_back(Q.getNode());
02712   }
02713   // Extract the sign bit and add it to the quotient
02714   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q,
02715                           DAG.getConstant(VT.getScalarSizeInBits() - 1,
02716                                           getShiftAmountTy(Q.getValueType())));
02717   Created->push_back(T.getNode());
02718   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
02719 }
02720 
02721 /// \brief Given an ISD::UDIV node expressing a divide by constant,
02722 /// return a DAG expression to select that will generate the same value by
02723 /// multiplying by a magic number.
02724 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
02725 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
02726                                   SelectionDAG &DAG, bool IsAfterLegalization,
02727                                   std::vector<SDNode *> *Created) const {
02728   assert(Created && "No vector to hold udiv ops.");
02729 
02730   EVT VT = N->getValueType(0);
02731   SDLoc dl(N);
02732 
02733   // Check to see if we can do this.
02734   // FIXME: We should be more aggressive here.
02735   if (!isTypeLegal(VT))
02736     return SDValue();
02737 
02738   // FIXME: We should use a narrower constant when the upper
02739   // bits are known to be zero.
02740   APInt::mu magics = Divisor.magicu();
02741 
02742   SDValue Q = N->getOperand(0);
02743 
02744   // If the divisor is even, we can avoid using the expensive fixup by shifting
02745   // the divided value upfront.
02746   if (magics.a != 0 && !Divisor[0]) {
02747     unsigned Shift = Divisor.countTrailingZeros();
02748     Q = DAG.getNode(ISD::SRL, dl, VT, Q,
02749                     DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
02750     Created->push_back(Q.getNode());
02751 
02752     // Get magic number for the shifted divisor.
02753     magics = Divisor.lshr(Shift).magicu(Shift);
02754     assert(magics.a == 0 && "Should use cheap fixup now");
02755   }
02756 
02757   // Multiply the numerator (operand 0) by the magic value
02758   // FIXME: We should support doing a MUL in a wider type
02759   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
02760                             isOperationLegalOrCustom(ISD::MULHU, VT))
02761     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
02762   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
02763                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
02764     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
02765                             DAG.getConstant(magics.m, VT)).getNode(), 1);
02766   else
02767     return SDValue();       // No mulhu or equvialent
02768 
02769   Created->push_back(Q.getNode());
02770 
02771   if (magics.a == 0) {
02772     assert(magics.s < Divisor.getBitWidth() &&
02773            "We shouldn't generate an undefined shift!");
02774     return DAG.getNode(ISD::SRL, dl, VT, Q,
02775                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
02776   } else {
02777     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
02778     Created->push_back(NPQ.getNode());
02779     NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
02780                       DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
02781     Created->push_back(NPQ.getNode());
02782     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
02783     Created->push_back(NPQ.getNode());
02784     return DAG.getNode(ISD::SRL, dl, VT, NPQ,
02785              DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
02786   }
02787 }
02788 
02789 bool TargetLowering::
02790 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
02791   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
02792     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
02793                                 "be a constant integer");
02794     return true;
02795   }
02796 
02797   return false;
02798 }
02799 
02800 //===----------------------------------------------------------------------===//
02801 // Legalization Utilities
02802 //===----------------------------------------------------------------------===//
02803 
02804 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
02805                                SelectionDAG &DAG, SDValue LL, SDValue LH,
02806                                SDValue RL, SDValue RH) const {
02807   EVT VT = N->getValueType(0);
02808   SDLoc dl(N);
02809 
02810   bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
02811   bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
02812   bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
02813   bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
02814   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
02815     unsigned OuterBitSize = VT.getSizeInBits();
02816     unsigned InnerBitSize = HiLoVT.getSizeInBits();
02817     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
02818     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
02819 
02820     // LL, LH, RL, and RH must be either all NULL or all set to a value.
02821     assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
02822            (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
02823 
02824     if (!LL.getNode() && !RL.getNode() &&
02825         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
02826       LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
02827       RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
02828     }
02829 
02830     if (!LL.getNode())
02831       return false;
02832 
02833     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
02834     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
02835         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
02836       // The inputs are both zero-extended.
02837       if (HasUMUL_LOHI) {
02838         // We can emit a umul_lohi.
02839         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
02840                          RL);
02841         Hi = SDValue(Lo.getNode(), 1);
02842         return true;
02843       }
02844       if (HasMULHU) {
02845         // We can emit a mulhu+mul.
02846         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02847         Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
02848         return true;
02849       }
02850     }
02851     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
02852       // The input values are both sign-extended.
02853       if (HasSMUL_LOHI) {
02854         // We can emit a smul_lohi.
02855         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
02856                          RL);
02857         Hi = SDValue(Lo.getNode(), 1);
02858         return true;
02859       }
02860       if (HasMULHS) {
02861         // We can emit a mulhs+mul.
02862         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02863         Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
02864         return true;
02865       }
02866     }
02867 
02868     if (!LH.getNode() && !RH.getNode() &&
02869         isOperationLegalOrCustom(ISD::SRL, VT) &&
02870         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
02871       unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
02872       SDValue Shift = DAG.getConstant(ShiftAmt, getShiftAmountTy(VT));
02873       LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
02874       LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
02875       RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
02876       RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
02877     }
02878 
02879     if (!LH.getNode())
02880       return false;
02881 
02882     if (HasUMUL_LOHI) {
02883       // Lo,Hi = umul LHS, RHS.
02884       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
02885                                      DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
02886       Lo = UMulLOHI;
02887       Hi = UMulLOHI.getValue(1);
02888       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
02889       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
02890       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
02891       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
02892       return true;
02893     }
02894     if (HasMULHU) {
02895       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02896       Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
02897       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
02898       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
02899       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
02900       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
02901       return true;
02902     }
02903   }
02904   return false;
02905 }
02906 
02907 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
02908                                SelectionDAG &DAG) const {
02909   EVT VT = Node->getOperand(0).getValueType();
02910   EVT NVT = Node->getValueType(0);
02911   SDLoc dl(SDValue(Node, 0));
02912 
02913   // FIXME: Only f32 to i64 conversions are supported.
02914   if (VT != MVT::f32 || NVT != MVT::i64)
02915     return false;
02916 
02917   // Expand f32 -> i64 conversion
02918   // This algorithm comes from compiler-rt's implementation of fixsfdi:
02919   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
02920   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
02921                                 VT.getSizeInBits());
02922   SDValue ExponentMask = DAG.getConstant(0x7F800000, IntVT);
02923   SDValue ExponentLoBit = DAG.getConstant(23, IntVT);
02924   SDValue Bias = DAG.getConstant(127, IntVT);
02925   SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()),
02926                                      IntVT);
02927   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, IntVT);
02928   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, IntVT);
02929 
02930   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
02931 
02932   SDValue ExponentBits = DAG.getNode(ISD::SRL, dl, IntVT,
02933       DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
02934       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT)));
02935   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
02936 
02937   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
02938       DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
02939       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT)));
02940   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
02941 
02942   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
02943       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
02944       DAG.getConstant(0x00800000, IntVT));
02945 
02946   R = DAG.getZExtOrTrunc(R, dl, NVT);
02947 
02948 
02949   R = DAG.getSelectCC(dl, Exponent, ExponentLoBit,
02950      DAG.getNode(ISD::SHL, dl, NVT, R,
02951                  DAG.getZExtOrTrunc(
02952                     DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
02953                     dl, getShiftAmountTy(IntVT))),
02954      DAG.getNode(ISD::SRL, dl, NVT, R,
02955                  DAG.getZExtOrTrunc(
02956                     DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
02957                     dl, getShiftAmountTy(IntVT))),
02958      ISD::SETGT);
02959 
02960   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
02961       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
02962       Sign);
02963 
02964   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, IntVT),
02965       DAG.getConstant(0, NVT), Ret, ISD::SETLT);
02966   return true;
02967 }