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