Make TargetLowering::getPointerTy() taking DataLayout as an argument
[oota-llvm.git] / lib / CodeGen / SelectionDAG / TargetLowering.cpp
1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include <cctype>
36 using namespace llvm;
37
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40   : TargetLoweringBase(tm) {}
41
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
43   return nullptr;
44 }
45
46 /// Check whether a given call node is in tail position within its function. If
47 /// so, it sets Chain to the input chain of the tail call.
48 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
49                                           SDValue &Chain) const {
50   const Function *F = DAG.getMachineFunction().getFunction();
51
52   // Conservatively require the attributes of the call to match those of
53   // the return. Ignore noalias because it doesn't affect the call sequence.
54   AttributeSet CallerAttrs = F->getAttributes();
55   if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
56       .removeAttribute(Attribute::NoAlias).hasAttributes())
57     return false;
58
59   // It's not safe to eliminate the sign / zero extension of the return value.
60   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
61       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
62     return false;
63
64   // Check if the only use is a function return node.
65   return isUsedByReturnOnly(Node, Chain);
66 }
67
68 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
69 /// and called function attributes.
70 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
71                                                  unsigned AttrIdx) {
72   isSExt     = CS->paramHasAttr(AttrIdx, Attribute::SExt);
73   isZExt     = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
74   isInReg    = CS->paramHasAttr(AttrIdx, Attribute::InReg);
75   isSRet     = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
76   isNest     = CS->paramHasAttr(AttrIdx, Attribute::Nest);
77   isByVal    = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
78   isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
79   isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
80   Alignment  = CS->getParamAlignment(AttrIdx);
81 }
82
83 /// Generate a libcall taking the given operands as arguments and returning a
84 /// result of type RetVT.
85 std::pair<SDValue, SDValue>
86 TargetLowering::makeLibCall(SelectionDAG &DAG,
87                             RTLIB::Libcall LC, EVT RetVT,
88                             const SDValue *Ops, unsigned NumOps,
89                             bool isSigned, SDLoc dl,
90                             bool doesNotReturn,
91                             bool isReturnValueUsed) const {
92   TargetLowering::ArgListTy Args;
93   Args.reserve(NumOps);
94
95   TargetLowering::ArgListEntry Entry;
96   for (unsigned i = 0; i != NumOps; ++i) {
97     Entry.Node = Ops[i];
98     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
99     Entry.isSExt = shouldSignExtendTypeInLibCall(Ops[i].getValueType(), isSigned);
100     Entry.isZExt = !shouldSignExtendTypeInLibCall(Ops[i].getValueType(), isSigned);
101     Args.push_back(Entry);
102   }
103   if (LC == RTLIB::UNKNOWN_LIBCALL)
104     report_fatal_error("Unsupported library call operation!");
105   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
106                                          getPointerTy(DAG.getDataLayout()));
107
108   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
109   TargetLowering::CallLoweringInfo CLI(DAG);
110   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
111   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
112     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
113     .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
114     .setSExtResult(signExtend).setZExtResult(!signExtend);
115   return LowerCallTo(CLI);
116 }
117
118
119 /// SoftenSetCCOperands - Soften the operands of a comparison.  This code is
120 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
121 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
122                                          SDValue &NewLHS, SDValue &NewRHS,
123                                          ISD::CondCode &CCCode,
124                                          SDLoc dl) const {
125   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
126          && "Unsupported setcc type!");
127
128   // Expand into one or more soft-fp libcall(s).
129   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
130   switch (CCCode) {
131   case ISD::SETEQ:
132   case ISD::SETOEQ:
133     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
134           (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
135     break;
136   case ISD::SETNE:
137   case ISD::SETUNE:
138     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
139           (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
140     break;
141   case ISD::SETGE:
142   case ISD::SETOGE:
143     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
144           (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
145     break;
146   case ISD::SETLT:
147   case ISD::SETOLT:
148     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
149           (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
150     break;
151   case ISD::SETLE:
152   case ISD::SETOLE:
153     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
154           (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
155     break;
156   case ISD::SETGT:
157   case ISD::SETOGT:
158     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
159           (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
160     break;
161   case ISD::SETUO:
162     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
163           (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
164     break;
165   case ISD::SETO:
166     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
167           (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
168     break;
169   default:
170     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
171           (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
172     switch (CCCode) {
173     case ISD::SETONE:
174       // SETONE = SETOLT | SETOGT
175       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
176             (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
177       // Fallthrough
178     case ISD::SETUGT:
179       LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
180             (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
181       break;
182     case ISD::SETUGE:
183       LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
184             (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
185       break;
186     case ISD::SETULT:
187       LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
188             (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
189       break;
190     case ISD::SETULE:
191       LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
192             (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
193       break;
194     case ISD::SETUEQ:
195       LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
196             (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
197       break;
198     default: llvm_unreachable("Do not know how to soften this setcc!");
199     }
200   }
201
202   // Use the target specific return value for comparions lib calls.
203   EVT RetVT = getCmpLibcallReturnType();
204   SDValue Ops[2] = { NewLHS, NewRHS };
205   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/,
206                        dl).first;
207   NewRHS = DAG.getConstant(0, dl, RetVT);
208   CCCode = getCmpLibcallCC(LC1);
209   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
210     SDValue Tmp = DAG.getNode(
211         ISD::SETCC, dl,
212         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
213         NewLHS, NewRHS, DAG.getCondCode(CCCode));
214     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/,
215                          dl).first;
216     NewLHS = DAG.getNode(
217         ISD::SETCC, dl,
218         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
219         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
220     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
221     NewRHS = SDValue();
222   }
223 }
224
225 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
226 /// current function.  The returned value is a member of the
227 /// MachineJumpTableInfo::JTEntryKind enum.
228 unsigned TargetLowering::getJumpTableEncoding() const {
229   // In non-pic modes, just use the address of a block.
230   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
231     return MachineJumpTableInfo::EK_BlockAddress;
232
233   // In PIC mode, if the target supports a GPRel32 directive, use it.
234   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
235     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
236
237   // Otherwise, use a label difference.
238   return MachineJumpTableInfo::EK_LabelDifference32;
239 }
240
241 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
242                                                  SelectionDAG &DAG) const {
243   // If our PIC model is GP relative, use the global offset table as the base.
244   unsigned JTEncoding = getJumpTableEncoding();
245
246   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
247       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
248     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
249
250   return Table;
251 }
252
253 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
254 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
255 /// MCExpr.
256 const MCExpr *
257 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
258                                              unsigned JTI,MCContext &Ctx) const{
259   // The normal PIC reloc base is the label at the start of the jump table.
260   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
261 }
262
263 bool
264 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
265   // Assume that everything is safe in static mode.
266   if (getTargetMachine().getRelocationModel() == Reloc::Static)
267     return true;
268
269   // In dynamic-no-pic mode, assume that known defined values are safe.
270   if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
271       GA && GA->getGlobal()->isStrongDefinitionForLinker())
272     return true;
273
274   // Otherwise assume nothing is safe.
275   return false;
276 }
277
278 //===----------------------------------------------------------------------===//
279 //  Optimization Methods
280 //===----------------------------------------------------------------------===//
281
282 /// ShrinkDemandedConstant - Check to see if the specified operand of the
283 /// specified instruction is a constant integer.  If so, check to see if there
284 /// are any bits set in the constant that are not demanded.  If so, shrink the
285 /// constant and return true.
286 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
287                                                         const APInt &Demanded) {
288   SDLoc dl(Op);
289
290   // FIXME: ISD::SELECT, ISD::SELECT_CC
291   switch (Op.getOpcode()) {
292   default: break;
293   case ISD::XOR:
294   case ISD::AND:
295   case ISD::OR: {
296     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
297     if (!C) return false;
298
299     if (Op.getOpcode() == ISD::XOR &&
300         (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
301       return false;
302
303     // if we can expand it to have all bits set, do it
304     if (C->getAPIntValue().intersects(~Demanded)) {
305       EVT VT = Op.getValueType();
306       SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
307                                 DAG.getConstant(Demanded &
308                                                 C->getAPIntValue(),
309                                                 dl, VT));
310       return CombineTo(Op, New);
311     }
312
313     break;
314   }
315   }
316
317   return false;
318 }
319
320 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
321 /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
322 /// cast, but it could be generalized for targets with other types of
323 /// implicit widening casts.
324 bool
325 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
326                                                     unsigned BitWidth,
327                                                     const APInt &Demanded,
328                                                     SDLoc dl) {
329   assert(Op.getNumOperands() == 2 &&
330          "ShrinkDemandedOp only supports binary operators!");
331   assert(Op.getNode()->getNumValues() == 1 &&
332          "ShrinkDemandedOp only supports nodes with one result!");
333
334   // Early return, as this function cannot handle vector types.
335   if (Op.getValueType().isVector())
336     return false;
337
338   // Don't do this if the node has another user, which may require the
339   // full value.
340   if (!Op.getNode()->hasOneUse())
341     return false;
342
343   // Search for the smallest integer type with free casts to and from
344   // Op's type. For expedience, just check power-of-2 integer types.
345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
346   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
347   unsigned SmallVTBits = DemandedSize;
348   if (!isPowerOf2_32(SmallVTBits))
349     SmallVTBits = NextPowerOf2(SmallVTBits);
350   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
351     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
352     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
353         TLI.isZExtFree(SmallVT, Op.getValueType())) {
354       // We found a type with free casts.
355       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
356                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
357                                           Op.getNode()->getOperand(0)),
358                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
359                                           Op.getNode()->getOperand(1)));
360       bool NeedZext = DemandedSize > SmallVTBits;
361       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
362                               dl, Op.getValueType(), X);
363       return CombineTo(Op, Z);
364     }
365   }
366   return false;
367 }
368
369 /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
370 /// DemandedMask bits of the result of Op are ever used downstream.  If we can
371 /// use this information to simplify Op, create a new simplified DAG node and
372 /// return true, returning the original and new nodes in Old and New. Otherwise,
373 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
374 /// the expression (used to simplify the caller).  The KnownZero/One bits may
375 /// only be accurate for those bits in the DemandedMask.
376 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
377                                           const APInt &DemandedMask,
378                                           APInt &KnownZero,
379                                           APInt &KnownOne,
380                                           TargetLoweringOpt &TLO,
381                                           unsigned Depth) const {
382   unsigned BitWidth = DemandedMask.getBitWidth();
383   assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
384          "Mask size mismatches value type size!");
385   APInt NewMask = DemandedMask;
386   SDLoc dl(Op);
387
388   // Don't know anything.
389   KnownZero = KnownOne = APInt(BitWidth, 0);
390
391   // Other users may use these bits.
392   if (!Op.getNode()->hasOneUse()) {
393     if (Depth != 0) {
394       // If not at the root, Just compute the KnownZero/KnownOne bits to
395       // simplify things downstream.
396       TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
397       return false;
398     }
399     // If this is the root being simplified, allow it to have multiple uses,
400     // just set the NewMask to all bits.
401     NewMask = APInt::getAllOnesValue(BitWidth);
402   } else if (DemandedMask == 0) {
403     // Not demanding any bits from Op.
404     if (Op.getOpcode() != ISD::UNDEF)
405       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
406     return false;
407   } else if (Depth == 6) {        // Limit search depth.
408     return false;
409   }
410
411   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
412   switch (Op.getOpcode()) {
413   case ISD::Constant:
414     // We know all of the bits for a constant!
415     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
416     KnownZero = ~KnownOne;
417     return false;   // Don't fall through, will infinitely loop.
418   case ISD::AND:
419     // If the RHS is a constant, check to see if the LHS would be zero without
420     // using the bits from the RHS.  Below, we use knowledge about the RHS to
421     // simplify the LHS, here we're using information from the LHS to simplify
422     // the RHS.
423     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
424       APInt LHSZero, LHSOne;
425       // Do not increment Depth here; that can cause an infinite loop.
426       TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
427       // If the LHS already has zeros where RHSC does, this and is dead.
428       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
429         return TLO.CombineTo(Op, Op.getOperand(0));
430       // If any of the set bits in the RHS are known zero on the LHS, shrink
431       // the constant.
432       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
433         return true;
434     }
435
436     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
437                              KnownOne, TLO, Depth+1))
438       return true;
439     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
440     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
441                              KnownZero2, KnownOne2, TLO, Depth+1))
442       return true;
443     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
444
445     // If all of the demanded bits are known one on one side, return the other.
446     // These bits cannot contribute to the result of the 'and'.
447     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
448       return TLO.CombineTo(Op, Op.getOperand(0));
449     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
450       return TLO.CombineTo(Op, Op.getOperand(1));
451     // If all of the demanded bits in the inputs are known zeros, return zero.
452     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
453       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
454     // If the RHS is a constant, see if we can simplify it.
455     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
456       return true;
457     // If the operation can be done in a smaller type, do so.
458     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
459       return true;
460
461     // Output known-1 bits are only known if set in both the LHS & RHS.
462     KnownOne &= KnownOne2;
463     // Output known-0 are known to be clear if zero in either the LHS | RHS.
464     KnownZero |= KnownZero2;
465     break;
466   case ISD::OR:
467     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
468                              KnownOne, TLO, Depth+1))
469       return true;
470     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
471     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
472                              KnownZero2, KnownOne2, TLO, Depth+1))
473       return true;
474     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
475
476     // If all of the demanded bits are known zero on one side, return the other.
477     // These bits cannot contribute to the result of the 'or'.
478     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
479       return TLO.CombineTo(Op, Op.getOperand(0));
480     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
481       return TLO.CombineTo(Op, Op.getOperand(1));
482     // If all of the potentially set bits on one side are known to be set on
483     // the other side, just use the 'other' side.
484     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
485       return TLO.CombineTo(Op, Op.getOperand(0));
486     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
487       return TLO.CombineTo(Op, Op.getOperand(1));
488     // If the RHS is a constant, see if we can simplify it.
489     if (TLO.ShrinkDemandedConstant(Op, NewMask))
490       return true;
491     // If the operation can be done in a smaller type, do so.
492     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
493       return true;
494
495     // Output known-0 bits are only known if clear in both the LHS & RHS.
496     KnownZero &= KnownZero2;
497     // Output known-1 are known to be set if set in either the LHS | RHS.
498     KnownOne |= KnownOne2;
499     break;
500   case ISD::XOR:
501     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
502                              KnownOne, TLO, Depth+1))
503       return true;
504     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
505     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
506                              KnownOne2, TLO, Depth+1))
507       return true;
508     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
509
510     // If all of the demanded bits are known zero on one side, return the other.
511     // These bits cannot contribute to the result of the 'xor'.
512     if ((KnownZero & NewMask) == NewMask)
513       return TLO.CombineTo(Op, Op.getOperand(0));
514     if ((KnownZero2 & NewMask) == NewMask)
515       return TLO.CombineTo(Op, Op.getOperand(1));
516     // If the operation can be done in a smaller type, do so.
517     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
518       return true;
519
520     // If all of the unknown bits are known to be zero on one side or the other
521     // (but not both) turn this into an *inclusive* or.
522     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
523     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
524       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
525                                                Op.getOperand(0),
526                                                Op.getOperand(1)));
527
528     // Output known-0 bits are known if clear or set in both the LHS & RHS.
529     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
530     // Output known-1 are known to be set if set in only one of the LHS, RHS.
531     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
532
533     // If all of the demanded bits on one side are known, and all of the set
534     // bits on that side are also known to be set on the other side, turn this
535     // into an AND, as we know the bits will be cleared.
536     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
537     // NB: it is okay if more bits are known than are requested
538     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
539       if (KnownOne == KnownOne2) { // set bits are the same on both sides
540         EVT VT = Op.getValueType();
541         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
542         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
543                                                  Op.getOperand(0), ANDC));
544       }
545     }
546
547     // If the RHS is a constant, see if we can simplify it.
548     // for XOR, we prefer to force bits to 1 if they will make a -1.
549     // if we can't force bits, try to shrink constant
550     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
551       APInt Expanded = C->getAPIntValue() | (~NewMask);
552       // if we can expand it to have all bits set, do it
553       if (Expanded.isAllOnesValue()) {
554         if (Expanded != C->getAPIntValue()) {
555           EVT VT = Op.getValueType();
556           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
557                                         TLO.DAG.getConstant(Expanded, dl, VT));
558           return TLO.CombineTo(Op, New);
559         }
560         // if it already has all the bits set, nothing to change
561         // but don't shrink either!
562       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
563         return true;
564       }
565     }
566
567     KnownZero = KnownZeroOut;
568     KnownOne  = KnownOneOut;
569     break;
570   case ISD::SELECT:
571     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
572                              KnownOne, TLO, Depth+1))
573       return true;
574     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
575                              KnownOne2, TLO, Depth+1))
576       return true;
577     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
578     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
579
580     // If the operands are constants, see if we can simplify them.
581     if (TLO.ShrinkDemandedConstant(Op, NewMask))
582       return true;
583
584     // Only known if known in both the LHS and RHS.
585     KnownOne &= KnownOne2;
586     KnownZero &= KnownZero2;
587     break;
588   case ISD::SELECT_CC:
589     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
590                              KnownOne, TLO, Depth+1))
591       return true;
592     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
593                              KnownOne2, TLO, Depth+1))
594       return true;
595     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
596     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
597
598     // If the operands are constants, see if we can simplify them.
599     if (TLO.ShrinkDemandedConstant(Op, NewMask))
600       return true;
601
602     // Only known if known in both the LHS and RHS.
603     KnownOne &= KnownOne2;
604     KnownZero &= KnownZero2;
605     break;
606   case ISD::SHL:
607     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
608       unsigned ShAmt = SA->getZExtValue();
609       SDValue InOp = Op.getOperand(0);
610
611       // If the shift count is an invalid immediate, don't do anything.
612       if (ShAmt >= BitWidth)
613         break;
614
615       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
616       // single shift.  We can do this if the bottom bits (which are shifted
617       // out) are never demanded.
618       if (InOp.getOpcode() == ISD::SRL &&
619           isa<ConstantSDNode>(InOp.getOperand(1))) {
620         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
621           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
622           unsigned Opc = ISD::SHL;
623           int Diff = ShAmt-C1;
624           if (Diff < 0) {
625             Diff = -Diff;
626             Opc = ISD::SRL;
627           }
628
629           SDValue NewSA =
630             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
631           EVT VT = Op.getValueType();
632           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
633                                                    InOp.getOperand(0), NewSA));
634         }
635       }
636
637       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
638                                KnownZero, KnownOne, TLO, Depth+1))
639         return true;
640
641       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
642       // are not demanded. This will likely allow the anyext to be folded away.
643       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
644         SDValue InnerOp = InOp.getNode()->getOperand(0);
645         EVT InnerVT = InnerOp.getValueType();
646         unsigned InnerBits = InnerVT.getSizeInBits();
647         if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
648             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
649           EVT ShTy = getShiftAmountTy(InnerVT);
650           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
651             ShTy = InnerVT;
652           SDValue NarrowShl =
653             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
654                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
655           return
656             TLO.CombineTo(Op,
657                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
658                                           NarrowShl));
659         }
660         // Repeat the SHL optimization above in cases where an extension
661         // intervenes: (shl (anyext (shr x, c1)), c2) to
662         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
663         // aren't demanded (as above) and that the shifted upper c1 bits of
664         // x aren't demanded.
665         if (InOp.hasOneUse() &&
666             InnerOp.getOpcode() == ISD::SRL &&
667             InnerOp.hasOneUse() &&
668             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
669           uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
670             ->getZExtValue();
671           if (InnerShAmt < ShAmt &&
672               InnerShAmt < InnerBits &&
673               NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
674               NewMask.trunc(ShAmt) == 0) {
675             SDValue NewSA =
676               TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
677                                   Op.getOperand(1).getValueType());
678             EVT VT = Op.getValueType();
679             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
680                                              InnerOp.getOperand(0));
681             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
682                                                      NewExt, NewSA));
683           }
684         }
685       }
686
687       KnownZero <<= SA->getZExtValue();
688       KnownOne  <<= SA->getZExtValue();
689       // low bits known zero.
690       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
691     }
692     break;
693   case ISD::SRL:
694     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
695       EVT VT = Op.getValueType();
696       unsigned ShAmt = SA->getZExtValue();
697       unsigned VTSize = VT.getSizeInBits();
698       SDValue InOp = Op.getOperand(0);
699
700       // If the shift count is an invalid immediate, don't do anything.
701       if (ShAmt >= BitWidth)
702         break;
703
704       APInt InDemandedMask = (NewMask << ShAmt);
705
706       // If the shift is exact, then it does demand the low bits (and knows that
707       // they are zero).
708       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
709         InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
710
711       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
712       // single shift.  We can do this if the top bits (which are shifted out)
713       // are never demanded.
714       if (InOp.getOpcode() == ISD::SHL &&
715           isa<ConstantSDNode>(InOp.getOperand(1))) {
716         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
717           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
718           unsigned Opc = ISD::SRL;
719           int Diff = ShAmt-C1;
720           if (Diff < 0) {
721             Diff = -Diff;
722             Opc = ISD::SHL;
723           }
724
725           SDValue NewSA =
726             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
727           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
728                                                    InOp.getOperand(0), NewSA));
729         }
730       }
731
732       // Compute the new bits that are at the top now.
733       if (SimplifyDemandedBits(InOp, InDemandedMask,
734                                KnownZero, KnownOne, TLO, Depth+1))
735         return true;
736       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
737       KnownZero = KnownZero.lshr(ShAmt);
738       KnownOne  = KnownOne.lshr(ShAmt);
739
740       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
741       KnownZero |= HighBits;  // High bits known zero.
742     }
743     break;
744   case ISD::SRA:
745     // If this is an arithmetic shift right and only the low-bit is set, we can
746     // always convert this into a logical shr, even if the shift amount is
747     // variable.  The low bit of the shift cannot be an input sign bit unless
748     // the shift amount is >= the size of the datatype, which is undefined.
749     if (NewMask == 1)
750       return TLO.CombineTo(Op,
751                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
752                                            Op.getOperand(0), Op.getOperand(1)));
753
754     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
755       EVT VT = Op.getValueType();
756       unsigned ShAmt = SA->getZExtValue();
757
758       // If the shift count is an invalid immediate, don't do anything.
759       if (ShAmt >= BitWidth)
760         break;
761
762       APInt InDemandedMask = (NewMask << ShAmt);
763
764       // If the shift is exact, then it does demand the low bits (and knows that
765       // they are zero).
766       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
767         InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
768
769       // If any of the demanded bits are produced by the sign extension, we also
770       // demand the input sign bit.
771       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
772       if (HighBits.intersects(NewMask))
773         InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
774
775       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
776                                KnownZero, KnownOne, TLO, Depth+1))
777         return true;
778       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
779       KnownZero = KnownZero.lshr(ShAmt);
780       KnownOne  = KnownOne.lshr(ShAmt);
781
782       // Handle the sign bit, adjusted to where it is now in the mask.
783       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
784
785       // If the input sign bit is known to be zero, or if none of the top bits
786       // are demanded, turn this into an unsigned shift right.
787       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
788         SDNodeFlags Flags;
789         Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
790         return TLO.CombineTo(Op,
791                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
792                                              Op.getOperand(1), &Flags));
793       }
794
795       int Log2 = NewMask.exactLogBase2();
796       if (Log2 >= 0) {
797         // The bit must come from the sign.
798         SDValue NewSA =
799           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
800                               Op.getOperand(1).getValueType());
801         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
802                                                  Op.getOperand(0), NewSA));
803       }
804
805       if (KnownOne.intersects(SignBit))
806         // New bits are known one.
807         KnownOne |= HighBits;
808     }
809     break;
810   case ISD::SIGN_EXTEND_INREG: {
811     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
812
813     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
814     // If we only care about the highest bit, don't bother shifting right.
815     if (MsbMask == NewMask) {
816       unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
817       SDValue InOp = Op.getOperand(0);
818       unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
819       bool AlreadySignExtended =
820         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
821       // However if the input is already sign extended we expect the sign
822       // extension to be dropped altogether later and do not simplify.
823       if (!AlreadySignExtended) {
824         // Compute the correct shift amount type, which must be getShiftAmountTy
825         // for scalar types after legalization.
826         EVT ShiftAmtTy = Op.getValueType();
827         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
828           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
829
830         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
831                                                ShiftAmtTy);
832         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
833                                                  Op.getValueType(), InOp,
834                                                  ShiftAmt));
835       }
836     }
837
838     // Sign extension.  Compute the demanded bits in the result that are not
839     // present in the input.
840     APInt NewBits =
841       APInt::getHighBitsSet(BitWidth,
842                             BitWidth - ExVT.getScalarType().getSizeInBits());
843
844     // If none of the extended bits are demanded, eliminate the sextinreg.
845     if ((NewBits & NewMask) == 0)
846       return TLO.CombineTo(Op, Op.getOperand(0));
847
848     APInt InSignBit =
849       APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
850     APInt InputDemandedBits =
851       APInt::getLowBitsSet(BitWidth,
852                            ExVT.getScalarType().getSizeInBits()) &
853       NewMask;
854
855     // Since the sign extended bits are demanded, we know that the sign
856     // bit is demanded.
857     InputDemandedBits |= InSignBit;
858
859     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
860                              KnownZero, KnownOne, TLO, Depth+1))
861       return true;
862     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
863
864     // If the sign bit of the input is known set or clear, then we know the
865     // top bits of the result.
866
867     // If the input sign bit is known zero, convert this into a zero extension.
868     if (KnownZero.intersects(InSignBit))
869       return TLO.CombineTo(Op,
870                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
871
872     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
873       KnownOne |= NewBits;
874       KnownZero &= ~NewBits;
875     } else {                       // Input sign bit unknown
876       KnownZero &= ~NewBits;
877       KnownOne &= ~NewBits;
878     }
879     break;
880   }
881   case ISD::BUILD_PAIR: {
882     EVT HalfVT = Op.getOperand(0).getValueType();
883     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
884
885     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
886     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
887
888     APInt KnownZeroLo, KnownOneLo;
889     APInt KnownZeroHi, KnownOneHi;
890
891     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
892                              KnownOneLo, TLO, Depth + 1))
893       return true;
894
895     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
896                              KnownOneHi, TLO, Depth + 1))
897       return true;
898
899     KnownZero = KnownZeroLo.zext(BitWidth) |
900                 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
901
902     KnownOne = KnownOneLo.zext(BitWidth) |
903                KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
904     break;
905   }
906   case ISD::ZERO_EXTEND: {
907     unsigned OperandBitWidth =
908       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
909     APInt InMask = NewMask.trunc(OperandBitWidth);
910
911     // If none of the top bits are demanded, convert this into an any_extend.
912     APInt NewBits =
913       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
914     if (!NewBits.intersects(NewMask))
915       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
916                                                Op.getValueType(),
917                                                Op.getOperand(0)));
918
919     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
920                              KnownZero, KnownOne, TLO, Depth+1))
921       return true;
922     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
923     KnownZero = KnownZero.zext(BitWidth);
924     KnownOne = KnownOne.zext(BitWidth);
925     KnownZero |= NewBits;
926     break;
927   }
928   case ISD::SIGN_EXTEND: {
929     EVT InVT = Op.getOperand(0).getValueType();
930     unsigned InBits = InVT.getScalarType().getSizeInBits();
931     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
932     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
933     APInt NewBits   = ~InMask & NewMask;
934
935     // If none of the top bits are demanded, convert this into an any_extend.
936     if (NewBits == 0)
937       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
938                                               Op.getValueType(),
939                                               Op.getOperand(0)));
940
941     // Since some of the sign extended bits are demanded, we know that the sign
942     // bit is demanded.
943     APInt InDemandedBits = InMask & NewMask;
944     InDemandedBits |= InSignBit;
945     InDemandedBits = InDemandedBits.trunc(InBits);
946
947     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
948                              KnownOne, TLO, Depth+1))
949       return true;
950     KnownZero = KnownZero.zext(BitWidth);
951     KnownOne = KnownOne.zext(BitWidth);
952
953     // If the sign bit is known zero, convert this to a zero extend.
954     if (KnownZero.intersects(InSignBit))
955       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
956                                                Op.getValueType(),
957                                                Op.getOperand(0)));
958
959     // If the sign bit is known one, the top bits match.
960     if (KnownOne.intersects(InSignBit)) {
961       KnownOne |= NewBits;
962       assert((KnownZero & NewBits) == 0);
963     } else {   // Otherwise, top bits aren't known.
964       assert((KnownOne & NewBits) == 0);
965       assert((KnownZero & NewBits) == 0);
966     }
967     break;
968   }
969   case ISD::ANY_EXTEND: {
970     unsigned OperandBitWidth =
971       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
972     APInt InMask = NewMask.trunc(OperandBitWidth);
973     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
974                              KnownZero, KnownOne, TLO, Depth+1))
975       return true;
976     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
977     KnownZero = KnownZero.zext(BitWidth);
978     KnownOne = KnownOne.zext(BitWidth);
979     break;
980   }
981   case ISD::TRUNCATE: {
982     // Simplify the input, using demanded bit information, and compute the known
983     // zero/one bits live out.
984     unsigned OperandBitWidth =
985       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
986     APInt TruncMask = NewMask.zext(OperandBitWidth);
987     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
988                              KnownZero, KnownOne, TLO, Depth+1))
989       return true;
990     KnownZero = KnownZero.trunc(BitWidth);
991     KnownOne = KnownOne.trunc(BitWidth);
992
993     // If the input is only used by this truncate, see if we can shrink it based
994     // on the known demanded bits.
995     if (Op.getOperand(0).getNode()->hasOneUse()) {
996       SDValue In = Op.getOperand(0);
997       switch (In.getOpcode()) {
998       default: break;
999       case ISD::SRL:
1000         // Shrink SRL by a constant if none of the high bits shifted in are
1001         // demanded.
1002         if (TLO.LegalTypes() &&
1003             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1004           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1005           // undesirable.
1006           break;
1007         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1008         if (!ShAmt)
1009           break;
1010         SDValue Shift = In.getOperand(1);
1011         if (TLO.LegalTypes()) {
1012           uint64_t ShVal = ShAmt->getZExtValue();
1013           Shift =
1014             TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(Op.getValueType()));
1015         }
1016
1017         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1018                                                OperandBitWidth - BitWidth);
1019         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1020
1021         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1022           // None of the shifted in bits are needed.  Add a truncate of the
1023           // shift input, then shift it.
1024           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1025                                              Op.getValueType(),
1026                                              In.getOperand(0));
1027           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1028                                                    Op.getValueType(),
1029                                                    NewTrunc,
1030                                                    Shift));
1031         }
1032         break;
1033       }
1034     }
1035
1036     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037     break;
1038   }
1039   case ISD::AssertZext: {
1040     // AssertZext demands all of the high bits, plus any of the low bits
1041     // demanded by its users.
1042     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1043     APInt InMask = APInt::getLowBitsSet(BitWidth,
1044                                         VT.getSizeInBits());
1045     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1046                              KnownZero, KnownOne, TLO, Depth+1))
1047       return true;
1048     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049
1050     KnownZero |= ~InMask & NewMask;
1051     break;
1052   }
1053   case ISD::BITCAST:
1054     // If this is an FP->Int bitcast and if the sign bit is the only
1055     // thing demanded, turn this into a FGETSIGN.
1056     if (!TLO.LegalOperations() &&
1057         !Op.getValueType().isVector() &&
1058         !Op.getOperand(0).getValueType().isVector() &&
1059         NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1060         Op.getOperand(0).getValueType().isFloatingPoint()) {
1061       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1062       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1063       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
1064         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1065         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1066         // place.  We expect the SHL to be eliminated by other optimizations.
1067         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1068         unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1069         if (!OpVTLegal && OpVTSizeInBits > 32)
1070           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1071         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1072         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1073         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1074                                                  Op.getValueType(),
1075                                                  Sign, ShAmt));
1076       }
1077     }
1078     break;
1079   case ISD::ADD:
1080   case ISD::MUL:
1081   case ISD::SUB: {
1082     // Add, Sub, and Mul don't demand any bits in positions beyond that
1083     // of the highest bit demanded of them.
1084     APInt LoMask = APInt::getLowBitsSet(BitWidth,
1085                                         BitWidth - NewMask.countLeadingZeros());
1086     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1087                              KnownOne2, TLO, Depth+1))
1088       return true;
1089     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1090                              KnownOne2, TLO, Depth+1))
1091       return true;
1092     // See if the operation should be performed at a smaller bit width.
1093     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1094       return true;
1095   }
1096   // FALL THROUGH
1097   default:
1098     // Just use computeKnownBits to compute output bits.
1099     TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1100     break;
1101   }
1102
1103   // If we know the value of all of the demanded bits, return this as a
1104   // constant.
1105   if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1106     // Avoid folding to a constant if any OpaqueConstant is involved.
1107     const SDNode *N = Op.getNode();
1108     for (SDNodeIterator I = SDNodeIterator::begin(N),
1109          E = SDNodeIterator::end(N); I != E; ++I) {
1110       SDNode *Op = *I;
1111       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1112         if (C->isOpaque())
1113           return false;
1114     }
1115     return TLO.CombineTo(Op,
1116                          TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1117   }
1118
1119   return false;
1120 }
1121
1122 /// computeKnownBitsForTargetNode - Determine which of the bits specified
1123 /// in Mask are known to be either zero or one and return them in the
1124 /// KnownZero/KnownOne bitsets.
1125 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1126                                                    APInt &KnownZero,
1127                                                    APInt &KnownOne,
1128                                                    const SelectionDAG &DAG,
1129                                                    unsigned Depth) const {
1130   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1131           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1132           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1133           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1134          "Should use MaskedValueIsZero if you don't know whether Op"
1135          " is a target node!");
1136   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1137 }
1138
1139 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1140 /// targets that want to expose additional information about sign bits to the
1141 /// DAG Combiner.
1142 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1143                                                          const SelectionDAG &,
1144                                                          unsigned Depth) const {
1145   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1146           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1147           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1148           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1149          "Should use ComputeNumSignBits if you don't know whether Op"
1150          " is a target node!");
1151   return 1;
1152 }
1153
1154 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1155 /// one bit set. This differs from computeKnownBits in that it doesn't need to
1156 /// determine which bit is set.
1157 ///
1158 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1159   // A left-shift of a constant one will have exactly one bit set, because
1160   // shifting the bit off the end is undefined.
1161   if (Val.getOpcode() == ISD::SHL)
1162     if (ConstantSDNode *C =
1163          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1164       if (C->getAPIntValue() == 1)
1165         return true;
1166
1167   // Similarly, a right-shift of a constant sign-bit will have exactly
1168   // one bit set.
1169   if (Val.getOpcode() == ISD::SRL)
1170     if (ConstantSDNode *C =
1171          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1172       if (C->getAPIntValue().isSignBit())
1173         return true;
1174
1175   // More could be done here, though the above checks are enough
1176   // to handle some common cases.
1177
1178   // Fall back to computeKnownBits to catch other known cases.
1179   EVT OpVT = Val.getValueType();
1180   unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
1181   APInt KnownZero, KnownOne;
1182   DAG.computeKnownBits(Val, KnownZero, KnownOne);
1183   return (KnownZero.countPopulation() == BitWidth - 1) &&
1184          (KnownOne.countPopulation() == 1);
1185 }
1186
1187 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1188   if (!N)
1189     return false;
1190
1191   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1192   if (!CN) {
1193     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1194     if (!BV)
1195       return false;
1196
1197     BitVector UndefElements;
1198     CN = BV->getConstantSplatNode(&UndefElements);
1199     // Only interested in constant splats, and we don't try to handle undef
1200     // elements in identifying boolean constants.
1201     if (!CN || UndefElements.none())
1202       return false;
1203   }
1204
1205   switch (getBooleanContents(N->getValueType(0))) {
1206   case UndefinedBooleanContent:
1207     return CN->getAPIntValue()[0];
1208   case ZeroOrOneBooleanContent:
1209     return CN->isOne();
1210   case ZeroOrNegativeOneBooleanContent:
1211     return CN->isAllOnesValue();
1212   }
1213
1214   llvm_unreachable("Invalid boolean contents");
1215 }
1216
1217 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1218   if (!N)
1219     return false;
1220
1221   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1222   if (!CN) {
1223     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1224     if (!BV)
1225       return false;
1226
1227     BitVector UndefElements;
1228     CN = BV->getConstantSplatNode(&UndefElements);
1229     // Only interested in constant splats, and we don't try to handle undef
1230     // elements in identifying boolean constants.
1231     if (!CN || UndefElements.none())
1232       return false;
1233   }
1234
1235   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1236     return !CN->getAPIntValue()[0];
1237
1238   return CN->isNullValue();
1239 }
1240
1241 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1242 /// and cc. If it is unable to simplify it, return a null SDValue.
1243 SDValue
1244 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1245                               ISD::CondCode Cond, bool foldBooleans,
1246                               DAGCombinerInfo &DCI, SDLoc dl) const {
1247   SelectionDAG &DAG = DCI.DAG;
1248
1249   // These setcc operations always fold.
1250   switch (Cond) {
1251   default: break;
1252   case ISD::SETFALSE:
1253   case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1254   case ISD::SETTRUE:
1255   case ISD::SETTRUE2: {
1256     TargetLowering::BooleanContent Cnt =
1257         getBooleanContents(N0->getValueType(0));
1258     return DAG.getConstant(
1259         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1260         VT);
1261   }
1262   }
1263
1264   // Ensure that the constant occurs on the RHS, and fold constant
1265   // comparisons.
1266   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1267   if (isa<ConstantSDNode>(N0.getNode()) &&
1268       (DCI.isBeforeLegalizeOps() ||
1269        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1270     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1271
1272   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1273     const APInt &C1 = N1C->getAPIntValue();
1274
1275     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1276     // equality comparison, then we're just comparing whether X itself is
1277     // zero.
1278     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1279         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1280         N0.getOperand(1).getOpcode() == ISD::Constant) {
1281       const APInt &ShAmt
1282         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1283       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1284           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1285         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1286           // (srl (ctlz x), 5) == 0  -> X != 0
1287           // (srl (ctlz x), 5) != 1  -> X != 0
1288           Cond = ISD::SETNE;
1289         } else {
1290           // (srl (ctlz x), 5) != 0  -> X == 0
1291           // (srl (ctlz x), 5) == 1  -> X == 0
1292           Cond = ISD::SETEQ;
1293         }
1294         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1295         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1296                             Zero, Cond);
1297       }
1298     }
1299
1300     SDValue CTPOP = N0;
1301     // Look through truncs that don't change the value of a ctpop.
1302     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1303       CTPOP = N0.getOperand(0);
1304
1305     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1306         (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1307                         Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1308       EVT CTVT = CTPOP.getValueType();
1309       SDValue CTOp = CTPOP.getOperand(0);
1310
1311       // (ctpop x) u< 2 -> (x & x-1) == 0
1312       // (ctpop x) u> 1 -> (x & x-1) != 0
1313       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1314         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1315                                   DAG.getConstant(1, dl, CTVT));
1316         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1317         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1318         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1319       }
1320
1321       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1322     }
1323
1324     // (zext x) == C --> x == (trunc C)
1325     // (sext x) == C --> x == (trunc C)
1326     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1327         DCI.isBeforeLegalize() && N0->hasOneUse()) {
1328       unsigned MinBits = N0.getValueSizeInBits();
1329       SDValue PreExt;
1330       bool Signed = false;
1331       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1332         // ZExt
1333         MinBits = N0->getOperand(0).getValueSizeInBits();
1334         PreExt = N0->getOperand(0);
1335       } else if (N0->getOpcode() == ISD::AND) {
1336         // DAGCombine turns costly ZExts into ANDs
1337         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1338           if ((C->getAPIntValue()+1).isPowerOf2()) {
1339             MinBits = C->getAPIntValue().countTrailingOnes();
1340             PreExt = N0->getOperand(0);
1341           }
1342       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1343         // SExt
1344         MinBits = N0->getOperand(0).getValueSizeInBits();
1345         PreExt = N0->getOperand(0);
1346         Signed = true;
1347       } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
1348         // ZEXTLOAD / SEXTLOAD
1349         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1350           MinBits = LN0->getMemoryVT().getSizeInBits();
1351           PreExt = N0;
1352         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1353           Signed = true;
1354           MinBits = LN0->getMemoryVT().getSizeInBits();
1355           PreExt = N0;
1356         }
1357       }
1358
1359       // Figure out how many bits we need to preserve this constant.
1360       unsigned ReqdBits = Signed ?
1361         C1.getBitWidth() - C1.getNumSignBits() + 1 :
1362         C1.getActiveBits();
1363
1364       // Make sure we're not losing bits from the constant.
1365       if (MinBits > 0 &&
1366           MinBits < C1.getBitWidth() &&
1367           MinBits >= ReqdBits) {
1368         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1369         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1370           // Will get folded away.
1371           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1372           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1373           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1374         }
1375       }
1376     }
1377
1378     // If the LHS is '(and load, const)', the RHS is 0,
1379     // the test is for equality or unsigned, and all 1 bits of the const are
1380     // in the same partial word, see if we can shorten the load.
1381     if (DCI.isBeforeLegalize() &&
1382         !ISD::isSignedIntSetCC(Cond) &&
1383         N0.getOpcode() == ISD::AND && C1 == 0 &&
1384         N0.getNode()->hasOneUse() &&
1385         isa<LoadSDNode>(N0.getOperand(0)) &&
1386         N0.getOperand(0).getNode()->hasOneUse() &&
1387         isa<ConstantSDNode>(N0.getOperand(1))) {
1388       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1389       APInt bestMask;
1390       unsigned bestWidth = 0, bestOffset = 0;
1391       if (!Lod->isVolatile() && Lod->isUnindexed()) {
1392         unsigned origWidth = N0.getValueType().getSizeInBits();
1393         unsigned maskWidth = origWidth;
1394         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1395         // 8 bits, but have to be careful...
1396         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1397           origWidth = Lod->getMemoryVT().getSizeInBits();
1398         const APInt &Mask =
1399           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1400         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1401           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1402           for (unsigned offset=0; offset<origWidth/width; offset++) {
1403             if ((newMask & Mask) == Mask) {
1404               if (!DAG.getDataLayout().isLittleEndian())
1405                 bestOffset = (origWidth/width - offset - 1) * (width/8);
1406               else
1407                 bestOffset = (uint64_t)offset * (width/8);
1408               bestMask = Mask.lshr(offset * (width/8) * 8);
1409               bestWidth = width;
1410               break;
1411             }
1412             newMask = newMask << width;
1413           }
1414         }
1415       }
1416       if (bestWidth) {
1417         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1418         if (newVT.isRound()) {
1419           EVT PtrType = Lod->getOperand(1).getValueType();
1420           SDValue Ptr = Lod->getBasePtr();
1421           if (bestOffset != 0)
1422             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1423                               DAG.getConstant(bestOffset, dl, PtrType));
1424           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1425           SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
1426                                 Lod->getPointerInfo().getWithOffset(bestOffset),
1427                                         false, false, false, NewAlign);
1428           return DAG.getSetCC(dl, VT,
1429                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1430                                       DAG.getConstant(bestMask.trunc(bestWidth),
1431                                                       dl, newVT)),
1432                               DAG.getConstant(0LL, dl, newVT), Cond);
1433         }
1434       }
1435     }
1436
1437     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1438     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1439       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1440
1441       // If the comparison constant has bits in the upper part, the
1442       // zero-extended value could never match.
1443       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1444                                               C1.getBitWidth() - InSize))) {
1445         switch (Cond) {
1446         case ISD::SETUGT:
1447         case ISD::SETUGE:
1448         case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1449         case ISD::SETULT:
1450         case ISD::SETULE:
1451         case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1452         case ISD::SETGT:
1453         case ISD::SETGE:
1454           // True if the sign bit of C1 is set.
1455           return DAG.getConstant(C1.isNegative(), dl, VT);
1456         case ISD::SETLT:
1457         case ISD::SETLE:
1458           // True if the sign bit of C1 isn't set.
1459           return DAG.getConstant(C1.isNonNegative(), dl, VT);
1460         default:
1461           break;
1462         }
1463       }
1464
1465       // Otherwise, we can perform the comparison with the low bits.
1466       switch (Cond) {
1467       case ISD::SETEQ:
1468       case ISD::SETNE:
1469       case ISD::SETUGT:
1470       case ISD::SETUGE:
1471       case ISD::SETULT:
1472       case ISD::SETULE: {
1473         EVT newVT = N0.getOperand(0).getValueType();
1474         if (DCI.isBeforeLegalizeOps() ||
1475             (isOperationLegal(ISD::SETCC, newVT) &&
1476              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1477           EVT NewSetCCVT =
1478               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1479           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1480
1481           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1482                                           NewConst, Cond);
1483           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1484         }
1485         break;
1486       }
1487       default:
1488         break;   // todo, be more careful with signed comparisons
1489       }
1490     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1491                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1492       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1493       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1494       EVT ExtDstTy = N0.getValueType();
1495       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1496
1497       // If the constant doesn't fit into the number of bits for the source of
1498       // the sign extension, it is impossible for both sides to be equal.
1499       if (C1.getMinSignedBits() > ExtSrcTyBits)
1500         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1501
1502       SDValue ZextOp;
1503       EVT Op0Ty = N0.getOperand(0).getValueType();
1504       if (Op0Ty == ExtSrcTy) {
1505         ZextOp = N0.getOperand(0);
1506       } else {
1507         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1508         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1509                               DAG.getConstant(Imm, dl, Op0Ty));
1510       }
1511       if (!DCI.isCalledByLegalizer())
1512         DCI.AddToWorklist(ZextOp.getNode());
1513       // Otherwise, make this a use of a zext.
1514       return DAG.getSetCC(dl, VT, ZextOp,
1515                           DAG.getConstant(C1 & APInt::getLowBitsSet(
1516                                                               ExtDstTyBits,
1517                                                               ExtSrcTyBits),
1518                                           dl, ExtDstTy),
1519                           Cond);
1520     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1521                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1522       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1523       if (N0.getOpcode() == ISD::SETCC &&
1524           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1525         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1526         if (TrueWhenTrue)
1527           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1528         // Invert the condition.
1529         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1530         CC = ISD::getSetCCInverse(CC,
1531                                   N0.getOperand(0).getValueType().isInteger());
1532         if (DCI.isBeforeLegalizeOps() ||
1533             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1534           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1535       }
1536
1537       if ((N0.getOpcode() == ISD::XOR ||
1538            (N0.getOpcode() == ISD::AND &&
1539             N0.getOperand(0).getOpcode() == ISD::XOR &&
1540             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1541           isa<ConstantSDNode>(N0.getOperand(1)) &&
1542           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1543         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1544         // can only do this if the top bits are known zero.
1545         unsigned BitWidth = N0.getValueSizeInBits();
1546         if (DAG.MaskedValueIsZero(N0,
1547                                   APInt::getHighBitsSet(BitWidth,
1548                                                         BitWidth-1))) {
1549           // Okay, get the un-inverted input value.
1550           SDValue Val;
1551           if (N0.getOpcode() == ISD::XOR)
1552             Val = N0.getOperand(0);
1553           else {
1554             assert(N0.getOpcode() == ISD::AND &&
1555                     N0.getOperand(0).getOpcode() == ISD::XOR);
1556             // ((X^1)&1)^1 -> X & 1
1557             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1558                               N0.getOperand(0).getOperand(0),
1559                               N0.getOperand(1));
1560           }
1561
1562           return DAG.getSetCC(dl, VT, Val, N1,
1563                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1564         }
1565       } else if (N1C->getAPIntValue() == 1 &&
1566                  (VT == MVT::i1 ||
1567                   getBooleanContents(N0->getValueType(0)) ==
1568                       ZeroOrOneBooleanContent)) {
1569         SDValue Op0 = N0;
1570         if (Op0.getOpcode() == ISD::TRUNCATE)
1571           Op0 = Op0.getOperand(0);
1572
1573         if ((Op0.getOpcode() == ISD::XOR) &&
1574             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1575             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1576           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1577           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1578           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1579                               Cond);
1580         }
1581         if (Op0.getOpcode() == ISD::AND &&
1582             isa<ConstantSDNode>(Op0.getOperand(1)) &&
1583             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1584           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1585           if (Op0.getValueType().bitsGT(VT))
1586             Op0 = DAG.getNode(ISD::AND, dl, VT,
1587                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1588                           DAG.getConstant(1, dl, VT));
1589           else if (Op0.getValueType().bitsLT(VT))
1590             Op0 = DAG.getNode(ISD::AND, dl, VT,
1591                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1592                         DAG.getConstant(1, dl, VT));
1593
1594           return DAG.getSetCC(dl, VT, Op0,
1595                               DAG.getConstant(0, dl, Op0.getValueType()),
1596                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1597         }
1598         if (Op0.getOpcode() == ISD::AssertZext &&
1599             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1600           return DAG.getSetCC(dl, VT, Op0,
1601                               DAG.getConstant(0, dl, Op0.getValueType()),
1602                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1603       }
1604     }
1605
1606     APInt MinVal, MaxVal;
1607     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1608     if (ISD::isSignedIntSetCC(Cond)) {
1609       MinVal = APInt::getSignedMinValue(OperandBitSize);
1610       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1611     } else {
1612       MinVal = APInt::getMinValue(OperandBitSize);
1613       MaxVal = APInt::getMaxValue(OperandBitSize);
1614     }
1615
1616     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1617     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1618       if (C1 == MinVal) return DAG.getConstant(1, dl, VT);  // X >= MIN --> true
1619       // X >= C0 --> X > (C0 - 1)
1620       APInt C = C1 - 1;
1621       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1622       if ((DCI.isBeforeLegalizeOps() ||
1623            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1624           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1625                                 isLegalICmpImmediate(C.getSExtValue())))) {
1626         return DAG.getSetCC(dl, VT, N0,
1627                             DAG.getConstant(C, dl, N1.getValueType()),
1628                             NewCC);
1629       }
1630     }
1631
1632     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1633       if (C1 == MaxVal) return DAG.getConstant(1, dl, VT);  // X <= MAX --> true
1634       // X <= C0 --> X < (C0 + 1)
1635       APInt C = C1 + 1;
1636       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1637       if ((DCI.isBeforeLegalizeOps() ||
1638            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1639           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1640                                 isLegalICmpImmediate(C.getSExtValue())))) {
1641         return DAG.getSetCC(dl, VT, N0,
1642                             DAG.getConstant(C, dl, N1.getValueType()),
1643                             NewCC);
1644       }
1645     }
1646
1647     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1648       return DAG.getConstant(0, dl, VT);      // X < MIN --> false
1649     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1650       return DAG.getConstant(1, dl, VT);      // X >= MIN --> true
1651     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1652       return DAG.getConstant(0, dl, VT);      // X > MAX --> false
1653     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1654       return DAG.getConstant(1, dl, VT);      // X <= MAX --> true
1655
1656     // Canonicalize setgt X, Min --> setne X, Min
1657     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1658       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1659     // Canonicalize setlt X, Max --> setne X, Max
1660     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1661       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1662
1663     // If we have setult X, 1, turn it into seteq X, 0
1664     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1665       return DAG.getSetCC(dl, VT, N0,
1666                           DAG.getConstant(MinVal, dl, N0.getValueType()),
1667                           ISD::SETEQ);
1668     // If we have setugt X, Max-1, turn it into seteq X, Max
1669     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1670       return DAG.getSetCC(dl, VT, N0,
1671                           DAG.getConstant(MaxVal, dl, N0.getValueType()),
1672                           ISD::SETEQ);
1673
1674     // If we have "setcc X, C0", check to see if we can shrink the immediate
1675     // by changing cc.
1676
1677     // SETUGT X, SINTMAX  -> SETLT X, 0
1678     if (Cond == ISD::SETUGT &&
1679         C1 == APInt::getSignedMaxValue(OperandBitSize))
1680       return DAG.getSetCC(dl, VT, N0,
1681                           DAG.getConstant(0, dl, N1.getValueType()),
1682                           ISD::SETLT);
1683
1684     // SETULT X, SINTMIN  -> SETGT X, -1
1685     if (Cond == ISD::SETULT &&
1686         C1 == APInt::getSignedMinValue(OperandBitSize)) {
1687       SDValue ConstMinusOne =
1688           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
1689                           N1.getValueType());
1690       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1691     }
1692
1693     // Fold bit comparisons when we can.
1694     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1695         (VT == N0.getValueType() ||
1696          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1697         N0.getOpcode() == ISD::AND) {
1698       auto &DL = DAG.getDataLayout();
1699       if (ConstantSDNode *AndRHS =
1700                   dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1701         EVT ShiftTy = DCI.isBeforeLegalize()
1702                           ? getPointerTy(DL)
1703                           : getShiftAmountTy(N0.getValueType());
1704         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1705           // Perform the xform if the AND RHS is a single bit.
1706           if (AndRHS->getAPIntValue().isPowerOf2()) {
1707             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1708                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1709                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1710                                    ShiftTy)));
1711           }
1712         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1713           // (X & 8) == 8  -->  (X & 8) >> 3
1714           // Perform the xform if C1 is a single bit.
1715           if (C1.isPowerOf2()) {
1716             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1717                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1718                                       DAG.getConstant(C1.logBase2(), dl,
1719                                                       ShiftTy)));
1720           }
1721         }
1722       }
1723     }
1724
1725     if (C1.getMinSignedBits() <= 64 &&
1726         !isLegalICmpImmediate(C1.getSExtValue())) {
1727       // (X & -256) == 256 -> (X >> 8) == 1
1728       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1729           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
1730         if (ConstantSDNode *AndRHS =
1731             dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1732           const APInt &AndRHSC = AndRHS->getAPIntValue();
1733           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1734             unsigned ShiftBits = AndRHSC.countTrailingZeros();
1735             auto &DL = DAG.getDataLayout();
1736             EVT ShiftTy = DCI.isBeforeLegalize()
1737                               ? getPointerTy(DL)
1738                               : getShiftAmountTy(N0.getValueType());
1739             EVT CmpTy = N0.getValueType();
1740             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
1741                                         DAG.getConstant(ShiftBits, dl,
1742                                                         ShiftTy));
1743             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
1744             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1745           }
1746         }
1747       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1748                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1749         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1750         // X <  0x100000000 -> (X >> 32) <  1
1751         // X >= 0x100000000 -> (X >> 32) >= 1
1752         // X <= 0x0ffffffff -> (X >> 32) <  1
1753         // X >  0x0ffffffff -> (X >> 32) >= 1
1754         unsigned ShiftBits;
1755         APInt NewC = C1;
1756         ISD::CondCode NewCond = Cond;
1757         if (AdjOne) {
1758           ShiftBits = C1.countTrailingOnes();
1759           NewC = NewC + 1;
1760           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1761         } else {
1762           ShiftBits = C1.countTrailingZeros();
1763         }
1764         NewC = NewC.lshr(ShiftBits);
1765         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1766           isLegalICmpImmediate(NewC.getSExtValue())) {
1767           auto &DL = DAG.getDataLayout();
1768           EVT ShiftTy = DCI.isBeforeLegalize()
1769                             ? getPointerTy(DL)
1770                             : getShiftAmountTy(N0.getValueType());
1771           EVT CmpTy = N0.getValueType();
1772           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
1773                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
1774           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
1775           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1776         }
1777       }
1778     }
1779   }
1780
1781   if (isa<ConstantFPSDNode>(N0.getNode())) {
1782     // Constant fold or commute setcc.
1783     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1784     if (O.getNode()) return O;
1785   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1786     // If the RHS of an FP comparison is a constant, simplify it away in
1787     // some cases.
1788     if (CFP->getValueAPF().isNaN()) {
1789       // If an operand is known to be a nan, we can fold it.
1790       switch (ISD::getUnorderedFlavor(Cond)) {
1791       default: llvm_unreachable("Unknown flavor!");
1792       case 0:  // Known false.
1793         return DAG.getConstant(0, dl, VT);
1794       case 1:  // Known true.
1795         return DAG.getConstant(1, dl, VT);
1796       case 2:  // Undefined.
1797         return DAG.getUNDEF(VT);
1798       }
1799     }
1800
1801     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
1802     // constant if knowing that the operand is non-nan is enough.  We prefer to
1803     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1804     // materialize 0.0.
1805     if (Cond == ISD::SETO || Cond == ISD::SETUO)
1806       return DAG.getSetCC(dl, VT, N0, N0, Cond);
1807
1808     // If the condition is not legal, see if we can find an equivalent one
1809     // which is legal.
1810     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1811       // If the comparison was an awkward floating-point == or != and one of
1812       // the comparison operands is infinity or negative infinity, convert the
1813       // condition to a less-awkward <= or >=.
1814       if (CFP->getValueAPF().isInfinity()) {
1815         if (CFP->getValueAPF().isNegative()) {
1816           if (Cond == ISD::SETOEQ &&
1817               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1818             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1819           if (Cond == ISD::SETUEQ &&
1820               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1821             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1822           if (Cond == ISD::SETUNE &&
1823               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1824             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1825           if (Cond == ISD::SETONE &&
1826               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1827             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1828         } else {
1829           if (Cond == ISD::SETOEQ &&
1830               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1831             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1832           if (Cond == ISD::SETUEQ &&
1833               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1834             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1835           if (Cond == ISD::SETUNE &&
1836               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1837             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1838           if (Cond == ISD::SETONE &&
1839               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1840             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1841         }
1842       }
1843     }
1844   }
1845
1846   if (N0 == N1) {
1847     // The sext(setcc()) => setcc() optimization relies on the appropriate
1848     // constant being emitted.
1849     uint64_t EqVal = 0;
1850     switch (getBooleanContents(N0.getValueType())) {
1851     case UndefinedBooleanContent:
1852     case ZeroOrOneBooleanContent:
1853       EqVal = ISD::isTrueWhenEqual(Cond);
1854       break;
1855     case ZeroOrNegativeOneBooleanContent:
1856       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1857       break;
1858     }
1859
1860     // We can always fold X == X for integer setcc's.
1861     if (N0.getValueType().isInteger()) {
1862       return DAG.getConstant(EqVal, dl, VT);
1863     }
1864     unsigned UOF = ISD::getUnorderedFlavor(Cond);
1865     if (UOF == 2)   // FP operators that are undefined on NaNs.
1866       return DAG.getConstant(EqVal, dl, VT);
1867     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1868       return DAG.getConstant(EqVal, dl, VT);
1869     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
1870     // if it is not already.
1871     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1872     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
1873           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
1874       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
1875   }
1876
1877   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1878       N0.getValueType().isInteger()) {
1879     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1880         N0.getOpcode() == ISD::XOR) {
1881       // Simplify (X+Y) == (X+Z) -->  Y == Z
1882       if (N0.getOpcode() == N1.getOpcode()) {
1883         if (N0.getOperand(0) == N1.getOperand(0))
1884           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
1885         if (N0.getOperand(1) == N1.getOperand(1))
1886           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
1887         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1888           // If X op Y == Y op X, try other combinations.
1889           if (N0.getOperand(0) == N1.getOperand(1))
1890             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
1891                                 Cond);
1892           if (N0.getOperand(1) == N1.getOperand(0))
1893             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
1894                                 Cond);
1895         }
1896       }
1897
1898       // If RHS is a legal immediate value for a compare instruction, we need
1899       // to be careful about increasing register pressure needlessly.
1900       bool LegalRHSImm = false;
1901
1902       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1903         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1904           // Turn (X+C1) == C2 --> X == C2-C1
1905           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
1906             return DAG.getSetCC(dl, VT, N0.getOperand(0),
1907                                 DAG.getConstant(RHSC->getAPIntValue()-
1908                                                 LHSR->getAPIntValue(),
1909                                 dl, N0.getValueType()), Cond);
1910           }
1911
1912           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1913           if (N0.getOpcode() == ISD::XOR)
1914             // If we know that all of the inverted bits are zero, don't bother
1915             // performing the inversion.
1916             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1917               return
1918                 DAG.getSetCC(dl, VT, N0.getOperand(0),
1919                              DAG.getConstant(LHSR->getAPIntValue() ^
1920                                                RHSC->getAPIntValue(),
1921                                              dl, N0.getValueType()),
1922                              Cond);
1923         }
1924
1925         // Turn (C1-X) == C2 --> X == C1-C2
1926         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1927           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
1928             return
1929               DAG.getSetCC(dl, VT, N0.getOperand(1),
1930                            DAG.getConstant(SUBC->getAPIntValue() -
1931                                              RHSC->getAPIntValue(),
1932                                            dl, N0.getValueType()),
1933                            Cond);
1934           }
1935         }
1936
1937         // Could RHSC fold directly into a compare?
1938         if (RHSC->getValueType(0).getSizeInBits() <= 64)
1939           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
1940       }
1941
1942       // Simplify (X+Z) == X -->  Z == 0
1943       // Don't do this if X is an immediate that can fold into a cmp
1944       // instruction and X+Z has other uses. It could be an induction variable
1945       // chain, and the transform would increase register pressure.
1946       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
1947         if (N0.getOperand(0) == N1)
1948           return DAG.getSetCC(dl, VT, N0.getOperand(1),
1949                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
1950         if (N0.getOperand(1) == N1) {
1951           if (DAG.isCommutativeBinOp(N0.getOpcode()))
1952             return DAG.getSetCC(dl, VT, N0.getOperand(0),
1953                                 DAG.getConstant(0, dl, N0.getValueType()),
1954                                 Cond);
1955           if (N0.getNode()->hasOneUse()) {
1956             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1957             // (Z-X) == X  --> Z == X<<1
1958             SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
1959                        DAG.getConstant(1, dl,
1960                                        getShiftAmountTy(N1.getValueType())));
1961             if (!DCI.isCalledByLegalizer())
1962               DCI.AddToWorklist(SH.getNode());
1963             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
1964           }
1965         }
1966       }
1967     }
1968
1969     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1970         N1.getOpcode() == ISD::XOR) {
1971       // Simplify  X == (X+Z) -->  Z == 0
1972       if (N1.getOperand(0) == N0)
1973         return DAG.getSetCC(dl, VT, N1.getOperand(1),
1974                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
1975       if (N1.getOperand(1) == N0) {
1976         if (DAG.isCommutativeBinOp(N1.getOpcode()))
1977           return DAG.getSetCC(dl, VT, N1.getOperand(0),
1978                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
1979         if (N1.getNode()->hasOneUse()) {
1980           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1981           // X == (Z-X)  --> X<<1 == Z
1982           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
1983                        DAG.getConstant(1, dl,
1984                                        getShiftAmountTy(N0.getValueType())));
1985           if (!DCI.isCalledByLegalizer())
1986             DCI.AddToWorklist(SH.getNode());
1987           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
1988         }
1989       }
1990     }
1991
1992     // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
1993     // Note that where y is variable and is known to have at most
1994     // one bit set (for example, if it is z&1) we cannot do this;
1995     // the expressions are not equivalent when y==0.
1996     if (N0.getOpcode() == ISD::AND)
1997       if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
1998         if (ValueHasExactlyOneBitSet(N1, DAG)) {
1999           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2000           if (DCI.isBeforeLegalizeOps() ||
2001               isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2002             SDValue Zero = DAG.getConstant(0, dl, N1.getValueType());
2003             return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2004           }
2005         }
2006       }
2007     if (N1.getOpcode() == ISD::AND)
2008       if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
2009         if (ValueHasExactlyOneBitSet(N0, DAG)) {
2010           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2011           if (DCI.isBeforeLegalizeOps() ||
2012               isCondCodeLegal(Cond, N1.getSimpleValueType())) {
2013             SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
2014             return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2015           }
2016         }
2017       }
2018   }
2019
2020   // Fold away ALL boolean setcc's.
2021   SDValue Temp;
2022   if (N0.getValueType() == MVT::i1 && foldBooleans) {
2023     switch (Cond) {
2024     default: llvm_unreachable("Unknown integer setcc!");
2025     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2026       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2027       N0 = DAG.getNOT(dl, Temp, MVT::i1);
2028       if (!DCI.isCalledByLegalizer())
2029         DCI.AddToWorklist(Temp.getNode());
2030       break;
2031     case ISD::SETNE:  // X != Y   -->  (X^Y)
2032       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2033       break;
2034     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2035     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2036       Temp = DAG.getNOT(dl, N0, MVT::i1);
2037       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2038       if (!DCI.isCalledByLegalizer())
2039         DCI.AddToWorklist(Temp.getNode());
2040       break;
2041     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2042     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2043       Temp = DAG.getNOT(dl, N1, MVT::i1);
2044       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2045       if (!DCI.isCalledByLegalizer())
2046         DCI.AddToWorklist(Temp.getNode());
2047       break;
2048     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2049     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2050       Temp = DAG.getNOT(dl, N0, MVT::i1);
2051       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2052       if (!DCI.isCalledByLegalizer())
2053         DCI.AddToWorklist(Temp.getNode());
2054       break;
2055     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2056     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2057       Temp = DAG.getNOT(dl, N1, MVT::i1);
2058       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2059       break;
2060     }
2061     if (VT != MVT::i1) {
2062       if (!DCI.isCalledByLegalizer())
2063         DCI.AddToWorklist(N0.getNode());
2064       // FIXME: If running after legalize, we probably can't do this.
2065       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2066     }
2067     return N0;
2068   }
2069
2070   // Could not fold it.
2071   return SDValue();
2072 }
2073
2074 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
2075 /// node is a GlobalAddress + offset.
2076 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2077                                     int64_t &Offset) const {
2078   if (isa<GlobalAddressSDNode>(N)) {
2079     GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
2080     GA = GASD->getGlobal();
2081     Offset += GASD->getOffset();
2082     return true;
2083   }
2084
2085   if (N->getOpcode() == ISD::ADD) {
2086     SDValue N1 = N->getOperand(0);
2087     SDValue N2 = N->getOperand(1);
2088     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2089       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
2090       if (V) {
2091         Offset += V->getSExtValue();
2092         return true;
2093       }
2094     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2095       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
2096       if (V) {
2097         Offset += V->getSExtValue();
2098         return true;
2099       }
2100     }
2101   }
2102
2103   return false;
2104 }
2105
2106
2107 SDValue TargetLowering::
2108 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
2109   // Default implementation: no optimization.
2110   return SDValue();
2111 }
2112
2113 //===----------------------------------------------------------------------===//
2114 //  Inline Assembler Implementation Methods
2115 //===----------------------------------------------------------------------===//
2116
2117 TargetLowering::ConstraintType
2118 TargetLowering::getConstraintType(StringRef Constraint) const {
2119   unsigned S = Constraint.size();
2120
2121   if (S == 1) {
2122     switch (Constraint[0]) {
2123     default: break;
2124     case 'r': return C_RegisterClass;
2125     case 'm':    // memory
2126     case 'o':    // offsetable
2127     case 'V':    // not offsetable
2128       return C_Memory;
2129     case 'i':    // Simple Integer or Relocatable Constant
2130     case 'n':    // Simple Integer
2131     case 'E':    // Floating Point Constant
2132     case 'F':    // Floating Point Constant
2133     case 's':    // Relocatable Constant
2134     case 'p':    // Address.
2135     case 'X':    // Allow ANY value.
2136     case 'I':    // Target registers.
2137     case 'J':
2138     case 'K':
2139     case 'L':
2140     case 'M':
2141     case 'N':
2142     case 'O':
2143     case 'P':
2144     case '<':
2145     case '>':
2146       return C_Other;
2147     }
2148   }
2149
2150   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2151     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2152       return C_Memory;
2153     return C_Register;
2154   }
2155   return C_Unknown;
2156 }
2157
2158 /// LowerXConstraint - try to replace an X constraint, which matches anything,
2159 /// with another that has more specific requirements based on the type of the
2160 /// corresponding operand.
2161 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2162   if (ConstraintVT.isInteger())
2163     return "r";
2164   if (ConstraintVT.isFloatingPoint())
2165     return "f";      // works for many targets
2166   return nullptr;
2167 }
2168
2169 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2170 /// vector.  If it is invalid, don't add anything to Ops.
2171 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2172                                                   std::string &Constraint,
2173                                                   std::vector<SDValue> &Ops,
2174                                                   SelectionDAG &DAG) const {
2175
2176   if (Constraint.length() > 1) return;
2177
2178   char ConstraintLetter = Constraint[0];
2179   switch (ConstraintLetter) {
2180   default: break;
2181   case 'X':     // Allows any operand; labels (basic block) use this.
2182     if (Op.getOpcode() == ISD::BasicBlock) {
2183       Ops.push_back(Op);
2184       return;
2185     }
2186     // fall through
2187   case 'i':    // Simple Integer or Relocatable Constant
2188   case 'n':    // Simple Integer
2189   case 's': {  // Relocatable Constant
2190     // These operands are interested in values of the form (GV+C), where C may
2191     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2192     // is possible and fine if either GV or C are missing.
2193     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2194     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2195
2196     // If we have "(add GV, C)", pull out GV/C
2197     if (Op.getOpcode() == ISD::ADD) {
2198       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2199       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2200       if (!C || !GA) {
2201         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2202         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2203       }
2204       if (!C || !GA)
2205         C = nullptr, GA = nullptr;
2206     }
2207
2208     // If we find a valid operand, map to the TargetXXX version so that the
2209     // value itself doesn't get selected.
2210     if (GA) {   // Either &GV   or   &GV+C
2211       if (ConstraintLetter != 'n') {
2212         int64_t Offs = GA->getOffset();
2213         if (C) Offs += C->getZExtValue();
2214         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2215                                                  C ? SDLoc(C) : SDLoc(),
2216                                                  Op.getValueType(), Offs));
2217         return;
2218       }
2219     }
2220     if (C) {   // just C, no GV.
2221       // Simple constants are not allowed for 's'.
2222       if (ConstraintLetter != 's') {
2223         // gcc prints these as sign extended.  Sign extend value to 64 bits
2224         // now; without this it would get ZExt'd later in
2225         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2226         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2227                                             SDLoc(C), MVT::i64));
2228         return;
2229       }
2230     }
2231     break;
2232   }
2233   }
2234 }
2235
2236 std::pair<unsigned, const TargetRegisterClass *>
2237 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2238                                              StringRef Constraint,
2239                                              MVT VT) const {
2240   if (Constraint.empty() || Constraint[0] != '{')
2241     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2242   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2243
2244   // Remove the braces from around the name.
2245   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2246
2247   std::pair<unsigned, const TargetRegisterClass*> R =
2248     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2249
2250   // Figure out which register class contains this reg.
2251   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2252        E = RI->regclass_end(); RCI != E; ++RCI) {
2253     const TargetRegisterClass *RC = *RCI;
2254
2255     // If none of the value types for this register class are valid, we
2256     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2257     if (!isLegalRC(RC))
2258       continue;
2259
2260     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2261          I != E; ++I) {
2262       if (RegName.equals_lower(RI->getName(*I))) {
2263         std::pair<unsigned, const TargetRegisterClass*> S =
2264           std::make_pair(*I, RC);
2265
2266         // If this register class has the requested value type, return it,
2267         // otherwise keep searching and return the first class found
2268         // if no other is found which explicitly has the requested type.
2269         if (RC->hasType(VT))
2270           return S;
2271         else if (!R.second)
2272           R = S;
2273       }
2274     }
2275   }
2276
2277   return R;
2278 }
2279
2280 //===----------------------------------------------------------------------===//
2281 // Constraint Selection.
2282
2283 /// isMatchingInputConstraint - Return true of this is an input operand that is
2284 /// a matching constraint like "4".
2285 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2286   assert(!ConstraintCode.empty() && "No known constraint!");
2287   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2288 }
2289
2290 /// getMatchedOperand - If this is an input matching constraint, this method
2291 /// returns the output operand it matches.
2292 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2293   assert(!ConstraintCode.empty() && "No known constraint!");
2294   return atoi(ConstraintCode.c_str());
2295 }
2296
2297
2298 /// ParseConstraints - Split up the constraint string from the inline
2299 /// assembly value into the specific constraints and their prefixes,
2300 /// and also tie in the associated operand values.
2301 /// If this returns an empty vector, and if the constraint string itself
2302 /// isn't empty, there was an error parsing.
2303 TargetLowering::AsmOperandInfoVector
2304 TargetLowering::ParseConstraints(const DataLayout &DL,
2305                                  const TargetRegisterInfo *TRI,
2306                                  ImmutableCallSite CS) const {
2307   /// ConstraintOperands - Information about all of the constraints.
2308   AsmOperandInfoVector ConstraintOperands;
2309   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2310   unsigned maCount = 0; // Largest number of multiple alternative constraints.
2311
2312   // Do a prepass over the constraints, canonicalizing them, and building up the
2313   // ConstraintOperands list.
2314   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2315   unsigned ResNo = 0;   // ResNo - The result number of the next output.
2316
2317   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2318     ConstraintOperands.emplace_back(std::move(CI));
2319     AsmOperandInfo &OpInfo = ConstraintOperands.back();
2320
2321     // Update multiple alternative constraint count.
2322     if (OpInfo.multipleAlternatives.size() > maCount)
2323       maCount = OpInfo.multipleAlternatives.size();
2324
2325     OpInfo.ConstraintVT = MVT::Other;
2326
2327     // Compute the value type for each operand.
2328     switch (OpInfo.Type) {
2329     case InlineAsm::isOutput:
2330       // Indirect outputs just consume an argument.
2331       if (OpInfo.isIndirect) {
2332         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2333         break;
2334       }
2335
2336       // The return value of the call is this value.  As such, there is no
2337       // corresponding argument.
2338       assert(!CS.getType()->isVoidTy() &&
2339              "Bad inline asm!");
2340       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2341         OpInfo.ConstraintVT =
2342             getSimpleValueType(DL, STy->getElementType(ResNo));
2343       } else {
2344         assert(ResNo == 0 && "Asm only has one result!");
2345         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2346       }
2347       ++ResNo;
2348       break;
2349     case InlineAsm::isInput:
2350       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2351       break;
2352     case InlineAsm::isClobber:
2353       // Nothing to do.
2354       break;
2355     }
2356
2357     if (OpInfo.CallOperandVal) {
2358       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2359       if (OpInfo.isIndirect) {
2360         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2361         if (!PtrTy)
2362           report_fatal_error("Indirect operand for inline asm not a pointer!");
2363         OpTy = PtrTy->getElementType();
2364       }
2365
2366       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2367       if (StructType *STy = dyn_cast<StructType>(OpTy))
2368         if (STy->getNumElements() == 1)
2369           OpTy = STy->getElementType(0);
2370
2371       // If OpTy is not a single value, it may be a struct/union that we
2372       // can tile with integers.
2373       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2374         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2375         switch (BitSize) {
2376         default: break;
2377         case 1:
2378         case 8:
2379         case 16:
2380         case 32:
2381         case 64:
2382         case 128:
2383           OpInfo.ConstraintVT =
2384             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2385           break;
2386         }
2387       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2388         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2389         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2390       } else {
2391         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2392       }
2393     }
2394   }
2395
2396   // If we have multiple alternative constraints, select the best alternative.
2397   if (!ConstraintOperands.empty()) {
2398     if (maCount) {
2399       unsigned bestMAIndex = 0;
2400       int bestWeight = -1;
2401       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2402       int weight = -1;
2403       unsigned maIndex;
2404       // Compute the sums of the weights for each alternative, keeping track
2405       // of the best (highest weight) one so far.
2406       for (maIndex = 0; maIndex < maCount; ++maIndex) {
2407         int weightSum = 0;
2408         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2409             cIndex != eIndex; ++cIndex) {
2410           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2411           if (OpInfo.Type == InlineAsm::isClobber)
2412             continue;
2413
2414           // If this is an output operand with a matching input operand,
2415           // look up the matching input. If their types mismatch, e.g. one
2416           // is an integer, the other is floating point, or their sizes are
2417           // different, flag it as an maCantMatch.
2418           if (OpInfo.hasMatchingInput()) {
2419             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2420             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2421               if ((OpInfo.ConstraintVT.isInteger() !=
2422                    Input.ConstraintVT.isInteger()) ||
2423                   (OpInfo.ConstraintVT.getSizeInBits() !=
2424                    Input.ConstraintVT.getSizeInBits())) {
2425                 weightSum = -1;  // Can't match.
2426                 break;
2427               }
2428             }
2429           }
2430           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2431           if (weight == -1) {
2432             weightSum = -1;
2433             break;
2434           }
2435           weightSum += weight;
2436         }
2437         // Update best.
2438         if (weightSum > bestWeight) {
2439           bestWeight = weightSum;
2440           bestMAIndex = maIndex;
2441         }
2442       }
2443
2444       // Now select chosen alternative in each constraint.
2445       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2446           cIndex != eIndex; ++cIndex) {
2447         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2448         if (cInfo.Type == InlineAsm::isClobber)
2449           continue;
2450         cInfo.selectAlternative(bestMAIndex);
2451       }
2452     }
2453   }
2454
2455   // Check and hook up tied operands, choose constraint code to use.
2456   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2457       cIndex != eIndex; ++cIndex) {
2458     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2459
2460     // If this is an output operand with a matching input operand, look up the
2461     // matching input. If their types mismatch, e.g. one is an integer, the
2462     // other is floating point, or their sizes are different, flag it as an
2463     // error.
2464     if (OpInfo.hasMatchingInput()) {
2465       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2466
2467       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2468         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2469             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2470                                          OpInfo.ConstraintVT);
2471         std::pair<unsigned, const TargetRegisterClass *> InputRC =
2472             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2473                                          Input.ConstraintVT);
2474         if ((OpInfo.ConstraintVT.isInteger() !=
2475              Input.ConstraintVT.isInteger()) ||
2476             (MatchRC.second != InputRC.second)) {
2477           report_fatal_error("Unsupported asm: input constraint"
2478                              " with a matching output constraint of"
2479                              " incompatible type!");
2480         }
2481       }
2482
2483     }
2484   }
2485
2486   return ConstraintOperands;
2487 }
2488
2489
2490 /// getConstraintGenerality - Return an integer indicating how general CT
2491 /// is.
2492 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2493   switch (CT) {
2494   case TargetLowering::C_Other:
2495   case TargetLowering::C_Unknown:
2496     return 0;
2497   case TargetLowering::C_Register:
2498     return 1;
2499   case TargetLowering::C_RegisterClass:
2500     return 2;
2501   case TargetLowering::C_Memory:
2502     return 3;
2503   }
2504   llvm_unreachable("Invalid constraint type");
2505 }
2506
2507 /// Examine constraint type and operand type and determine a weight value.
2508 /// This object must already have been set up with the operand type
2509 /// and the current alternative constraint selected.
2510 TargetLowering::ConstraintWeight
2511   TargetLowering::getMultipleConstraintMatchWeight(
2512     AsmOperandInfo &info, int maIndex) const {
2513   InlineAsm::ConstraintCodeVector *rCodes;
2514   if (maIndex >= (int)info.multipleAlternatives.size())
2515     rCodes = &info.Codes;
2516   else
2517     rCodes = &info.multipleAlternatives[maIndex].Codes;
2518   ConstraintWeight BestWeight = CW_Invalid;
2519
2520   // Loop over the options, keeping track of the most general one.
2521   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2522     ConstraintWeight weight =
2523       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2524     if (weight > BestWeight)
2525       BestWeight = weight;
2526   }
2527
2528   return BestWeight;
2529 }
2530
2531 /// Examine constraint type and operand type and determine a weight value.
2532 /// This object must already have been set up with the operand type
2533 /// and the current alternative constraint selected.
2534 TargetLowering::ConstraintWeight
2535   TargetLowering::getSingleConstraintMatchWeight(
2536     AsmOperandInfo &info, const char *constraint) const {
2537   ConstraintWeight weight = CW_Invalid;
2538   Value *CallOperandVal = info.CallOperandVal;
2539     // If we don't have a value, we can't do a match,
2540     // but allow it at the lowest weight.
2541   if (!CallOperandVal)
2542     return CW_Default;
2543   // Look at the constraint type.
2544   switch (*constraint) {
2545     case 'i': // immediate integer.
2546     case 'n': // immediate integer with a known value.
2547       if (isa<ConstantInt>(CallOperandVal))
2548         weight = CW_Constant;
2549       break;
2550     case 's': // non-explicit intregal immediate.
2551       if (isa<GlobalValue>(CallOperandVal))
2552         weight = CW_Constant;
2553       break;
2554     case 'E': // immediate float if host format.
2555     case 'F': // immediate float.
2556       if (isa<ConstantFP>(CallOperandVal))
2557         weight = CW_Constant;
2558       break;
2559     case '<': // memory operand with autodecrement.
2560     case '>': // memory operand with autoincrement.
2561     case 'm': // memory operand.
2562     case 'o': // offsettable memory operand
2563     case 'V': // non-offsettable memory operand
2564       weight = CW_Memory;
2565       break;
2566     case 'r': // general register.
2567     case 'g': // general register, memory operand or immediate integer.
2568               // note: Clang converts "g" to "imr".
2569       if (CallOperandVal->getType()->isIntegerTy())
2570         weight = CW_Register;
2571       break;
2572     case 'X': // any operand.
2573     default:
2574       weight = CW_Default;
2575       break;
2576   }
2577   return weight;
2578 }
2579
2580 /// ChooseConstraint - If there are multiple different constraints that we
2581 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
2582 /// This is somewhat tricky: constraints fall into four classes:
2583 ///    Other         -> immediates and magic values
2584 ///    Register      -> one specific register
2585 ///    RegisterClass -> a group of regs
2586 ///    Memory        -> memory
2587 /// Ideally, we would pick the most specific constraint possible: if we have
2588 /// something that fits into a register, we would pick it.  The problem here
2589 /// is that if we have something that could either be in a register or in
2590 /// memory that use of the register could cause selection of *other*
2591 /// operands to fail: they might only succeed if we pick memory.  Because of
2592 /// this the heuristic we use is:
2593 ///
2594 ///  1) If there is an 'other' constraint, and if the operand is valid for
2595 ///     that constraint, use it.  This makes us take advantage of 'i'
2596 ///     constraints when available.
2597 ///  2) Otherwise, pick the most general constraint present.  This prefers
2598 ///     'm' over 'r', for example.
2599 ///
2600 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2601                              const TargetLowering &TLI,
2602                              SDValue Op, SelectionDAG *DAG) {
2603   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2604   unsigned BestIdx = 0;
2605   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2606   int BestGenerality = -1;
2607
2608   // Loop over the options, keeping track of the most general one.
2609   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2610     TargetLowering::ConstraintType CType =
2611       TLI.getConstraintType(OpInfo.Codes[i]);
2612
2613     // If this is an 'other' constraint, see if the operand is valid for it.
2614     // For example, on X86 we might have an 'rI' constraint.  If the operand
2615     // is an integer in the range [0..31] we want to use I (saving a load
2616     // of a register), otherwise we must use 'r'.
2617     if (CType == TargetLowering::C_Other && Op.getNode()) {
2618       assert(OpInfo.Codes[i].size() == 1 &&
2619              "Unhandled multi-letter 'other' constraint");
2620       std::vector<SDValue> ResultOps;
2621       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2622                                        ResultOps, *DAG);
2623       if (!ResultOps.empty()) {
2624         BestType = CType;
2625         BestIdx = i;
2626         break;
2627       }
2628     }
2629
2630     // Things with matching constraints can only be registers, per gcc
2631     // documentation.  This mainly affects "g" constraints.
2632     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2633       continue;
2634
2635     // This constraint letter is more general than the previous one, use it.
2636     int Generality = getConstraintGenerality(CType);
2637     if (Generality > BestGenerality) {
2638       BestType = CType;
2639       BestIdx = i;
2640       BestGenerality = Generality;
2641     }
2642   }
2643
2644   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2645   OpInfo.ConstraintType = BestType;
2646 }
2647
2648 /// ComputeConstraintToUse - Determines the constraint code and constraint
2649 /// type to use for the specific AsmOperandInfo, setting
2650 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
2651 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2652                                             SDValue Op,
2653                                             SelectionDAG *DAG) const {
2654   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2655
2656   // Single-letter constraints ('r') are very common.
2657   if (OpInfo.Codes.size() == 1) {
2658     OpInfo.ConstraintCode = OpInfo.Codes[0];
2659     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2660   } else {
2661     ChooseConstraint(OpInfo, *this, Op, DAG);
2662   }
2663
2664   // 'X' matches anything.
2665   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2666     // Labels and constants are handled elsewhere ('X' is the only thing
2667     // that matches labels).  For Functions, the type here is the type of
2668     // the result, which is not what we want to look at; leave them alone.
2669     Value *v = OpInfo.CallOperandVal;
2670     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2671       OpInfo.CallOperandVal = v;
2672       return;
2673     }
2674
2675     // Otherwise, try to resolve it to something we know about by looking at
2676     // the actual operand type.
2677     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2678       OpInfo.ConstraintCode = Repl;
2679       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2680     }
2681   }
2682 }
2683
2684 /// \brief Given an exact SDIV by a constant, create a multiplication
2685 /// with the multiplicative inverse of the constant.
2686 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2687                               SDLoc dl, SelectionDAG &DAG,
2688                               std::vector<SDNode *> &Created) {
2689   assert(d != 0 && "Division by zero!");
2690
2691   // Shift the value upfront if it is even, so the LSB is one.
2692   unsigned ShAmt = d.countTrailingZeros();
2693   if (ShAmt) {
2694     // TODO: For UDIV use SRL instead of SRA.
2695     SDValue Amt =
2696         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType()));
2697     SDNodeFlags Flags;
2698     Flags.setExact(true);
2699     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2700     Created.push_back(Op1.getNode());
2701     d = d.ashr(ShAmt);
2702   }
2703
2704   // Calculate the multiplicative inverse, using Newton's method.
2705   APInt t, xn = d;
2706   while ((t = d*xn) != 1)
2707     xn *= APInt(d.getBitWidth(), 2) - t;
2708
2709   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2710   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2711   Created.push_back(Mul.getNode());
2712   return Mul;
2713 }
2714
2715 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2716 /// return a DAG expression to select that will generate the same value by
2717 /// multiplying by a magic number.
2718 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2719 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2720                                   SelectionDAG &DAG, bool IsAfterLegalization,
2721                                   std::vector<SDNode *> *Created) const {
2722   assert(Created && "No vector to hold sdiv ops.");
2723
2724   EVT VT = N->getValueType(0);
2725   SDLoc dl(N);
2726
2727   // Check to see if we can do this.
2728   // FIXME: We should be more aggressive here.
2729   if (!isTypeLegal(VT))
2730     return SDValue();
2731
2732   // If the sdiv has an 'exact' bit we can use a simpler lowering.
2733   if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2734     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2735
2736   APInt::ms magics = Divisor.magic();
2737
2738   // Multiply the numerator (operand 0) by the magic value
2739   // FIXME: We should support doing a MUL in a wider type
2740   SDValue Q;
2741   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2742                             isOperationLegalOrCustom(ISD::MULHS, VT))
2743     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2744                     DAG.getConstant(magics.m, dl, VT));
2745   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2746                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2747     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2748                               N->getOperand(0),
2749                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
2750   else
2751     return SDValue();       // No mulhs or equvialent
2752   // If d > 0 and m < 0, add the numerator
2753   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
2754     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2755     Created->push_back(Q.getNode());
2756   }
2757   // If d < 0 and m > 0, subtract the numerator.
2758   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
2759     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2760     Created->push_back(Q.getNode());
2761   }
2762   // Shift right algebraic if shift value is nonzero
2763   if (magics.s > 0) {
2764     Q = DAG.getNode(ISD::SRA, dl, VT, Q,
2765                     DAG.getConstant(magics.s, dl,
2766                                     getShiftAmountTy(Q.getValueType())));
2767     Created->push_back(Q.getNode());
2768   }
2769   // Extract the sign bit and add it to the quotient
2770   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q,
2771                           DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2772                                           getShiftAmountTy(Q.getValueType())));
2773   Created->push_back(T.getNode());
2774   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2775 }
2776
2777 /// \brief Given an ISD::UDIV node expressing a divide by constant,
2778 /// return a DAG expression to select that will generate the same value by
2779 /// multiplying by a magic number.
2780 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2781 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2782                                   SelectionDAG &DAG, bool IsAfterLegalization,
2783                                   std::vector<SDNode *> *Created) const {
2784   assert(Created && "No vector to hold udiv ops.");
2785
2786   EVT VT = N->getValueType(0);
2787   SDLoc dl(N);
2788
2789   // Check to see if we can do this.
2790   // FIXME: We should be more aggressive here.
2791   if (!isTypeLegal(VT))
2792     return SDValue();
2793
2794   // FIXME: We should use a narrower constant when the upper
2795   // bits are known to be zero.
2796   APInt::mu magics = Divisor.magicu();
2797
2798   SDValue Q = N->getOperand(0);
2799
2800   // If the divisor is even, we can avoid using the expensive fixup by shifting
2801   // the divided value upfront.
2802   if (magics.a != 0 && !Divisor[0]) {
2803     unsigned Shift = Divisor.countTrailingZeros();
2804     Q = DAG.getNode(ISD::SRL, dl, VT, Q,
2805                     DAG.getConstant(Shift, dl,
2806                                     getShiftAmountTy(Q.getValueType())));
2807     Created->push_back(Q.getNode());
2808
2809     // Get magic number for the shifted divisor.
2810     magics = Divisor.lshr(Shift).magicu(Shift);
2811     assert(magics.a == 0 && "Should use cheap fixup now");
2812   }
2813
2814   // Multiply the numerator (operand 0) by the magic value
2815   // FIXME: We should support doing a MUL in a wider type
2816   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2817                             isOperationLegalOrCustom(ISD::MULHU, VT))
2818     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
2819   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2820                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2821     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
2822                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
2823   else
2824     return SDValue();       // No mulhu or equvialent
2825
2826   Created->push_back(Q.getNode());
2827
2828   if (magics.a == 0) {
2829     assert(magics.s < Divisor.getBitWidth() &&
2830            "We shouldn't generate an undefined shift!");
2831     return DAG.getNode(ISD::SRL, dl, VT, Q,
2832                        DAG.getConstant(magics.s, dl,
2833                                        getShiftAmountTy(Q.getValueType())));
2834   } else {
2835     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2836     Created->push_back(NPQ.getNode());
2837     NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
2838                       DAG.getConstant(1, dl,
2839                                       getShiftAmountTy(NPQ.getValueType())));
2840     Created->push_back(NPQ.getNode());
2841     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2842     Created->push_back(NPQ.getNode());
2843     return DAG.getNode(ISD::SRL, dl, VT, NPQ,
2844                        DAG.getConstant(magics.s - 1, dl,
2845                                        getShiftAmountTy(NPQ.getValueType())));
2846   }
2847 }
2848
2849 bool TargetLowering::
2850 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2851   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2852     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2853                                 "be a constant integer");
2854     return true;
2855   }
2856
2857   return false;
2858 }
2859
2860 //===----------------------------------------------------------------------===//
2861 // Legalization Utilities
2862 //===----------------------------------------------------------------------===//
2863
2864 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2865                                SelectionDAG &DAG, SDValue LL, SDValue LH,
2866                                SDValue RL, SDValue RH) const {
2867   EVT VT = N->getValueType(0);
2868   SDLoc dl(N);
2869
2870   bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
2871   bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
2872   bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
2873   bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
2874   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
2875     unsigned OuterBitSize = VT.getSizeInBits();
2876     unsigned InnerBitSize = HiLoVT.getSizeInBits();
2877     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
2878     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
2879
2880     // LL, LH, RL, and RH must be either all NULL or all set to a value.
2881     assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
2882            (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
2883
2884     if (!LL.getNode() && !RL.getNode() &&
2885         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
2886       LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
2887       RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
2888     }
2889
2890     if (!LL.getNode())
2891       return false;
2892
2893     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
2894     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
2895         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
2896       // The inputs are both zero-extended.
2897       if (HasUMUL_LOHI) {
2898         // We can emit a umul_lohi.
2899         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
2900                          RL);
2901         Hi = SDValue(Lo.getNode(), 1);
2902         return true;
2903       }
2904       if (HasMULHU) {
2905         // We can emit a mulhu+mul.
2906         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2907         Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
2908         return true;
2909       }
2910     }
2911     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
2912       // The input values are both sign-extended.
2913       if (HasSMUL_LOHI) {
2914         // We can emit a smul_lohi.
2915         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
2916                          RL);
2917         Hi = SDValue(Lo.getNode(), 1);
2918         return true;
2919       }
2920       if (HasMULHS) {
2921         // We can emit a mulhs+mul.
2922         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2923         Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
2924         return true;
2925       }
2926     }
2927
2928     if (!LH.getNode() && !RH.getNode() &&
2929         isOperationLegalOrCustom(ISD::SRL, VT) &&
2930         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
2931       unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
2932       SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT));
2933       LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
2934       LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
2935       RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
2936       RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
2937     }
2938
2939     if (!LH.getNode())
2940       return false;
2941
2942     if (HasUMUL_LOHI) {
2943       // Lo,Hi = umul LHS, RHS.
2944       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
2945                                      DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
2946       Lo = UMulLOHI;
2947       Hi = UMulLOHI.getValue(1);
2948       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
2949       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
2950       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
2951       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
2952       return true;
2953     }
2954     if (HasMULHU) {
2955       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2956       Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
2957       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
2958       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
2959       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
2960       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
2961       return true;
2962     }
2963   }
2964   return false;
2965 }
2966
2967 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
2968                                SelectionDAG &DAG) const {
2969   EVT VT = Node->getOperand(0).getValueType();
2970   EVT NVT = Node->getValueType(0);
2971   SDLoc dl(SDValue(Node, 0));
2972
2973   // FIXME: Only f32 to i64 conversions are supported.
2974   if (VT != MVT::f32 || NVT != MVT::i64)
2975     return false;
2976
2977   // Expand f32 -> i64 conversion
2978   // This algorithm comes from compiler-rt's implementation of fixsfdi:
2979   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
2980   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
2981                                 VT.getSizeInBits());
2982   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
2983   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
2984   SDValue Bias = DAG.getConstant(127, dl, IntVT);
2985   SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
2986                                      IntVT);
2987   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
2988   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
2989
2990   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
2991
2992   SDValue ExponentBits = DAG.getNode(ISD::SRL, dl, IntVT,
2993       DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
2994       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT)));
2995   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
2996
2997   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
2998       DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
2999       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT)));
3000   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3001
3002   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3003       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3004       DAG.getConstant(0x00800000, dl, IntVT));
3005
3006   R = DAG.getZExtOrTrunc(R, dl, NVT);
3007
3008
3009   R = DAG.getSelectCC(dl, Exponent, ExponentLoBit,
3010      DAG.getNode(ISD::SHL, dl, NVT, R,
3011                  DAG.getZExtOrTrunc(
3012                     DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3013                     dl, getShiftAmountTy(IntVT))),
3014      DAG.getNode(ISD::SRL, dl, NVT, R,
3015                  DAG.getZExtOrTrunc(
3016                     DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3017                     dl, getShiftAmountTy(IntVT))),
3018      ISD::SETGT);
3019
3020   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3021       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3022       Sign);
3023
3024   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3025       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3026   return true;
3027 }