TargetLowering.cpp revision 93f81e2822aa67337f629398c81bc2844ef9400a
1//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/Target/TargetData.h"
16#include "llvm/Target/TargetMachine.h"
17#include "llvm/Target/MRegisterInfo.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/CodeGen/SelectionDAG.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/Support/MathExtras.h"
22using namespace llvm;
23
24/// InitLibcallNames - Set default libcall names.
25///
26static void InitLibcallNames(const char **Names) {
27  Names[RTLIB::SHL_I32] = "__ashlsi3";
28  Names[RTLIB::SHL_I64] = "__ashldi3";
29  Names[RTLIB::SRL_I32] = "__lshrsi3";
30  Names[RTLIB::SRL_I64] = "__lshrdi3";
31  Names[RTLIB::SRA_I32] = "__ashrsi3";
32  Names[RTLIB::SRA_I64] = "__ashrdi3";
33  Names[RTLIB::MUL_I32] = "__mulsi3";
34  Names[RTLIB::MUL_I64] = "__muldi3";
35  Names[RTLIB::SDIV_I32] = "__divsi3";
36  Names[RTLIB::SDIV_I64] = "__divdi3";
37  Names[RTLIB::UDIV_I32] = "__udivsi3";
38  Names[RTLIB::UDIV_I64] = "__udivdi3";
39  Names[RTLIB::SREM_I32] = "__modsi3";
40  Names[RTLIB::SREM_I64] = "__moddi3";
41  Names[RTLIB::UREM_I32] = "__umodsi3";
42  Names[RTLIB::UREM_I64] = "__umoddi3";
43  Names[RTLIB::NEG_I32] = "__negsi2";
44  Names[RTLIB::NEG_I64] = "__negdi2";
45  Names[RTLIB::ADD_F32] = "__addsf3";
46  Names[RTLIB::ADD_F64] = "__adddf3";
47  Names[RTLIB::SUB_F32] = "__subsf3";
48  Names[RTLIB::SUB_F64] = "__subdf3";
49  Names[RTLIB::MUL_F32] = "__mulsf3";
50  Names[RTLIB::MUL_F64] = "__muldf3";
51  Names[RTLIB::DIV_F32] = "__divsf3";
52  Names[RTLIB::DIV_F64] = "__divdf3";
53  Names[RTLIB::REM_F32] = "fmodf";
54  Names[RTLIB::REM_F64] = "fmod";
55  Names[RTLIB::NEG_F32] = "__negsf2";
56  Names[RTLIB::NEG_F64] = "__negdf2";
57  Names[RTLIB::POWI_F32] = "__powisf2";
58  Names[RTLIB::POWI_F64] = "__powidf2";
59  Names[RTLIB::SQRT_F32] = "sqrtf";
60  Names[RTLIB::SQRT_F64] = "sqrt";
61  Names[RTLIB::SIN_F32] = "sinf";
62  Names[RTLIB::SIN_F64] = "sin";
63  Names[RTLIB::COS_F32] = "cosf";
64  Names[RTLIB::COS_F64] = "cos";
65  Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
66  Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
67  Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
68  Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
69  Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
70  Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
71  Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
72  Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
73  Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
74  Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
75  Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
76  Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
77  Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
78  Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
79  Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
80  Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
81  Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
82  Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
83  Names[RTLIB::OEQ_F32] = "__eqsf2";
84  Names[RTLIB::OEQ_F64] = "__eqdf2";
85  Names[RTLIB::UNE_F32] = "__nesf2";
86  Names[RTLIB::UNE_F64] = "__nedf2";
87  Names[RTLIB::OGE_F32] = "__gesf2";
88  Names[RTLIB::OGE_F64] = "__gedf2";
89  Names[RTLIB::OLT_F32] = "__ltsf2";
90  Names[RTLIB::OLT_F64] = "__ltdf2";
91  Names[RTLIB::OLE_F32] = "__lesf2";
92  Names[RTLIB::OLE_F64] = "__ledf2";
93  Names[RTLIB::OGT_F32] = "__gtsf2";
94  Names[RTLIB::OGT_F64] = "__gtdf2";
95  Names[RTLIB::UO_F32] = "__unordsf2";
96  Names[RTLIB::UO_F64] = "__unorddf2";
97  Names[RTLIB::O_F32] = "__unordsf2";
98  Names[RTLIB::O_F64] = "__unorddf2";
99}
100
101/// InitCmpLibcallCCs - Set default comparison libcall CC.
102///
103static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
104  memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
105  CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
106  CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
107  CCs[RTLIB::UNE_F32] = ISD::SETNE;
108  CCs[RTLIB::UNE_F64] = ISD::SETNE;
109  CCs[RTLIB::OGE_F32] = ISD::SETGE;
110  CCs[RTLIB::OGE_F64] = ISD::SETGE;
111  CCs[RTLIB::OLT_F32] = ISD::SETLT;
112  CCs[RTLIB::OLT_F64] = ISD::SETLT;
113  CCs[RTLIB::OLE_F32] = ISD::SETLE;
114  CCs[RTLIB::OLE_F64] = ISD::SETLE;
115  CCs[RTLIB::OGT_F32] = ISD::SETGT;
116  CCs[RTLIB::OGT_F64] = ISD::SETGT;
117  CCs[RTLIB::UO_F32] = ISD::SETNE;
118  CCs[RTLIB::UO_F64] = ISD::SETNE;
119  CCs[RTLIB::O_F32] = ISD::SETEQ;
120  CCs[RTLIB::O_F64] = ISD::SETEQ;
121}
122
123TargetLowering::TargetLowering(TargetMachine &tm)
124  : TM(tm), TD(TM.getTargetData()) {
125  assert(ISD::BUILTIN_OP_END <= 156 &&
126         "Fixed size array in TargetLowering is not large enough!");
127  // All operations default to being supported.
128  memset(OpActions, 0, sizeof(OpActions));
129  memset(LoadXActions, 0, sizeof(LoadXActions));
130  memset(&StoreXActions, 0, sizeof(StoreXActions));
131  memset(&IndexedModeActions, 0, sizeof(IndexedModeActions));
132
133  // Set all indexed load / store to expand.
134  for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
135    for (unsigned IM = (unsigned)ISD::PRE_INC;
136         IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
137      setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand);
138      setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand);
139    }
140  }
141
142  IsLittleEndian = TD->isLittleEndian();
143  UsesGlobalOffsetTable = false;
144  ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD->getIntPtrType());
145  ShiftAmtHandling = Undefined;
146  memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
147  memset(TargetDAGCombineArray, 0,
148         sizeof(TargetDAGCombineArray)/sizeof(TargetDAGCombineArray[0]));
149  maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
150  allowUnalignedMemoryAccesses = false;
151  UseUnderscoreSetJmp = false;
152  UseUnderscoreLongJmp = false;
153  SelectIsExpensive = false;
154  IntDivIsCheap = false;
155  Pow2DivIsCheap = false;
156  StackPointerRegisterToSaveRestore = 0;
157  ExceptionPointerRegister = 0;
158  ExceptionSelectorRegister = 0;
159  SchedPreferenceInfo = SchedulingForLatency;
160  JumpBufSize = 0;
161  JumpBufAlignment = 0;
162  IfCvtBlockSizeLimit = 2;
163
164  InitLibcallNames(LibcallRoutineNames);
165  InitCmpLibcallCCs(CmpLibcallCCs);
166}
167
168TargetLowering::~TargetLowering() {}
169
170/// computeRegisterProperties - Once all of the register classes are added,
171/// this allows us to compute derived properties we expose.
172void TargetLowering::computeRegisterProperties() {
173  assert(MVT::LAST_VALUETYPE <= 32 &&
174         "Too many value types for ValueTypeActions to hold!");
175
176  // Everything defaults to needing one register.
177  for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
178    NumRegistersForVT[i] = 1;
179    RegisterTypeForVT[i] = TransformToType[i] = i;
180  }
181  // ...except isVoid, which doesn't need any registers.
182  NumRegistersForVT[MVT::isVoid] = 0;
183
184  // Find the largest integer register class.
185  unsigned LargestIntReg = MVT::i128;
186  for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
187    assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
188
189  // Every integer value type larger than this largest register takes twice as
190  // many registers to represent as the previous ValueType.
191  for (MVT::ValueType ExpandedReg = LargestIntReg + 1;
192       MVT::isInteger(ExpandedReg); ++ExpandedReg) {
193    NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
194    RegisterTypeForVT[ExpandedReg] = LargestIntReg;
195    TransformToType[ExpandedReg] = ExpandedReg - 1;
196    ValueTypeActions.setTypeAction(ExpandedReg, Expand);
197  }
198
199  // Inspect all of the ValueType's smaller than the largest integer
200  // register to see which ones need promotion.
201  MVT::ValueType LegalIntReg = LargestIntReg;
202  for (MVT::ValueType IntReg = LargestIntReg - 1;
203       IntReg >= MVT::i1; --IntReg) {
204    if (isTypeLegal(IntReg)) {
205      LegalIntReg = IntReg;
206    } else {
207      RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg;
208      ValueTypeActions.setTypeAction(IntReg, Promote);
209    }
210  }
211
212  // Decide how to handle f64. If the target does not have native f64 support,
213  // expand it to i64 and we will be generating soft float library calls.
214  if (!isTypeLegal(MVT::f64)) {
215    NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
216    RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
217    TransformToType[MVT::f64] = MVT::i64;
218    ValueTypeActions.setTypeAction(MVT::f64, Expand);
219  }
220
221  // Decide how to handle f32. If the target does not have native support for
222  // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
223  if (!isTypeLegal(MVT::f32)) {
224    if (isTypeLegal(MVT::f64)) {
225      NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
226      RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
227      TransformToType[MVT::f32] = MVT::f64;
228      ValueTypeActions.setTypeAction(MVT::f32, Promote);
229    } else {
230      NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
231      RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
232      TransformToType[MVT::f32] = MVT::i32;
233      ValueTypeActions.setTypeAction(MVT::f32, Expand);
234    }
235  }
236
237  // Loop over all of the vector value types to see which need transformations.
238  for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE;
239       i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
240    if (!isTypeLegal(i)) {
241      MVT::ValueType IntermediateVT, RegisterVT;
242      unsigned NumIntermediates;
243      NumRegistersForVT[i] =
244        getVectorTypeBreakdown(i,
245                               IntermediateVT, NumIntermediates,
246                               RegisterVT);
247      RegisterTypeForVT[i] = RegisterVT;
248      TransformToType[i] = MVT::Other; // this isn't actually used
249      ValueTypeActions.setTypeAction(i, Expand);
250    }
251  }
252}
253
254const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
255  return NULL;
256}
257
258/// getVectorTypeBreakdown - Vector types are broken down into some number of
259/// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
260/// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
261/// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
262///
263/// This method returns the number of registers needed, and the VT for each
264/// register.  It also returns the VT and quantity of the intermediate values
265/// before they are promoted/expanded.
266///
267unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT,
268                                                MVT::ValueType &IntermediateVT,
269                                                unsigned &NumIntermediates,
270                                      MVT::ValueType &RegisterVT) const {
271  // Figure out the right, legal destination reg to copy into.
272  unsigned NumElts = MVT::getVectorNumElements(VT);
273  MVT::ValueType EltTy = MVT::getVectorElementType(VT);
274
275  unsigned NumVectorRegs = 1;
276
277  // Divide the input until we get to a supported size.  This will always
278  // end with a scalar if the target doesn't support vectors.
279  while (NumElts > 1 &&
280         !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) {
281    NumElts >>= 1;
282    NumVectorRegs <<= 1;
283  }
284
285  NumIntermediates = NumVectorRegs;
286
287  MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts);
288  if (!isTypeLegal(NewVT))
289    NewVT = EltTy;
290  IntermediateVT = NewVT;
291
292  MVT::ValueType DestVT = getTypeToTransformTo(NewVT);
293  RegisterVT = DestVT;
294  if (DestVT < NewVT) {
295    // Value is expanded, e.g. i64 -> i16.
296    return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT));
297  } else {
298    // Otherwise, promotion or legal types use the same number of registers as
299    // the vector decimated to the appropriate level.
300    return NumVectorRegs;
301  }
302
303  return 1;
304}
305
306//===----------------------------------------------------------------------===//
307//  Optimization Methods
308//===----------------------------------------------------------------------===//
309
310/// ShrinkDemandedConstant - Check to see if the specified operand of the
311/// specified instruction is a constant integer.  If so, check to see if there
312/// are any bits set in the constant that are not demanded.  If so, shrink the
313/// constant and return true.
314bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op,
315                                                            uint64_t Demanded) {
316  // FIXME: ISD::SELECT, ISD::SELECT_CC
317  switch(Op.getOpcode()) {
318  default: break;
319  case ISD::AND:
320  case ISD::OR:
321  case ISD::XOR:
322    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
323      if ((~Demanded & C->getValue()) != 0) {
324        MVT::ValueType VT = Op.getValueType();
325        SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
326                                    DAG.getConstant(Demanded & C->getValue(),
327                                                    VT));
328        return CombineTo(Op, New);
329      }
330    break;
331  }
332  return false;
333}
334
335/// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
336/// DemandedMask bits of the result of Op are ever used downstream.  If we can
337/// use this information to simplify Op, create a new simplified DAG node and
338/// return true, returning the original and new nodes in Old and New. Otherwise,
339/// analyze the expression and return a mask of KnownOne and KnownZero bits for
340/// the expression (used to simplify the caller).  The KnownZero/One bits may
341/// only be accurate for those bits in the DemandedMask.
342bool TargetLowering::SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask,
343                                          uint64_t &KnownZero,
344                                          uint64_t &KnownOne,
345                                          TargetLoweringOpt &TLO,
346                                          unsigned Depth) const {
347  KnownZero = KnownOne = 0;   // Don't know anything.
348
349  // The masks are not wide enough to represent this type!  Should use APInt.
350  if (Op.getValueType() == MVT::i128)
351    return false;
352
353  // Other users may use these bits.
354  if (!Op.Val->hasOneUse()) {
355    if (Depth != 0) {
356      // If not at the root, Just compute the KnownZero/KnownOne bits to
357      // simplify things downstream.
358      TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
359      return false;
360    }
361    // If this is the root being simplified, allow it to have multiple uses,
362    // just set the DemandedMask to all bits.
363    DemandedMask = MVT::getIntVTBitMask(Op.getValueType());
364  } else if (DemandedMask == 0) {
365    // Not demanding any bits from Op.
366    if (Op.getOpcode() != ISD::UNDEF)
367      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
368    return false;
369  } else if (Depth == 6) {        // Limit search depth.
370    return false;
371  }
372
373  uint64_t KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
374  switch (Op.getOpcode()) {
375  case ISD::Constant:
376    // We know all of the bits for a constant!
377    KnownOne = cast<ConstantSDNode>(Op)->getValue() & DemandedMask;
378    KnownZero = ~KnownOne & DemandedMask;
379    return false;   // Don't fall through, will infinitely loop.
380  case ISD::AND:
381    // If the RHS is a constant, check to see if the LHS would be zero without
382    // using the bits from the RHS.  Below, we use knowledge about the RHS to
383    // simplify the LHS, here we're using information from the LHS to simplify
384    // the RHS.
385    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
386      uint64_t LHSZero, LHSOne;
387      TLO.DAG.ComputeMaskedBits(Op.getOperand(0), DemandedMask,
388                                LHSZero, LHSOne, Depth+1);
389      // If the LHS already has zeros where RHSC does, this and is dead.
390      if ((LHSZero & DemandedMask) == (~RHSC->getValue() & DemandedMask))
391        return TLO.CombineTo(Op, Op.getOperand(0));
392      // If any of the set bits in the RHS are known zero on the LHS, shrink
393      // the constant.
394      if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & DemandedMask))
395        return true;
396    }
397
398    if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
399                             KnownOne, TLO, Depth+1))
400      return true;
401    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
402    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownZero,
403                             KnownZero2, KnownOne2, TLO, Depth+1))
404      return true;
405    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
406
407    // If all of the demanded bits are known one on one side, return the other.
408    // These bits cannot contribute to the result of the 'and'.
409    if ((DemandedMask & ~KnownZero2 & KnownOne)==(DemandedMask & ~KnownZero2))
410      return TLO.CombineTo(Op, Op.getOperand(0));
411    if ((DemandedMask & ~KnownZero & KnownOne2)==(DemandedMask & ~KnownZero))
412      return TLO.CombineTo(Op, Op.getOperand(1));
413    // If all of the demanded bits in the inputs are known zeros, return zero.
414    if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
415      return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
416    // If the RHS is a constant, see if we can simplify it.
417    if (TLO.ShrinkDemandedConstant(Op, DemandedMask & ~KnownZero2))
418      return true;
419
420    // Output known-1 bits are only known if set in both the LHS & RHS.
421    KnownOne &= KnownOne2;
422    // Output known-0 are known to be clear if zero in either the LHS | RHS.
423    KnownZero |= KnownZero2;
424    break;
425  case ISD::OR:
426    if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
427                             KnownOne, TLO, Depth+1))
428      return true;
429    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
430    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownOne,
431                             KnownZero2, KnownOne2, TLO, Depth+1))
432      return true;
433    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
434
435    // If all of the demanded bits are known zero on one side, return the other.
436    // These bits cannot contribute to the result of the 'or'.
437    if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
438      return TLO.CombineTo(Op, Op.getOperand(0));
439    if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
440      return TLO.CombineTo(Op, Op.getOperand(1));
441    // If all of the potentially set bits on one side are known to be set on
442    // the other side, just use the 'other' side.
443    if ((DemandedMask & (~KnownZero) & KnownOne2) ==
444        (DemandedMask & (~KnownZero)))
445      return TLO.CombineTo(Op, Op.getOperand(0));
446    if ((DemandedMask & (~KnownZero2) & KnownOne) ==
447        (DemandedMask & (~KnownZero2)))
448      return TLO.CombineTo(Op, Op.getOperand(1));
449    // If the RHS is a constant, see if we can simplify it.
450    if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
451      return true;
452
453    // Output known-0 bits are only known if clear in both the LHS & RHS.
454    KnownZero &= KnownZero2;
455    // Output known-1 are known to be set if set in either the LHS | RHS.
456    KnownOne |= KnownOne2;
457    break;
458  case ISD::XOR:
459    if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
460                             KnownOne, TLO, Depth+1))
461      return true;
462    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
463    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask, KnownZero2,
464                             KnownOne2, TLO, Depth+1))
465      return true;
466    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
467
468    // If all of the demanded bits are known zero on one side, return the other.
469    // These bits cannot contribute to the result of the 'xor'.
470    if ((DemandedMask & KnownZero) == DemandedMask)
471      return TLO.CombineTo(Op, Op.getOperand(0));
472    if ((DemandedMask & KnownZero2) == DemandedMask)
473      return TLO.CombineTo(Op, Op.getOperand(1));
474
475    // If all of the unknown bits are known to be zero on one side or the other
476    // (but not both) turn this into an *inclusive* or.
477    //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
478    if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0)
479      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
480                                               Op.getOperand(0),
481                                               Op.getOperand(1)));
482
483    // Output known-0 bits are known if clear or set in both the LHS & RHS.
484    KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
485    // Output known-1 are known to be set if set in only one of the LHS, RHS.
486    KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
487
488    // If all of the demanded bits on one side are known, and all of the set
489    // bits on that side are also known to be set on the other side, turn this
490    // into an AND, as we know the bits will be cleared.
491    //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
492    if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
493      if ((KnownOne & KnownOne2) == KnownOne) {
494        MVT::ValueType VT = Op.getValueType();
495        SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & DemandedMask, VT);
496        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
497                                                 ANDC));
498      }
499    }
500
501    // If the RHS is a constant, see if we can simplify it.
502    // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
503    if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
504      return true;
505
506    KnownZero = KnownZeroOut;
507    KnownOne  = KnownOneOut;
508    break;
509  case ISD::SETCC:
510    // If we know the result of a setcc has the top bits zero, use this info.
511    if (getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
512      KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
513    break;
514  case ISD::SELECT:
515    if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero,
516                             KnownOne, TLO, Depth+1))
517      return true;
518    if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero2,
519                             KnownOne2, TLO, Depth+1))
520      return true;
521    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
522    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
523
524    // If the operands are constants, see if we can simplify them.
525    if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
526      return true;
527
528    // Only known if known in both the LHS and RHS.
529    KnownOne &= KnownOne2;
530    KnownZero &= KnownZero2;
531    break;
532  case ISD::SELECT_CC:
533    if (SimplifyDemandedBits(Op.getOperand(3), DemandedMask, KnownZero,
534                             KnownOne, TLO, Depth+1))
535      return true;
536    if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero2,
537                             KnownOne2, TLO, Depth+1))
538      return true;
539    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
540    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
541
542    // If the operands are constants, see if we can simplify them.
543    if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
544      return true;
545
546    // Only known if known in both the LHS and RHS.
547    KnownOne &= KnownOne2;
548    KnownZero &= KnownZero2;
549    break;
550  case ISD::SHL:
551    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
552      unsigned ShAmt = SA->getValue();
553      SDOperand InOp = Op.getOperand(0);
554
555      // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
556      // single shift.  We can do this if the bottom bits (which are shifted
557      // out) are never demanded.
558      if (InOp.getOpcode() == ISD::SRL &&
559          isa<ConstantSDNode>(InOp.getOperand(1))) {
560        if (ShAmt && (DemandedMask & ((1ULL << ShAmt)-1)) == 0) {
561          unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
562          unsigned Opc = ISD::SHL;
563          int Diff = ShAmt-C1;
564          if (Diff < 0) {
565            Diff = -Diff;
566            Opc = ISD::SRL;
567          }
568
569          SDOperand NewSA =
570            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
571          MVT::ValueType VT = Op.getValueType();
572          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
573                                                   InOp.getOperand(0), NewSA));
574        }
575      }
576
577      if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask >> ShAmt,
578                               KnownZero, KnownOne, TLO, Depth+1))
579        return true;
580      KnownZero <<= SA->getValue();
581      KnownOne  <<= SA->getValue();
582      KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
583    }
584    break;
585  case ISD::SRL:
586    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
587      MVT::ValueType VT = Op.getValueType();
588      unsigned ShAmt = SA->getValue();
589      uint64_t TypeMask = MVT::getIntVTBitMask(VT);
590      unsigned VTSize = MVT::getSizeInBits(VT);
591      SDOperand InOp = Op.getOperand(0);
592
593      // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
594      // single shift.  We can do this if the top bits (which are shifted out)
595      // are never demanded.
596      if (InOp.getOpcode() == ISD::SHL &&
597          isa<ConstantSDNode>(InOp.getOperand(1))) {
598        if (ShAmt && (DemandedMask & (~0ULL << (VTSize-ShAmt))) == 0) {
599          unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
600          unsigned Opc = ISD::SRL;
601          int Diff = ShAmt-C1;
602          if (Diff < 0) {
603            Diff = -Diff;
604            Opc = ISD::SHL;
605          }
606
607          SDOperand NewSA =
608            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
609          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
610                                                   InOp.getOperand(0), NewSA));
611        }
612      }
613
614      // Compute the new bits that are at the top now.
615      if (SimplifyDemandedBits(InOp, (DemandedMask << ShAmt) & TypeMask,
616                               KnownZero, KnownOne, TLO, Depth+1))
617        return true;
618      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
619      KnownZero &= TypeMask;
620      KnownOne  &= TypeMask;
621      KnownZero >>= ShAmt;
622      KnownOne  >>= ShAmt;
623
624      uint64_t HighBits = (1ULL << ShAmt)-1;
625      HighBits <<= VTSize - ShAmt;
626      KnownZero |= HighBits;  // High bits known zero.
627    }
628    break;
629  case ISD::SRA:
630    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
631      MVT::ValueType VT = Op.getValueType();
632      unsigned ShAmt = SA->getValue();
633
634      // Compute the new bits that are at the top now.
635      uint64_t TypeMask = MVT::getIntVTBitMask(VT);
636
637      uint64_t InDemandedMask = (DemandedMask << ShAmt) & TypeMask;
638
639      // If any of the demanded bits are produced by the sign extension, we also
640      // demand the input sign bit.
641      uint64_t HighBits = (1ULL << ShAmt)-1;
642      HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
643      if (HighBits & DemandedMask)
644        InDemandedMask |= MVT::getIntVTSignBit(VT);
645
646      if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
647                               KnownZero, KnownOne, TLO, Depth+1))
648        return true;
649      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
650      KnownZero &= TypeMask;
651      KnownOne  &= TypeMask;
652      KnownZero >>= ShAmt;
653      KnownOne  >>= ShAmt;
654
655      // Handle the sign bits.
656      uint64_t SignBit = MVT::getIntVTSignBit(VT);
657      SignBit >>= ShAmt;  // Adjust to where it is now in the mask.
658
659      // If the input sign bit is known to be zero, or if none of the top bits
660      // are demanded, turn this into an unsigned shift right.
661      if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
662        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
663                                                 Op.getOperand(1)));
664      } else if (KnownOne & SignBit) { // New bits are known one.
665        KnownOne |= HighBits;
666      }
667    }
668    break;
669  case ISD::SIGN_EXTEND_INREG: {
670    MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
671
672    // Sign extension.  Compute the demanded bits in the result that are not
673    // present in the input.
674    uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & DemandedMask;
675
676    // If none of the extended bits are demanded, eliminate the sextinreg.
677    if (NewBits == 0)
678      return TLO.CombineTo(Op, Op.getOperand(0));
679
680    uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
681    int64_t InputDemandedBits = DemandedMask & MVT::getIntVTBitMask(EVT);
682
683    // Since the sign extended bits are demanded, we know that the sign
684    // bit is demanded.
685    InputDemandedBits |= InSignBit;
686
687    if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
688                             KnownZero, KnownOne, TLO, Depth+1))
689      return true;
690    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
691
692    // If the sign bit of the input is known set or clear, then we know the
693    // top bits of the result.
694
695    // If the input sign bit is known zero, convert this into a zero extension.
696    if (KnownZero & InSignBit)
697      return TLO.CombineTo(Op,
698                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
699
700    if (KnownOne & InSignBit) {    // Input sign bit known set
701      KnownOne |= NewBits;
702      KnownZero &= ~NewBits;
703    } else {                       // Input sign bit unknown
704      KnownZero &= ~NewBits;
705      KnownOne &= ~NewBits;
706    }
707    break;
708  }
709  case ISD::CTTZ:
710  case ISD::CTLZ:
711  case ISD::CTPOP: {
712    MVT::ValueType VT = Op.getValueType();
713    unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
714    KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
715    KnownOne  = 0;
716    break;
717  }
718  case ISD::LOAD: {
719    if (ISD::isZEXTLoad(Op.Val)) {
720      LoadSDNode *LD = cast<LoadSDNode>(Op);
721      MVT::ValueType VT = LD->getLoadedVT();
722      KnownZero |= ~MVT::getIntVTBitMask(VT) & DemandedMask;
723    }
724    break;
725  }
726  case ISD::ZERO_EXTEND: {
727    uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
728
729    // If none of the top bits are demanded, convert this into an any_extend.
730    uint64_t NewBits = (~InMask) & DemandedMask;
731    if (NewBits == 0)
732      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND,
733                                               Op.getValueType(),
734                                               Op.getOperand(0)));
735
736    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
737                             KnownZero, KnownOne, TLO, Depth+1))
738      return true;
739    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
740    KnownZero |= NewBits;
741    break;
742  }
743  case ISD::SIGN_EXTEND: {
744    MVT::ValueType InVT = Op.getOperand(0).getValueType();
745    uint64_t InMask    = MVT::getIntVTBitMask(InVT);
746    uint64_t InSignBit = MVT::getIntVTSignBit(InVT);
747    uint64_t NewBits   = (~InMask) & DemandedMask;
748
749    // If none of the top bits are demanded, convert this into an any_extend.
750    if (NewBits == 0)
751      return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
752                                           Op.getOperand(0)));
753
754    // Since some of the sign extended bits are demanded, we know that the sign
755    // bit is demanded.
756    uint64_t InDemandedBits = DemandedMask & InMask;
757    InDemandedBits |= InSignBit;
758
759    if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
760                             KnownOne, TLO, Depth+1))
761      return true;
762
763    // If the sign bit is known zero, convert this to a zero extend.
764    if (KnownZero & InSignBit)
765      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND,
766                                               Op.getValueType(),
767                                               Op.getOperand(0)));
768
769    // If the sign bit is known one, the top bits match.
770    if (KnownOne & InSignBit) {
771      KnownOne  |= NewBits;
772      KnownZero &= ~NewBits;
773    } else {   // Otherwise, top bits aren't known.
774      KnownOne  &= ~NewBits;
775      KnownZero &= ~NewBits;
776    }
777    break;
778  }
779  case ISD::ANY_EXTEND: {
780    uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
781    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
782                             KnownZero, KnownOne, TLO, Depth+1))
783      return true;
784    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
785    break;
786  }
787  case ISD::TRUNCATE: {
788    // Simplify the input, using demanded bit information, and compute the known
789    // zero/one bits live out.
790    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
791                             KnownZero, KnownOne, TLO, Depth+1))
792      return true;
793
794    // If the input is only used by this truncate, see if we can shrink it based
795    // on the known demanded bits.
796    if (Op.getOperand(0).Val->hasOneUse()) {
797      SDOperand In = Op.getOperand(0);
798      switch (In.getOpcode()) {
799      default: break;
800      case ISD::SRL:
801        // Shrink SRL by a constant if none of the high bits shifted in are
802        // demanded.
803        if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
804          uint64_t HighBits = MVT::getIntVTBitMask(In.getValueType());
805          HighBits &= ~MVT::getIntVTBitMask(Op.getValueType());
806          HighBits >>= ShAmt->getValue();
807
808          if (ShAmt->getValue() < MVT::getSizeInBits(Op.getValueType()) &&
809              (DemandedMask & HighBits) == 0) {
810            // None of the shifted in bits are needed.  Add a truncate of the
811            // shift input, then shift it.
812            SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE,
813                                                 Op.getValueType(),
814                                                 In.getOperand(0));
815            return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
816                                                   NewTrunc, In.getOperand(1)));
817          }
818        }
819        break;
820      }
821    }
822
823    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
824    uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
825    KnownZero &= OutMask;
826    KnownOne &= OutMask;
827    break;
828  }
829  case ISD::AssertZext: {
830    MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
831    uint64_t InMask = MVT::getIntVTBitMask(VT);
832    if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
833                             KnownZero, KnownOne, TLO, Depth+1))
834      return true;
835    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
836    KnownZero |= ~InMask & DemandedMask;
837    break;
838  }
839  case ISD::ADD:
840  case ISD::SUB:
841  case ISD::INTRINSIC_WO_CHAIN:
842  case ISD::INTRINSIC_W_CHAIN:
843  case ISD::INTRINSIC_VOID:
844    // Just use ComputeMaskedBits to compute output bits.
845    TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
846    break;
847  }
848
849  // If we know the value of all of the demanded bits, return this as a
850  // constant.
851  if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
852    return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
853
854  return false;
855}
856
857/// computeMaskedBitsForTargetNode - Determine which of the bits specified
858/// in Mask are known to be either zero or one and return them in the
859/// KnownZero/KnownOne bitsets.
860void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
861                                                    uint64_t Mask,
862                                                    uint64_t &KnownZero,
863                                                    uint64_t &KnownOne,
864                                                    const SelectionDAG &DAG,
865                                                    unsigned Depth) const {
866  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
867          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
868          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
869          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
870         "Should use MaskedValueIsZero if you don't know whether Op"
871         " is a target node!");
872  KnownZero = 0;
873  KnownOne = 0;
874}
875
876/// ComputeNumSignBitsForTargetNode - This method can be implemented by
877/// targets that want to expose additional information about sign bits to the
878/// DAG Combiner.
879unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
880                                                         unsigned Depth) const {
881  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
882          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
883          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
884          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
885         "Should use ComputeNumSignBits if you don't know whether Op"
886         " is a target node!");
887  return 1;
888}
889
890
891/// SimplifySetCC - Try to simplify a setcc built with the specified operands
892/// and cc. If it is unable to simplify it, return a null SDOperand.
893SDOperand
894TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
895                              ISD::CondCode Cond, bool foldBooleans,
896                              DAGCombinerInfo &DCI) const {
897  SelectionDAG &DAG = DCI.DAG;
898
899  // These setcc operations always fold.
900  switch (Cond) {
901  default: break;
902  case ISD::SETFALSE:
903  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
904  case ISD::SETTRUE:
905  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
906  }
907
908  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
909    uint64_t C1 = N1C->getValue();
910    if (isa<ConstantSDNode>(N0.Val)) {
911      return DAG.FoldSetCC(VT, N0, N1, Cond);
912    } else {
913      // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
914      // equality comparison, then we're just comparing whether X itself is
915      // zero.
916      if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
917          N0.getOperand(0).getOpcode() == ISD::CTLZ &&
918          N0.getOperand(1).getOpcode() == ISD::Constant) {
919        unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
920        if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
921            ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
922          if ((C1 == 0) == (Cond == ISD::SETEQ)) {
923            // (srl (ctlz x), 5) == 0  -> X != 0
924            // (srl (ctlz x), 5) != 1  -> X != 0
925            Cond = ISD::SETNE;
926          } else {
927            // (srl (ctlz x), 5) != 0  -> X == 0
928            // (srl (ctlz x), 5) == 1  -> X == 0
929            Cond = ISD::SETEQ;
930          }
931          SDOperand Zero = DAG.getConstant(0, N0.getValueType());
932          return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
933                              Zero, Cond);
934        }
935      }
936
937      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
938      if (N0.getOpcode() == ISD::ZERO_EXTEND) {
939        unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
940
941        // If the comparison constant has bits in the upper part, the
942        // zero-extended value could never match.
943        if (C1 & (~0ULL << InSize)) {
944          unsigned VSize = MVT::getSizeInBits(N0.getValueType());
945          switch (Cond) {
946          case ISD::SETUGT:
947          case ISD::SETUGE:
948          case ISD::SETEQ: return DAG.getConstant(0, VT);
949          case ISD::SETULT:
950          case ISD::SETULE:
951          case ISD::SETNE: return DAG.getConstant(1, VT);
952          case ISD::SETGT:
953          case ISD::SETGE:
954            // True if the sign bit of C1 is set.
955            return DAG.getConstant((C1 & (1ULL << (VSize-1))) != 0, VT);
956          case ISD::SETLT:
957          case ISD::SETLE:
958            // True if the sign bit of C1 isn't set.
959            return DAG.getConstant((C1 & (1ULL << (VSize-1))) == 0, VT);
960          default:
961            break;
962          }
963        }
964
965        // Otherwise, we can perform the comparison with the low bits.
966        switch (Cond) {
967        case ISD::SETEQ:
968        case ISD::SETNE:
969        case ISD::SETUGT:
970        case ISD::SETUGE:
971        case ISD::SETULT:
972        case ISD::SETULE:
973          return DAG.getSetCC(VT, N0.getOperand(0),
974                          DAG.getConstant(C1, N0.getOperand(0).getValueType()),
975                          Cond);
976        default:
977          break;   // todo, be more careful with signed comparisons
978        }
979      } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
980                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
981        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
982        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
983        MVT::ValueType ExtDstTy = N0.getValueType();
984        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
985
986        // If the extended part has any inconsistent bits, it cannot ever
987        // compare equal.  In other words, they have to be all ones or all
988        // zeros.
989        uint64_t ExtBits =
990          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
991        if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
992          return DAG.getConstant(Cond == ISD::SETNE, VT);
993
994        SDOperand ZextOp;
995        MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
996        if (Op0Ty == ExtSrcTy) {
997          ZextOp = N0.getOperand(0);
998        } else {
999          int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
1000          ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1001                               DAG.getConstant(Imm, Op0Ty));
1002        }
1003        if (!DCI.isCalledByLegalizer())
1004          DCI.AddToWorklist(ZextOp.Val);
1005        // Otherwise, make this a use of a zext.
1006        return DAG.getSetCC(VT, ZextOp,
1007                            DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
1008                                            ExtDstTy),
1009                            Cond);
1010      } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
1011                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1012
1013        // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1014        if (N0.getOpcode() == ISD::SETCC) {
1015          bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1016          if (TrueWhenTrue)
1017            return N0;
1018
1019          // Invert the condition.
1020          ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1021          CC = ISD::getSetCCInverse(CC,
1022                               MVT::isInteger(N0.getOperand(0).getValueType()));
1023          return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1024        }
1025
1026        if ((N0.getOpcode() == ISD::XOR ||
1027             (N0.getOpcode() == ISD::AND &&
1028              N0.getOperand(0).getOpcode() == ISD::XOR &&
1029              N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1030            isa<ConstantSDNode>(N0.getOperand(1)) &&
1031            cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
1032          // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1033          // can only do this if the top bits are known zero.
1034          if (DAG.MaskedValueIsZero(N0,
1035                                    MVT::getIntVTBitMask(N0.getValueType())-1)){
1036            // Okay, get the un-inverted input value.
1037            SDOperand Val;
1038            if (N0.getOpcode() == ISD::XOR)
1039              Val = N0.getOperand(0);
1040            else {
1041              assert(N0.getOpcode() == ISD::AND &&
1042                     N0.getOperand(0).getOpcode() == ISD::XOR);
1043              // ((X^1)&1)^1 -> X & 1
1044              Val = DAG.getNode(ISD::AND, N0.getValueType(),
1045                                N0.getOperand(0).getOperand(0),
1046                                N0.getOperand(1));
1047            }
1048            return DAG.getSetCC(VT, Val, N1,
1049                                Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1050          }
1051        }
1052      }
1053
1054      uint64_t MinVal, MaxVal;
1055      unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
1056      if (ISD::isSignedIntSetCC(Cond)) {
1057        MinVal = 1ULL << (OperandBitSize-1);
1058        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
1059          MaxVal = ~0ULL >> (65-OperandBitSize);
1060        else
1061          MaxVal = 0;
1062      } else {
1063        MinVal = 0;
1064        MaxVal = ~0ULL >> (64-OperandBitSize);
1065      }
1066
1067      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1068      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1069        if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
1070        --C1;                                          // X >= C0 --> X > (C0-1)
1071        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1072                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1073      }
1074
1075      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1076        if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
1077        ++C1;                                          // X <= C0 --> X < (C0+1)
1078        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1079                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1080      }
1081
1082      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1083        return DAG.getConstant(0, VT);      // X < MIN --> false
1084      if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1085        return DAG.getConstant(1, VT);      // X >= MIN --> true
1086      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1087        return DAG.getConstant(0, VT);      // X > MAX --> false
1088      if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1089        return DAG.getConstant(1, VT);      // X <= MAX --> true
1090
1091      // Canonicalize setgt X, Min --> setne X, Min
1092      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1093        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1094      // Canonicalize setlt X, Max --> setne X, Max
1095      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1096        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1097
1098      // If we have setult X, 1, turn it into seteq X, 0
1099      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1100        return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1101                        ISD::SETEQ);
1102      // If we have setugt X, Max-1, turn it into seteq X, Max
1103      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1104        return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1105                        ISD::SETEQ);
1106
1107      // If we have "setcc X, C0", check to see if we can shrink the immediate
1108      // by changing cc.
1109
1110      // SETUGT X, SINTMAX  -> SETLT X, 0
1111      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1112          C1 == (~0ULL >> (65-OperandBitSize)))
1113        return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1114                            ISD::SETLT);
1115
1116      // FIXME: Implement the rest of these.
1117
1118      // Fold bit comparisons when we can.
1119      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1120          VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1121        if (ConstantSDNode *AndRHS =
1122                    dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1123          if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1124            // Perform the xform if the AND RHS is a single bit.
1125            if (isPowerOf2_64(AndRHS->getValue())) {
1126              return DAG.getNode(ISD::SRL, VT, N0,
1127                             DAG.getConstant(Log2_64(AndRHS->getValue()),
1128                                             getShiftAmountTy()));
1129            }
1130          } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1131            // (X & 8) == 8  -->  (X & 8) >> 3
1132            // Perform the xform if C1 is a single bit.
1133            if (isPowerOf2_64(C1)) {
1134              return DAG.getNode(ISD::SRL, VT, N0,
1135                          DAG.getConstant(Log2_64(C1), getShiftAmountTy()));
1136            }
1137          }
1138        }
1139    }
1140  } else if (isa<ConstantSDNode>(N0.Val)) {
1141      // Ensure that the constant occurs on the RHS.
1142    return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1143  }
1144
1145  if (isa<ConstantFPSDNode>(N0.Val)) {
1146    // Constant fold or commute setcc.
1147    SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
1148    if (O.Val) return O;
1149  }
1150
1151  if (N0 == N1) {
1152    // We can always fold X == X for integer setcc's.
1153    if (MVT::isInteger(N0.getValueType()))
1154      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1155    unsigned UOF = ISD::getUnorderedFlavor(Cond);
1156    if (UOF == 2)   // FP operators that are undefined on NaNs.
1157      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1158    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1159      return DAG.getConstant(UOF, VT);
1160    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
1161    // if it is not already.
1162    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1163    if (NewCond != Cond)
1164      return DAG.getSetCC(VT, N0, N1, NewCond);
1165  }
1166
1167  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1168      MVT::isInteger(N0.getValueType())) {
1169    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1170        N0.getOpcode() == ISD::XOR) {
1171      // Simplify (X+Y) == (X+Z) -->  Y == Z
1172      if (N0.getOpcode() == N1.getOpcode()) {
1173        if (N0.getOperand(0) == N1.getOperand(0))
1174          return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1175        if (N0.getOperand(1) == N1.getOperand(1))
1176          return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1177        if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1178          // If X op Y == Y op X, try other combinations.
1179          if (N0.getOperand(0) == N1.getOperand(1))
1180            return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1181          if (N0.getOperand(1) == N1.getOperand(0))
1182            return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1183        }
1184      }
1185
1186      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1187        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1188          // Turn (X+C1) == C2 --> X == C2-C1
1189          if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1190            return DAG.getSetCC(VT, N0.getOperand(0),
1191                              DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1192                                N0.getValueType()), Cond);
1193          }
1194
1195          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1196          if (N0.getOpcode() == ISD::XOR)
1197            // If we know that all of the inverted bits are zero, don't bother
1198            // performing the inversion.
1199            if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
1200              return DAG.getSetCC(VT, N0.getOperand(0),
1201                              DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
1202                                              N0.getValueType()), Cond);
1203        }
1204
1205        // Turn (C1-X) == C2 --> X == C1-C2
1206        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1207          if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
1208            return DAG.getSetCC(VT, N0.getOperand(1),
1209                             DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
1210                                             N0.getValueType()), Cond);
1211          }
1212        }
1213      }
1214
1215      // Simplify (X+Z) == X -->  Z == 0
1216      if (N0.getOperand(0) == N1)
1217        return DAG.getSetCC(VT, N0.getOperand(1),
1218                        DAG.getConstant(0, N0.getValueType()), Cond);
1219      if (N0.getOperand(1) == N1) {
1220        if (DAG.isCommutativeBinOp(N0.getOpcode()))
1221          return DAG.getSetCC(VT, N0.getOperand(0),
1222                          DAG.getConstant(0, N0.getValueType()), Cond);
1223        else if (N0.Val->hasOneUse()) {
1224          assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1225          // (Z-X) == X  --> Z == X<<1
1226          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1227                                     N1,
1228                                     DAG.getConstant(1, getShiftAmountTy()));
1229          if (!DCI.isCalledByLegalizer())
1230            DCI.AddToWorklist(SH.Val);
1231          return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1232        }
1233      }
1234    }
1235
1236    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1237        N1.getOpcode() == ISD::XOR) {
1238      // Simplify  X == (X+Z) -->  Z == 0
1239      if (N1.getOperand(0) == N0) {
1240        return DAG.getSetCC(VT, N1.getOperand(1),
1241                        DAG.getConstant(0, N1.getValueType()), Cond);
1242      } else if (N1.getOperand(1) == N0) {
1243        if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1244          return DAG.getSetCC(VT, N1.getOperand(0),
1245                          DAG.getConstant(0, N1.getValueType()), Cond);
1246        } else if (N1.Val->hasOneUse()) {
1247          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1248          // X == (Z-X)  --> X<<1 == Z
1249          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
1250                                     DAG.getConstant(1, getShiftAmountTy()));
1251          if (!DCI.isCalledByLegalizer())
1252            DCI.AddToWorklist(SH.Val);
1253          return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1254        }
1255      }
1256    }
1257  }
1258
1259  // Fold away ALL boolean setcc's.
1260  SDOperand Temp;
1261  if (N0.getValueType() == MVT::i1 && foldBooleans) {
1262    switch (Cond) {
1263    default: assert(0 && "Unknown integer setcc!");
1264    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
1265      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1266      N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1267      if (!DCI.isCalledByLegalizer())
1268        DCI.AddToWorklist(Temp.Val);
1269      break;
1270    case ISD::SETNE:  // X != Y   -->  (X^Y)
1271      N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1272      break;
1273    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
1274    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
1275      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1276      N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1277      if (!DCI.isCalledByLegalizer())
1278        DCI.AddToWorklist(Temp.Val);
1279      break;
1280    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
1281    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
1282      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1283      N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1284      if (!DCI.isCalledByLegalizer())
1285        DCI.AddToWorklist(Temp.Val);
1286      break;
1287    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
1288    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
1289      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1290      N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1291      if (!DCI.isCalledByLegalizer())
1292        DCI.AddToWorklist(Temp.Val);
1293      break;
1294    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
1295    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
1296      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1297      N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1298      break;
1299    }
1300    if (VT != MVT::i1) {
1301      if (!DCI.isCalledByLegalizer())
1302        DCI.AddToWorklist(N0.Val);
1303      // FIXME: If running after legalize, we probably can't do this.
1304      N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1305    }
1306    return N0;
1307  }
1308
1309  // Could not fold it.
1310  return SDOperand();
1311}
1312
1313SDOperand TargetLowering::
1314PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1315  // Default implementation: no optimization.
1316  return SDOperand();
1317}
1318
1319//===----------------------------------------------------------------------===//
1320//  Inline Assembler Implementation Methods
1321//===----------------------------------------------------------------------===//
1322
1323TargetLowering::ConstraintType
1324TargetLowering::getConstraintType(const std::string &Constraint) const {
1325  // FIXME: lots more standard ones to handle.
1326  if (Constraint.size() == 1) {
1327    switch (Constraint[0]) {
1328    default: break;
1329    case 'r': return C_RegisterClass;
1330    case 'm':    // memory
1331    case 'o':    // offsetable
1332    case 'V':    // not offsetable
1333      return C_Memory;
1334    case 'i':    // Simple Integer or Relocatable Constant
1335    case 'n':    // Simple Integer
1336    case 's':    // Relocatable Constant
1337    case 'X':    // Allow ANY value.
1338    case 'I':    // Target registers.
1339    case 'J':
1340    case 'K':
1341    case 'L':
1342    case 'M':
1343    case 'N':
1344    case 'O':
1345    case 'P':
1346      return C_Other;
1347    }
1348  }
1349
1350  if (Constraint.size() > 1 && Constraint[0] == '{' &&
1351      Constraint[Constraint.size()-1] == '}')
1352    return C_Register;
1353  return C_Unknown;
1354}
1355
1356/// isOperandValidForConstraint - Return the specified operand (possibly
1357/// modified) if the specified SDOperand is valid for the specified target
1358/// constraint letter, otherwise return null.
1359SDOperand TargetLowering::isOperandValidForConstraint(SDOperand Op,
1360                                                      char ConstraintLetter,
1361                                                      SelectionDAG &DAG) {
1362  switch (ConstraintLetter) {
1363  default: break;
1364  case 'i':    // Simple Integer or Relocatable Constant
1365  case 'n':    // Simple Integer
1366  case 's':    // Relocatable Constant
1367  case 'X': {  // Allows any operand.
1368    // These operands are interested in values of the form (GV+C), where C may
1369    // be folded in as an offset of GV, or it may be explicitly added.  Also, it
1370    // is possible and fine if either GV or C are missing.
1371    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1372    GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1373
1374    // If we have "(add GV, C)", pull out GV/C
1375    if (Op.getOpcode() == ISD::ADD) {
1376      C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1377      GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1378      if (C == 0 || GA == 0) {
1379        C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1380        GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1381      }
1382      if (C == 0 || GA == 0)
1383        C = 0, GA = 0;
1384    }
1385
1386    // If we find a valid operand, map to the TargetXXX version so that the
1387    // value itself doesn't get selected.
1388    if (GA) {   // Either &GV   or   &GV+C
1389      if (ConstraintLetter != 'n') {
1390        int64_t Offs = GA->getOffset();
1391        if (C) Offs += C->getValue();
1392        return DAG.getTargetGlobalAddress(GA->getGlobal(), Op.getValueType(),
1393                                          Offs);
1394      }
1395    }
1396    if (C) {   // just C, no GV.
1397      // Simple constants are not allowed for 's'.
1398      if (ConstraintLetter != 's')
1399        return DAG.getTargetConstant(C->getValue(), Op.getValueType());
1400    }
1401    break;
1402  }
1403  }
1404  return SDOperand(0,0);
1405}
1406
1407std::vector<unsigned> TargetLowering::
1408getRegClassForInlineAsmConstraint(const std::string &Constraint,
1409                                  MVT::ValueType VT) const {
1410  return std::vector<unsigned>();
1411}
1412
1413
1414std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1415getRegForInlineAsmConstraint(const std::string &Constraint,
1416                             MVT::ValueType VT) const {
1417  if (Constraint[0] != '{')
1418    return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1419  assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1420
1421  // Remove the braces from around the name.
1422  std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1423
1424  // Figure out which register class contains this reg.
1425  const MRegisterInfo *RI = TM.getRegisterInfo();
1426  for (MRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1427       E = RI->regclass_end(); RCI != E; ++RCI) {
1428    const TargetRegisterClass *RC = *RCI;
1429
1430    // If none of the the value types for this register class are valid, we
1431    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1432    bool isLegal = false;
1433    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1434         I != E; ++I) {
1435      if (isTypeLegal(*I)) {
1436        isLegal = true;
1437        break;
1438      }
1439    }
1440
1441    if (!isLegal) continue;
1442
1443    for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1444         I != E; ++I) {
1445      if (StringsEqualNoCase(RegName, RI->get(*I).Name))
1446        return std::make_pair(*I, RC);
1447    }
1448  }
1449
1450  return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1451}
1452
1453//===----------------------------------------------------------------------===//
1454//  Loop Strength Reduction hooks
1455//===----------------------------------------------------------------------===//
1456
1457/// isLegalAddressingMode - Return true if the addressing mode represented
1458/// by AM is legal for this target, for a load/store of the specified type.
1459bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
1460                                           const Type *Ty) const {
1461  // The default implementation of this implements a conservative RISCy, r+r and
1462  // r+i addr mode.
1463
1464  // Allows a sign-extended 16-bit immediate field.
1465  if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1466    return false;
1467
1468  // No global is ever allowed as a base.
1469  if (AM.BaseGV)
1470    return false;
1471
1472  // Only support r+r,
1473  switch (AM.Scale) {
1474  case 0:  // "r+i" or just "i", depending on HasBaseReg.
1475    break;
1476  case 1:
1477    if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1478      return false;
1479    // Otherwise we have r+r or r+i.
1480    break;
1481  case 2:
1482    if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1483      return false;
1484    // Allow 2*r as r+r.
1485    break;
1486  }
1487
1488  return true;
1489}
1490
1491// Magic for divide replacement
1492
1493struct ms {
1494  int64_t m;  // magic number
1495  int64_t s;  // shift amount
1496};
1497
1498struct mu {
1499  uint64_t m; // magic number
1500  int64_t a;  // add indicator
1501  int64_t s;  // shift amount
1502};
1503
1504/// magic - calculate the magic numbers required to codegen an integer sdiv as
1505/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
1506/// or -1.
1507static ms magic32(int32_t d) {
1508  int32_t p;
1509  uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1510  const uint32_t two31 = 0x80000000U;
1511  struct ms mag;
1512
1513  ad = abs(d);
1514  t = two31 + ((uint32_t)d >> 31);
1515  anc = t - 1 - t%ad;   // absolute value of nc
1516  p = 31;               // initialize p
1517  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
1518  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
1519  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
1520  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
1521  do {
1522    p = p + 1;
1523    q1 = 2*q1;        // update q1 = 2p/abs(nc)
1524    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
1525    if (r1 >= anc) {  // must be unsigned comparison
1526      q1 = q1 + 1;
1527      r1 = r1 - anc;
1528    }
1529    q2 = 2*q2;        // update q2 = 2p/abs(d)
1530    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
1531    if (r2 >= ad) {   // must be unsigned comparison
1532      q2 = q2 + 1;
1533      r2 = r2 - ad;
1534    }
1535    delta = ad - r2;
1536  } while (q1 < delta || (q1 == delta && r1 == 0));
1537
1538  mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1539  if (d < 0) mag.m = -mag.m; // resulting magic number
1540  mag.s = p - 32;            // resulting shift
1541  return mag;
1542}
1543
1544/// magicu - calculate the magic numbers required to codegen an integer udiv as
1545/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
1546static mu magicu32(uint32_t d) {
1547  int32_t p;
1548  uint32_t nc, delta, q1, r1, q2, r2;
1549  struct mu magu;
1550  magu.a = 0;               // initialize "add" indicator
1551  nc = - 1 - (-d)%d;
1552  p = 31;                   // initialize p
1553  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
1554  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
1555  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
1556  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
1557  do {
1558    p = p + 1;
1559    if (r1 >= nc - r1 ) {
1560      q1 = 2*q1 + 1;  // update q1
1561      r1 = 2*r1 - nc; // update r1
1562    }
1563    else {
1564      q1 = 2*q1; // update q1
1565      r1 = 2*r1; // update r1
1566    }
1567    if (r2 + 1 >= d - r2) {
1568      if (q2 >= 0x7FFFFFFF) magu.a = 1;
1569      q2 = 2*q2 + 1;     // update q2
1570      r2 = 2*r2 + 1 - d; // update r2
1571    }
1572    else {
1573      if (q2 >= 0x80000000) magu.a = 1;
1574      q2 = 2*q2;     // update q2
1575      r2 = 2*r2 + 1; // update r2
1576    }
1577    delta = d - 1 - r2;
1578  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1579  magu.m = q2 + 1; // resulting magic number
1580  magu.s = p - 32;  // resulting shift
1581  return magu;
1582}
1583
1584/// magic - calculate the magic numbers required to codegen an integer sdiv as
1585/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
1586/// or -1.
1587static ms magic64(int64_t d) {
1588  int64_t p;
1589  uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1590  const uint64_t two63 = 9223372036854775808ULL; // 2^63
1591  struct ms mag;
1592
1593  ad = d >= 0 ? d : -d;
1594  t = two63 + ((uint64_t)d >> 63);
1595  anc = t - 1 - t%ad;   // absolute value of nc
1596  p = 63;               // initialize p
1597  q1 = two63/anc;       // initialize q1 = 2p/abs(nc)
1598  r1 = two63 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
1599  q2 = two63/ad;        // initialize q2 = 2p/abs(d)
1600  r2 = two63 - q2*ad;   // initialize r2 = rem(2p,abs(d))
1601  do {
1602    p = p + 1;
1603    q1 = 2*q1;        // update q1 = 2p/abs(nc)
1604    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
1605    if (r1 >= anc) {  // must be unsigned comparison
1606      q1 = q1 + 1;
1607      r1 = r1 - anc;
1608    }
1609    q2 = 2*q2;        // update q2 = 2p/abs(d)
1610    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
1611    if (r2 >= ad) {   // must be unsigned comparison
1612      q2 = q2 + 1;
1613      r2 = r2 - ad;
1614    }
1615    delta = ad - r2;
1616  } while (q1 < delta || (q1 == delta && r1 == 0));
1617
1618  mag.m = q2 + 1;
1619  if (d < 0) mag.m = -mag.m; // resulting magic number
1620  mag.s = p - 64;            // resulting shift
1621  return mag;
1622}
1623
1624/// magicu - calculate the magic numbers required to codegen an integer udiv as
1625/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
1626static mu magicu64(uint64_t d)
1627{
1628  int64_t p;
1629  uint64_t nc, delta, q1, r1, q2, r2;
1630  struct mu magu;
1631  magu.a = 0;               // initialize "add" indicator
1632  nc = - 1 - (-d)%d;
1633  p = 63;                   // initialize p
1634  q1 = 0x8000000000000000ull/nc;       // initialize q1 = 2p/nc
1635  r1 = 0x8000000000000000ull - q1*nc;  // initialize r1 = rem(2p,nc)
1636  q2 = 0x7FFFFFFFFFFFFFFFull/d;        // initialize q2 = (2p-1)/d
1637  r2 = 0x7FFFFFFFFFFFFFFFull - q2*d;   // initialize r2 = rem((2p-1),d)
1638  do {
1639    p = p + 1;
1640    if (r1 >= nc - r1 ) {
1641      q1 = 2*q1 + 1;  // update q1
1642      r1 = 2*r1 - nc; // update r1
1643    }
1644    else {
1645      q1 = 2*q1; // update q1
1646      r1 = 2*r1; // update r1
1647    }
1648    if (r2 + 1 >= d - r2) {
1649      if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
1650      q2 = 2*q2 + 1;     // update q2
1651      r2 = 2*r2 + 1 - d; // update r2
1652    }
1653    else {
1654      if (q2 >= 0x8000000000000000ull) magu.a = 1;
1655      q2 = 2*q2;     // update q2
1656      r2 = 2*r2 + 1; // update r2
1657    }
1658    delta = d - 1 - r2;
1659  } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
1660  magu.m = q2 + 1; // resulting magic number
1661  magu.s = p - 64;  // resulting shift
1662  return magu;
1663}
1664
1665/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
1666/// return a DAG expression to select that will generate the same value by
1667/// multiplying by a magic number.  See:
1668/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1669SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
1670                                    std::vector<SDNode*>* Created) const {
1671  MVT::ValueType VT = N->getValueType(0);
1672
1673  // Check to see if we can do this.
1674  if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1675    return SDOperand();       // BuildSDIV only operates on i32 or i64
1676  if (!isOperationLegal(ISD::MULHS, VT))
1677    return SDOperand();       // Make sure the target supports MULHS.
1678
1679  int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
1680  ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
1681
1682  // Multiply the numerator (operand 0) by the magic value
1683  SDOperand Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
1684                            DAG.getConstant(magics.m, VT));
1685  // If d > 0 and m < 0, add the numerator
1686  if (d > 0 && magics.m < 0) {
1687    Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
1688    if (Created)
1689      Created->push_back(Q.Val);
1690  }
1691  // If d < 0 and m > 0, subtract the numerator.
1692  if (d < 0 && magics.m > 0) {
1693    Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
1694    if (Created)
1695      Created->push_back(Q.Val);
1696  }
1697  // Shift right algebraic if shift value is nonzero
1698  if (magics.s > 0) {
1699    Q = DAG.getNode(ISD::SRA, VT, Q,
1700                    DAG.getConstant(magics.s, getShiftAmountTy()));
1701    if (Created)
1702      Created->push_back(Q.Val);
1703  }
1704  // Extract the sign bit and add it to the quotient
1705  SDOperand T =
1706    DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
1707                                                 getShiftAmountTy()));
1708  if (Created)
1709    Created->push_back(T.Val);
1710  return DAG.getNode(ISD::ADD, VT, Q, T);
1711}
1712
1713/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
1714/// return a DAG expression to select that will generate the same value by
1715/// multiplying by a magic number.  See:
1716/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1717SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
1718                                    std::vector<SDNode*>* Created) const {
1719  MVT::ValueType VT = N->getValueType(0);
1720
1721  // Check to see if we can do this.
1722  if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1723    return SDOperand();       // BuildUDIV only operates on i32 or i64
1724  if (!isOperationLegal(ISD::MULHU, VT))
1725    return SDOperand();       // Make sure the target supports MULHU.
1726
1727  uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1728  mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
1729
1730  // Multiply the numerator (operand 0) by the magic value
1731  SDOperand Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
1732                            DAG.getConstant(magics.m, VT));
1733  if (Created)
1734    Created->push_back(Q.Val);
1735
1736  if (magics.a == 0) {
1737    return DAG.getNode(ISD::SRL, VT, Q,
1738                       DAG.getConstant(magics.s, getShiftAmountTy()));
1739  } else {
1740    SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
1741    if (Created)
1742      Created->push_back(NPQ.Val);
1743    NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
1744                      DAG.getConstant(1, getShiftAmountTy()));
1745    if (Created)
1746      Created->push_back(NPQ.Val);
1747    NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
1748    if (Created)
1749      Created->push_back(NPQ.Val);
1750    return DAG.getNode(ISD::SRL, VT, NPQ,
1751                       DAG.getConstant(magics.s-1, getShiftAmountTy()));
1752  }
1753}
1754