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