TargetLowering.cpp revision 8783398a4cfee14740a03dfb3084694ce6d23e02
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/TargetAsmInfo.h"
15#include "llvm/Target/TargetLowering.h"
16#include "llvm/Target/TargetSubtarget.h"
17#include "llvm/Target/TargetData.h"
18#include "llvm/Target/TargetMachine.h"
19#include "llvm/Target/TargetRegisterInfo.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/SelectionDAG.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27using namespace llvm;
28
29/// InitLibcallNames - Set default libcall names.
30///
31static void InitLibcallNames(const char **Names) {
32  Names[RTLIB::SHL_I32] = "__ashlsi3";
33  Names[RTLIB::SHL_I64] = "__ashldi3";
34  Names[RTLIB::SHL_I128] = "__ashlti3";
35  Names[RTLIB::SRL_I32] = "__lshrsi3";
36  Names[RTLIB::SRL_I64] = "__lshrdi3";
37  Names[RTLIB::SRL_I128] = "__lshrti3";
38  Names[RTLIB::SRA_I32] = "__ashrsi3";
39  Names[RTLIB::SRA_I64] = "__ashrdi3";
40  Names[RTLIB::SRA_I128] = "__ashrti3";
41  Names[RTLIB::MUL_I32] = "__mulsi3";
42  Names[RTLIB::MUL_I64] = "__muldi3";
43  Names[RTLIB::MUL_I128] = "__multi3";
44  Names[RTLIB::SDIV_I32] = "__divsi3";
45  Names[RTLIB::SDIV_I64] = "__divdi3";
46  Names[RTLIB::SDIV_I128] = "__divti3";
47  Names[RTLIB::UDIV_I32] = "__udivsi3";
48  Names[RTLIB::UDIV_I64] = "__udivdi3";
49  Names[RTLIB::UDIV_I128] = "__udivti3";
50  Names[RTLIB::SREM_I32] = "__modsi3";
51  Names[RTLIB::SREM_I64] = "__moddi3";
52  Names[RTLIB::SREM_I128] = "__modti3";
53  Names[RTLIB::UREM_I32] = "__umodsi3";
54  Names[RTLIB::UREM_I64] = "__umoddi3";
55  Names[RTLIB::UREM_I128] = "__umodti3";
56  Names[RTLIB::NEG_I32] = "__negsi2";
57  Names[RTLIB::NEG_I64] = "__negdi2";
58  Names[RTLIB::ADD_F32] = "__addsf3";
59  Names[RTLIB::ADD_F64] = "__adddf3";
60  Names[RTLIB::ADD_F80] = "__addxf3";
61  Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
62  Names[RTLIB::SUB_F32] = "__subsf3";
63  Names[RTLIB::SUB_F64] = "__subdf3";
64  Names[RTLIB::SUB_F80] = "__subxf3";
65  Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
66  Names[RTLIB::MUL_F32] = "__mulsf3";
67  Names[RTLIB::MUL_F64] = "__muldf3";
68  Names[RTLIB::MUL_F80] = "__mulxf3";
69  Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
70  Names[RTLIB::DIV_F32] = "__divsf3";
71  Names[RTLIB::DIV_F64] = "__divdf3";
72  Names[RTLIB::DIV_F80] = "__divxf3";
73  Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
74  Names[RTLIB::REM_F32] = "fmodf";
75  Names[RTLIB::REM_F64] = "fmod";
76  Names[RTLIB::REM_F80] = "fmodl";
77  Names[RTLIB::REM_PPCF128] = "fmodl";
78  Names[RTLIB::POWI_F32] = "__powisf2";
79  Names[RTLIB::POWI_F64] = "__powidf2";
80  Names[RTLIB::POWI_F80] = "__powixf2";
81  Names[RTLIB::POWI_PPCF128] = "__powitf2";
82  Names[RTLIB::SQRT_F32] = "sqrtf";
83  Names[RTLIB::SQRT_F64] = "sqrt";
84  Names[RTLIB::SQRT_F80] = "sqrtl";
85  Names[RTLIB::SQRT_PPCF128] = "sqrtl";
86  Names[RTLIB::SIN_F32] = "sinf";
87  Names[RTLIB::SIN_F64] = "sin";
88  Names[RTLIB::SIN_F80] = "sinl";
89  Names[RTLIB::SIN_PPCF128] = "sinl";
90  Names[RTLIB::COS_F32] = "cosf";
91  Names[RTLIB::COS_F64] = "cos";
92  Names[RTLIB::COS_F80] = "cosl";
93  Names[RTLIB::COS_PPCF128] = "cosl";
94  Names[RTLIB::POW_F32] = "powf";
95  Names[RTLIB::POW_F64] = "pow";
96  Names[RTLIB::POW_F80] = "powl";
97  Names[RTLIB::POW_PPCF128] = "powl";
98  Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
99  Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
100  Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
101  Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
102  Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
103  Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
104  Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
105  Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti";
106  Names[RTLIB::FPTOSINT_F80_I32] = "__fixxfsi";
107  Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
108  Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti";
109  Names[RTLIB::FPTOSINT_PPCF128_I32] = "__fixtfsi";
110  Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
111  Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti";
112  Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
113  Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
114  Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
115  Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
116  Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
117  Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti";
118  Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
119  Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
120  Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti";
121  Names[RTLIB::FPTOUINT_PPCF128_I32] = "__fixunstfsi";
122  Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
123  Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti";
124  Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
125  Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
126  Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
127  Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
128  Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
129  Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
130  Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
131  Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
132  Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
133  Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
134  Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
135  Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
136  Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
137  Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
138  Names[RTLIB::OEQ_F32] = "__eqsf2";
139  Names[RTLIB::OEQ_F64] = "__eqdf2";
140  Names[RTLIB::UNE_F32] = "__nesf2";
141  Names[RTLIB::UNE_F64] = "__nedf2";
142  Names[RTLIB::OGE_F32] = "__gesf2";
143  Names[RTLIB::OGE_F64] = "__gedf2";
144  Names[RTLIB::OLT_F32] = "__ltsf2";
145  Names[RTLIB::OLT_F64] = "__ltdf2";
146  Names[RTLIB::OLE_F32] = "__lesf2";
147  Names[RTLIB::OLE_F64] = "__ledf2";
148  Names[RTLIB::OGT_F32] = "__gtsf2";
149  Names[RTLIB::OGT_F64] = "__gtdf2";
150  Names[RTLIB::UO_F32] = "__unordsf2";
151  Names[RTLIB::UO_F64] = "__unorddf2";
152  Names[RTLIB::O_F32] = "__unordsf2";
153  Names[RTLIB::O_F64] = "__unorddf2";
154}
155
156/// InitCmpLibcallCCs - Set default comparison libcall CC.
157///
158static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
159  memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
160  CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
161  CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
162  CCs[RTLIB::UNE_F32] = ISD::SETNE;
163  CCs[RTLIB::UNE_F64] = ISD::SETNE;
164  CCs[RTLIB::OGE_F32] = ISD::SETGE;
165  CCs[RTLIB::OGE_F64] = ISD::SETGE;
166  CCs[RTLIB::OLT_F32] = ISD::SETLT;
167  CCs[RTLIB::OLT_F64] = ISD::SETLT;
168  CCs[RTLIB::OLE_F32] = ISD::SETLE;
169  CCs[RTLIB::OLE_F64] = ISD::SETLE;
170  CCs[RTLIB::OGT_F32] = ISD::SETGT;
171  CCs[RTLIB::OGT_F64] = ISD::SETGT;
172  CCs[RTLIB::UO_F32] = ISD::SETNE;
173  CCs[RTLIB::UO_F64] = ISD::SETNE;
174  CCs[RTLIB::O_F32] = ISD::SETEQ;
175  CCs[RTLIB::O_F64] = ISD::SETEQ;
176}
177
178TargetLowering::TargetLowering(TargetMachine &tm)
179  : TM(tm), TD(TM.getTargetData()) {
180  assert(ISD::BUILTIN_OP_END <= OpActionsCapacity &&
181         "Fixed size array in TargetLowering is not large enough!");
182  // All operations default to being supported.
183  memset(OpActions, 0, sizeof(OpActions));
184  memset(LoadXActions, 0, sizeof(LoadXActions));
185  memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
186  memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
187  memset(ConvertActions, 0, sizeof(ConvertActions));
188
189  // Set default actions for various operations.
190  for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
191    // Default all indexed load / store to expand.
192    for (unsigned IM = (unsigned)ISD::PRE_INC;
193         IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
194      setIndexedLoadAction(IM, (MVT::SimpleValueType)VT, Expand);
195      setIndexedStoreAction(IM, (MVT::SimpleValueType)VT, Expand);
196    }
197
198    // These operations default to expand.
199    setOperationAction(ISD::FGETSIGN, (MVT::SimpleValueType)VT, Expand);
200  }
201
202  // Most targets ignore the @llvm.prefetch intrinsic.
203  setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
204
205  // ConstantFP nodes default to expand.  Targets can either change this to
206  // Legal, in which case all fp constants are legal, or use addLegalFPImmediate
207  // to optimize expansions for certain constants.
208  setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
209  setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
210  setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
211
212  // Default ISD::TRAP to expand (which turns it into abort).
213  setOperationAction(ISD::TRAP, MVT::Other, Expand);
214
215  IsLittleEndian = TD->isLittleEndian();
216  UsesGlobalOffsetTable = false;
217  ShiftAmountTy = PointerTy = getValueType(TD->getIntPtrType());
218  ShiftAmtHandling = Undefined;
219  memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
220  memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
221  maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
222  allowUnalignedMemoryAccesses = false;
223  UseUnderscoreSetJmp = false;
224  UseUnderscoreLongJmp = false;
225  SelectIsExpensive = false;
226  IntDivIsCheap = false;
227  Pow2DivIsCheap = false;
228  StackPointerRegisterToSaveRestore = 0;
229  ExceptionPointerRegister = 0;
230  ExceptionSelectorRegister = 0;
231  SetCCResultContents = UndefinedSetCCResult;
232  SchedPreferenceInfo = SchedulingForLatency;
233  JumpBufSize = 0;
234  JumpBufAlignment = 0;
235  IfCvtBlockSizeLimit = 2;
236  IfCvtDupBlockSizeLimit = 0;
237  PrefLoopAlignment = 0;
238
239  InitLibcallNames(LibcallRoutineNames);
240  InitCmpLibcallCCs(CmpLibcallCCs);
241
242  // Tell Legalize whether the assembler supports DEBUG_LOC.
243  if (!TM.getTargetAsmInfo()->hasDotLocAndDotFile())
244    setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
245}
246
247TargetLowering::~TargetLowering() {}
248
249/// computeRegisterProperties - Once all of the register classes are added,
250/// this allows us to compute derived properties we expose.
251void TargetLowering::computeRegisterProperties() {
252  assert(MVT::LAST_VALUETYPE <= 32 &&
253         "Too many value types for ValueTypeActions to hold!");
254
255  // Everything defaults to needing one register.
256  for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
257    NumRegistersForVT[i] = 1;
258    RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
259  }
260  // ...except isVoid, which doesn't need any registers.
261  NumRegistersForVT[MVT::isVoid] = 0;
262
263  // Find the largest integer register class.
264  unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
265  for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
266    assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
267
268  // Every integer value type larger than this largest register takes twice as
269  // many registers to represent as the previous ValueType.
270  for (unsigned ExpandedReg = LargestIntReg + 1; ; ++ExpandedReg) {
271    MVT EVT = (MVT::SimpleValueType)ExpandedReg;
272    if (!EVT.isInteger())
273      break;
274    NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
275    RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
276    TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
277    ValueTypeActions.setTypeAction(EVT, Expand);
278  }
279
280  // Inspect all of the ValueType's smaller than the largest integer
281  // register to see which ones need promotion.
282  unsigned LegalIntReg = LargestIntReg;
283  for (unsigned IntReg = LargestIntReg - 1;
284       IntReg >= (unsigned)MVT::i1; --IntReg) {
285    MVT IVT = (MVT::SimpleValueType)IntReg;
286    if (isTypeLegal(IVT)) {
287      LegalIntReg = IntReg;
288    } else {
289      RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
290        (MVT::SimpleValueType)LegalIntReg;
291      ValueTypeActions.setTypeAction(IVT, Promote);
292    }
293  }
294
295  // ppcf128 type is really two f64's.
296  if (!isTypeLegal(MVT::ppcf128)) {
297    NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
298    RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
299    TransformToType[MVT::ppcf128] = MVT::f64;
300    ValueTypeActions.setTypeAction(MVT::ppcf128, Expand);
301  }
302
303  // Decide how to handle f64. If the target does not have native f64 support,
304  // expand it to i64 and we will be generating soft float library calls.
305  if (!isTypeLegal(MVT::f64)) {
306    NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
307    RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
308    TransformToType[MVT::f64] = MVT::i64;
309    ValueTypeActions.setTypeAction(MVT::f64, Expand);
310  }
311
312  // Decide how to handle f32. If the target does not have native support for
313  // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
314  if (!isTypeLegal(MVT::f32)) {
315    if (isTypeLegal(MVT::f64)) {
316      NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
317      RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
318      TransformToType[MVT::f32] = MVT::f64;
319      ValueTypeActions.setTypeAction(MVT::f32, Promote);
320    } else {
321      NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
322      RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
323      TransformToType[MVT::f32] = MVT::i32;
324      ValueTypeActions.setTypeAction(MVT::f32, Expand);
325    }
326  }
327
328  // Loop over all of the vector value types to see which need transformations.
329  for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
330       i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
331    MVT VT = (MVT::SimpleValueType)i;
332    if (!isTypeLegal(VT)) {
333      MVT IntermediateVT, RegisterVT;
334      unsigned NumIntermediates;
335      NumRegistersForVT[i] =
336        getVectorTypeBreakdown(VT,
337                               IntermediateVT, NumIntermediates,
338                               RegisterVT);
339      RegisterTypeForVT[i] = RegisterVT;
340      TransformToType[i] = MVT::Other; // this isn't actually used
341      ValueTypeActions.setTypeAction(VT, Expand);
342    }
343  }
344}
345
346const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
347  return NULL;
348}
349
350
351MVT TargetLowering::getSetCCResultType(const SDOperand &) const {
352  return getValueType(TD->getIntPtrType());
353}
354
355
356/// getVectorTypeBreakdown - Vector types are broken down into some number of
357/// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
358/// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
359/// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
360///
361/// This method returns the number of registers needed, and the VT for each
362/// register.  It also returns the VT and quantity of the intermediate values
363/// before they are promoted/expanded.
364///
365unsigned TargetLowering::getVectorTypeBreakdown(MVT VT,
366                                                MVT &IntermediateVT,
367                                                unsigned &NumIntermediates,
368                                      MVT &RegisterVT) const {
369  // Figure out the right, legal destination reg to copy into.
370  unsigned NumElts = VT.getVectorNumElements();
371  MVT EltTy = VT.getVectorElementType();
372
373  unsigned NumVectorRegs = 1;
374
375  // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
376  // could break down into LHS/RHS like LegalizeDAG does.
377  if (!isPowerOf2_32(NumElts)) {
378    NumVectorRegs = NumElts;
379    NumElts = 1;
380  }
381
382  // Divide the input until we get to a supported size.  This will always
383  // end with a scalar if the target doesn't support vectors.
384  while (NumElts > 1 && !isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
385    NumElts >>= 1;
386    NumVectorRegs <<= 1;
387  }
388
389  NumIntermediates = NumVectorRegs;
390
391  MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
392  if (!isTypeLegal(NewVT))
393    NewVT = EltTy;
394  IntermediateVT = NewVT;
395
396  MVT DestVT = getTypeToTransformTo(NewVT);
397  RegisterVT = DestVT;
398  if (DestVT.bitsLT(NewVT)) {
399    // Value is expanded, e.g. i64 -> i16.
400    return NumVectorRegs*(NewVT.getSizeInBits()/DestVT.getSizeInBits());
401  } else {
402    // Otherwise, promotion or legal types use the same number of registers as
403    // the vector decimated to the appropriate level.
404    return NumVectorRegs;
405  }
406
407  return 1;
408}
409
410/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
411/// function arguments in the caller parameter area.  This is the actual
412/// alignment, not its logarithm.
413unsigned TargetLowering::getByValTypeAlignment(const Type *Ty) const {
414  return TD->getCallFrameTypeAlignment(Ty);
415}
416
417SDOperand TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
418                                                   SelectionDAG &DAG) const {
419  if (usesGlobalOffsetTable())
420    return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
421  return Table;
422}
423
424//===----------------------------------------------------------------------===//
425//  Optimization Methods
426//===----------------------------------------------------------------------===//
427
428/// ShrinkDemandedConstant - Check to see if the specified operand of the
429/// specified instruction is a constant integer.  If so, check to see if there
430/// are any bits set in the constant that are not demanded.  If so, shrink the
431/// constant and return true.
432bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op,
433                                                        const APInt &Demanded) {
434  // FIXME: ISD::SELECT, ISD::SELECT_CC
435  switch(Op.getOpcode()) {
436  default: break;
437  case ISD::AND:
438  case ISD::OR:
439  case ISD::XOR:
440    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
441      if (C->getAPIntValue().intersects(~Demanded)) {
442        MVT VT = Op.getValueType();
443        SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
444                                    DAG.getConstant(Demanded &
445                                                      C->getAPIntValue(),
446                                                    VT));
447        return CombineTo(Op, New);
448      }
449    break;
450  }
451  return false;
452}
453
454/// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
455/// DemandedMask bits of the result of Op are ever used downstream.  If we can
456/// use this information to simplify Op, create a new simplified DAG node and
457/// return true, returning the original and new nodes in Old and New. Otherwise,
458/// analyze the expression and return a mask of KnownOne and KnownZero bits for
459/// the expression (used to simplify the caller).  The KnownZero/One bits may
460/// only be accurate for those bits in the DemandedMask.
461bool TargetLowering::SimplifyDemandedBits(SDOperand Op,
462                                          const APInt &DemandedMask,
463                                          APInt &KnownZero,
464                                          APInt &KnownOne,
465                                          TargetLoweringOpt &TLO,
466                                          unsigned Depth) const {
467  unsigned BitWidth = DemandedMask.getBitWidth();
468  assert(Op.getValueSizeInBits() == BitWidth &&
469         "Mask size mismatches value type size!");
470  APInt NewMask = DemandedMask;
471
472  // Don't know anything.
473  KnownZero = KnownOne = APInt(BitWidth, 0);
474
475  // Other users may use these bits.
476  if (!Op.Val->hasOneUse()) {
477    if (Depth != 0) {
478      // If not at the root, Just compute the KnownZero/KnownOne bits to
479      // simplify things downstream.
480      TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
481      return false;
482    }
483    // If this is the root being simplified, allow it to have multiple uses,
484    // just set the NewMask to all bits.
485    NewMask = APInt::getAllOnesValue(BitWidth);
486  } else if (DemandedMask == 0) {
487    // Not demanding any bits from Op.
488    if (Op.getOpcode() != ISD::UNDEF)
489      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
490    return false;
491  } else if (Depth == 6) {        // Limit search depth.
492    return false;
493  }
494
495  APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
496  switch (Op.getOpcode()) {
497  case ISD::Constant:
498    // We know all of the bits for a constant!
499    KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
500    KnownZero = ~KnownOne & NewMask;
501    return false;   // Don't fall through, will infinitely loop.
502  case ISD::AND:
503    // If the RHS is a constant, check to see if the LHS would be zero without
504    // using the bits from the RHS.  Below, we use knowledge about the RHS to
505    // simplify the LHS, here we're using information from the LHS to simplify
506    // the RHS.
507    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
508      APInt LHSZero, LHSOne;
509      TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
510                                LHSZero, LHSOne, Depth+1);
511      // If the LHS already has zeros where RHSC does, this and is dead.
512      if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
513        return TLO.CombineTo(Op, Op.getOperand(0));
514      // If any of the set bits in the RHS are known zero on the LHS, shrink
515      // the constant.
516      if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
517        return true;
518    }
519
520    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
521                             KnownOne, TLO, Depth+1))
522      return true;
523    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
524    if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
525                             KnownZero2, KnownOne2, TLO, Depth+1))
526      return true;
527    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
528
529    // If all of the demanded bits are known one on one side, return the other.
530    // These bits cannot contribute to the result of the 'and'.
531    if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
532      return TLO.CombineTo(Op, Op.getOperand(0));
533    if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
534      return TLO.CombineTo(Op, Op.getOperand(1));
535    // If all of the demanded bits in the inputs are known zeros, return zero.
536    if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
537      return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
538    // If the RHS is a constant, see if we can simplify it.
539    if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
540      return true;
541
542    // Output known-1 bits are only known if set in both the LHS & RHS.
543    KnownOne &= KnownOne2;
544    // Output known-0 are known to be clear if zero in either the LHS | RHS.
545    KnownZero |= KnownZero2;
546    break;
547  case ISD::OR:
548    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
549                             KnownOne, TLO, Depth+1))
550      return true;
551    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
552    if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
553                             KnownZero2, KnownOne2, TLO, Depth+1))
554      return true;
555    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
556
557    // If all of the demanded bits are known zero on one side, return the other.
558    // These bits cannot contribute to the result of the 'or'.
559    if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
560      return TLO.CombineTo(Op, Op.getOperand(0));
561    if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
562      return TLO.CombineTo(Op, Op.getOperand(1));
563    // If all of the potentially set bits on one side are known to be set on
564    // the other side, just use the 'other' side.
565    if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
566      return TLO.CombineTo(Op, Op.getOperand(0));
567    if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
568      return TLO.CombineTo(Op, Op.getOperand(1));
569    // If the RHS is a constant, see if we can simplify it.
570    if (TLO.ShrinkDemandedConstant(Op, NewMask))
571      return true;
572
573    // Output known-0 bits are only known if clear in both the LHS & RHS.
574    KnownZero &= KnownZero2;
575    // Output known-1 are known to be set if set in either the LHS | RHS.
576    KnownOne |= KnownOne2;
577    break;
578  case ISD::XOR:
579    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
580                             KnownOne, TLO, Depth+1))
581      return true;
582    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
583    if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
584                             KnownOne2, TLO, Depth+1))
585      return true;
586    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
587
588    // If all of the demanded bits are known zero on one side, return the other.
589    // These bits cannot contribute to the result of the 'xor'.
590    if ((KnownZero & NewMask) == NewMask)
591      return TLO.CombineTo(Op, Op.getOperand(0));
592    if ((KnownZero2 & NewMask) == NewMask)
593      return TLO.CombineTo(Op, Op.getOperand(1));
594
595    // If all of the unknown bits are known to be zero on one side or the other
596    // (but not both) turn this into an *inclusive* or.
597    //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
598    if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
599      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
600                                               Op.getOperand(0),
601                                               Op.getOperand(1)));
602
603    // Output known-0 bits are known if clear or set in both the LHS & RHS.
604    KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
605    // Output known-1 are known to be set if set in only one of the LHS, RHS.
606    KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
607
608    // If all of the demanded bits on one side are known, and all of the set
609    // bits on that side are also known to be set on the other side, turn this
610    // into an AND, as we know the bits will be cleared.
611    //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
612    if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known
613      if ((KnownOne & KnownOne2) == KnownOne) {
614        MVT VT = Op.getValueType();
615        SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
616        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
617                                                 ANDC));
618      }
619    }
620
621    // If the RHS is a constant, see if we can simplify it.
622    // for XOR, we prefer to force bits to 1 if they will make a -1.
623    // if we can't force bits, try to shrink constant
624    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
625      APInt Expanded = C->getAPIntValue() | (~NewMask);
626      // if we can expand it to have all bits set, do it
627      if (Expanded.isAllOnesValue()) {
628        if (Expanded != C->getAPIntValue()) {
629          MVT VT = Op.getValueType();
630          SDOperand New = TLO.DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
631                                          TLO.DAG.getConstant(Expanded, VT));
632          return TLO.CombineTo(Op, New);
633        }
634        // if it already has all the bits set, nothing to change
635        // but don't shrink either!
636      } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
637        return true;
638      }
639    }
640
641    KnownZero = KnownZeroOut;
642    KnownOne  = KnownOneOut;
643    break;
644  case ISD::SELECT:
645    if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
646                             KnownOne, TLO, Depth+1))
647      return true;
648    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
649                             KnownOne2, TLO, Depth+1))
650      return true;
651    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
652    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
653
654    // If the operands are constants, see if we can simplify them.
655    if (TLO.ShrinkDemandedConstant(Op, NewMask))
656      return true;
657
658    // Only known if known in both the LHS and RHS.
659    KnownOne &= KnownOne2;
660    KnownZero &= KnownZero2;
661    break;
662  case ISD::SELECT_CC:
663    if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
664                             KnownOne, TLO, Depth+1))
665      return true;
666    if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
667                             KnownOne2, TLO, Depth+1))
668      return true;
669    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672    // If the operands are constants, see if we can simplify them.
673    if (TLO.ShrinkDemandedConstant(Op, NewMask))
674      return true;
675
676    // Only known if known in both the LHS and RHS.
677    KnownOne &= KnownOne2;
678    KnownZero &= KnownZero2;
679    break;
680  case ISD::SHL:
681    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
682      unsigned ShAmt = SA->getValue();
683      SDOperand InOp = Op.getOperand(0);
684
685      // If the shift count is an invalid immediate, don't do anything.
686      if (ShAmt >= BitWidth)
687        break;
688
689      // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
690      // single shift.  We can do this if the bottom bits (which are shifted
691      // out) are never demanded.
692      if (InOp.getOpcode() == ISD::SRL &&
693          isa<ConstantSDNode>(InOp.getOperand(1))) {
694        if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
695          unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
696          unsigned Opc = ISD::SHL;
697          int Diff = ShAmt-C1;
698          if (Diff < 0) {
699            Diff = -Diff;
700            Opc = ISD::SRL;
701          }
702
703          SDOperand NewSA =
704            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
705          MVT VT = Op.getValueType();
706          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
707                                                   InOp.getOperand(0), NewSA));
708        }
709      }
710
711      if (SimplifyDemandedBits(Op.getOperand(0), NewMask.lshr(ShAmt),
712                               KnownZero, KnownOne, TLO, Depth+1))
713        return true;
714      KnownZero <<= SA->getValue();
715      KnownOne  <<= SA->getValue();
716      // low bits known zero.
717      KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getValue());
718    }
719    break;
720  case ISD::SRL:
721    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
722      MVT VT = Op.getValueType();
723      unsigned ShAmt = SA->getValue();
724      unsigned VTSize = VT.getSizeInBits();
725      SDOperand InOp = Op.getOperand(0);
726
727      // If the shift count is an invalid immediate, don't do anything.
728      if (ShAmt >= BitWidth)
729        break;
730
731      // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
732      // single shift.  We can do this if the top bits (which are shifted out)
733      // are never demanded.
734      if (InOp.getOpcode() == ISD::SHL &&
735          isa<ConstantSDNode>(InOp.getOperand(1))) {
736        if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
737          unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
738          unsigned Opc = ISD::SRL;
739          int Diff = ShAmt-C1;
740          if (Diff < 0) {
741            Diff = -Diff;
742            Opc = ISD::SHL;
743          }
744
745          SDOperand NewSA =
746            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
747          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
748                                                   InOp.getOperand(0), NewSA));
749        }
750      }
751
752      // Compute the new bits that are at the top now.
753      if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
754                               KnownZero, KnownOne, TLO, Depth+1))
755        return true;
756      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757      KnownZero = KnownZero.lshr(ShAmt);
758      KnownOne  = KnownOne.lshr(ShAmt);
759
760      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
761      KnownZero |= HighBits;  // High bits known zero.
762    }
763    break;
764  case ISD::SRA:
765    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
766      MVT VT = Op.getValueType();
767      unsigned ShAmt = SA->getValue();
768
769      // If the shift count is an invalid immediate, don't do anything.
770      if (ShAmt >= BitWidth)
771        break;
772
773      APInt InDemandedMask = (NewMask << ShAmt);
774
775      // If any of the demanded bits are produced by the sign extension, we also
776      // demand the input sign bit.
777      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
778      if (HighBits.intersects(NewMask))
779        InDemandedMask |= APInt::getSignBit(VT.getSizeInBits());
780
781      if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
782                               KnownZero, KnownOne, TLO, Depth+1))
783        return true;
784      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
785      KnownZero = KnownZero.lshr(ShAmt);
786      KnownOne  = KnownOne.lshr(ShAmt);
787
788      // Handle the sign bit, adjusted to where it is now in the mask.
789      APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
790
791      // If the input sign bit is known to be zero, or if none of the top bits
792      // are demanded, turn this into an unsigned shift right.
793      if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
794        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
795                                                 Op.getOperand(1)));
796      } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
797        KnownOne |= HighBits;
798      }
799    }
800    break;
801  case ISD::SIGN_EXTEND_INREG: {
802    MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
803
804    // Sign extension.  Compute the demanded bits in the result that are not
805    // present in the input.
806    APInt NewBits = APInt::getHighBitsSet(BitWidth,
807                                          BitWidth - EVT.getSizeInBits()) &
808                    NewMask;
809
810    // If none of the extended bits are demanded, eliminate the sextinreg.
811    if (NewBits == 0)
812      return TLO.CombineTo(Op, Op.getOperand(0));
813
814    APInt InSignBit = APInt::getSignBit(EVT.getSizeInBits());
815    InSignBit.zext(BitWidth);
816    APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth,
817                                                   EVT.getSizeInBits()) &
818                              NewMask;
819
820    // Since the sign extended bits are demanded, we know that the sign
821    // bit is demanded.
822    InputDemandedBits |= InSignBit;
823
824    if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
825                             KnownZero, KnownOne, TLO, Depth+1))
826      return true;
827    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
828
829    // If the sign bit of the input is known set or clear, then we know the
830    // top bits of the result.
831
832    // If the input sign bit is known zero, convert this into a zero extension.
833    if (KnownZero.intersects(InSignBit))
834      return TLO.CombineTo(Op,
835                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
836
837    if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
838      KnownOne |= NewBits;
839      KnownZero &= ~NewBits;
840    } else {                       // Input sign bit unknown
841      KnownZero &= ~NewBits;
842      KnownOne &= ~NewBits;
843    }
844    break;
845  }
846  case ISD::ZERO_EXTEND: {
847    unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits();
848    APInt InMask = NewMask;
849    InMask.trunc(OperandBitWidth);
850
851    // If none of the top bits are demanded, convert this into an any_extend.
852    APInt NewBits =
853      APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
854    if (!NewBits.intersects(NewMask))
855      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND,
856                                               Op.getValueType(),
857                                               Op.getOperand(0)));
858
859    if (SimplifyDemandedBits(Op.getOperand(0), InMask,
860                             KnownZero, KnownOne, TLO, Depth+1))
861      return true;
862    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
863    KnownZero.zext(BitWidth);
864    KnownOne.zext(BitWidth);
865    KnownZero |= NewBits;
866    break;
867  }
868  case ISD::SIGN_EXTEND: {
869    MVT InVT = Op.getOperand(0).getValueType();
870    unsigned InBits = InVT.getSizeInBits();
871    APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
872    APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
873    APInt NewBits   = ~InMask & NewMask;
874
875    // If none of the top bits are demanded, convert this into an any_extend.
876    if (NewBits == 0)
877      return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
878                                           Op.getOperand(0)));
879
880    // Since some of the sign extended bits are demanded, we know that the sign
881    // bit is demanded.
882    APInt InDemandedBits = InMask & NewMask;
883    InDemandedBits |= InSignBit;
884    InDemandedBits.trunc(InBits);
885
886    if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
887                             KnownOne, TLO, Depth+1))
888      return true;
889    KnownZero.zext(BitWidth);
890    KnownOne.zext(BitWidth);
891
892    // If the sign bit is known zero, convert this to a zero extend.
893    if (KnownZero.intersects(InSignBit))
894      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND,
895                                               Op.getValueType(),
896                                               Op.getOperand(0)));
897
898    // If the sign bit is known one, the top bits match.
899    if (KnownOne.intersects(InSignBit)) {
900      KnownOne  |= NewBits;
901      KnownZero &= ~NewBits;
902    } else {   // Otherwise, top bits aren't known.
903      KnownOne  &= ~NewBits;
904      KnownZero &= ~NewBits;
905    }
906    break;
907  }
908  case ISD::ANY_EXTEND: {
909    unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits();
910    APInt InMask = NewMask;
911    InMask.trunc(OperandBitWidth);
912    if (SimplifyDemandedBits(Op.getOperand(0), InMask,
913                             KnownZero, KnownOne, TLO, Depth+1))
914      return true;
915    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
916    KnownZero.zext(BitWidth);
917    KnownOne.zext(BitWidth);
918    break;
919  }
920  case ISD::TRUNCATE: {
921    // Simplify the input, using demanded bit information, and compute the known
922    // zero/one bits live out.
923    APInt TruncMask = NewMask;
924    TruncMask.zext(Op.getOperand(0).getValueSizeInBits());
925    if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
926                             KnownZero, KnownOne, TLO, Depth+1))
927      return true;
928    KnownZero.trunc(BitWidth);
929    KnownOne.trunc(BitWidth);
930
931    // If the input is only used by this truncate, see if we can shrink it based
932    // on the known demanded bits.
933    if (Op.getOperand(0).Val->hasOneUse()) {
934      SDOperand In = Op.getOperand(0);
935      unsigned InBitWidth = In.getValueSizeInBits();
936      switch (In.getOpcode()) {
937      default: break;
938      case ISD::SRL:
939        // Shrink SRL by a constant if none of the high bits shifted in are
940        // demanded.
941        if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
942          APInt HighBits = APInt::getHighBitsSet(InBitWidth,
943                                                 InBitWidth - BitWidth);
944          HighBits = HighBits.lshr(ShAmt->getValue());
945          HighBits.trunc(BitWidth);
946
947          if (ShAmt->getValue() < BitWidth && !(HighBits & NewMask)) {
948            // None of the shifted in bits are needed.  Add a truncate of the
949            // shift input, then shift it.
950            SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE,
951                                                 Op.getValueType(),
952                                                 In.getOperand(0));
953            return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
954                                                   NewTrunc, In.getOperand(1)));
955          }
956        }
957        break;
958      }
959    }
960
961    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
962    break;
963  }
964  case ISD::AssertZext: {
965    MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
966    APInt InMask = APInt::getLowBitsSet(BitWidth,
967                                        VT.getSizeInBits());
968    if (SimplifyDemandedBits(Op.getOperand(0), InMask & NewMask,
969                             KnownZero, KnownOne, TLO, Depth+1))
970      return true;
971    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
972    KnownZero |= ~InMask & NewMask;
973    break;
974  }
975  case ISD::BIT_CONVERT:
976#if 0
977    // If this is an FP->Int bitcast and if the sign bit is the only thing that
978    // is demanded, turn this into a FGETSIGN.
979    if (NewMask == MVT::getIntegerVTSignBit(Op.getValueType()) &&
980        MVT::isFloatingPoint(Op.getOperand(0).getValueType()) &&
981        !MVT::isVector(Op.getOperand(0).getValueType())) {
982      // Only do this xform if FGETSIGN is valid or if before legalize.
983      if (!TLO.AfterLegalize ||
984          isOperationLegal(ISD::FGETSIGN, Op.getValueType())) {
985        // Make a FGETSIGN + SHL to move the sign bit into the appropriate
986        // place.  We expect the SHL to be eliminated by other optimizations.
987        SDOperand Sign = TLO.DAG.getNode(ISD::FGETSIGN, Op.getValueType(),
988                                         Op.getOperand(0));
989        unsigned ShVal = Op.getValueType().getSizeInBits()-1;
990        SDOperand ShAmt = TLO.DAG.getConstant(ShVal, getShiftAmountTy());
991        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, Op.getValueType(),
992                                                 Sign, ShAmt));
993      }
994    }
995#endif
996    break;
997  default:
998    // Just use ComputeMaskedBits to compute output bits.
999    TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
1000    break;
1001  }
1002
1003  // If we know the value of all of the demanded bits, return this as a
1004  // constant.
1005  if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1006    return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1007
1008  return false;
1009}
1010
1011/// computeMaskedBitsForTargetNode - Determine which of the bits specified
1012/// in Mask are known to be either zero or one and return them in the
1013/// KnownZero/KnownOne bitsets.
1014void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
1015                                                    const APInt &Mask,
1016                                                    APInt &KnownZero,
1017                                                    APInt &KnownOne,
1018                                                    const SelectionDAG &DAG,
1019                                                    unsigned Depth) const {
1020  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1021          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1022          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1023          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1024         "Should use MaskedValueIsZero if you don't know whether Op"
1025         " is a target node!");
1026  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1027}
1028
1029/// ComputeNumSignBitsForTargetNode - This method can be implemented by
1030/// targets that want to expose additional information about sign bits to the
1031/// DAG Combiner.
1032unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
1033                                                         unsigned Depth) const {
1034  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1035          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1036          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1037          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1038         "Should use ComputeNumSignBits if you don't know whether Op"
1039         " is a target node!");
1040  return 1;
1041}
1042
1043
1044/// SimplifySetCC - Try to simplify a setcc built with the specified operands
1045/// and cc. If it is unable to simplify it, return a null SDOperand.
1046SDOperand
1047TargetLowering::SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
1048                              ISD::CondCode Cond, bool foldBooleans,
1049                              DAGCombinerInfo &DCI) const {
1050  SelectionDAG &DAG = DCI.DAG;
1051
1052  // These setcc operations always fold.
1053  switch (Cond) {
1054  default: break;
1055  case ISD::SETFALSE:
1056  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1057  case ISD::SETTRUE:
1058  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
1059  }
1060
1061  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1062    const APInt &C1 = N1C->getAPIntValue();
1063    if (isa<ConstantSDNode>(N0.Val)) {
1064      return DAG.FoldSetCC(VT, N0, N1, Cond);
1065    } else {
1066      // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1067      // equality comparison, then we're just comparing whether X itself is
1068      // zero.
1069      if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1070          N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1071          N0.getOperand(1).getOpcode() == ISD::Constant) {
1072        unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1073        if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1074            ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1075          if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1076            // (srl (ctlz x), 5) == 0  -> X != 0
1077            // (srl (ctlz x), 5) != 1  -> X != 0
1078            Cond = ISD::SETNE;
1079          } else {
1080            // (srl (ctlz x), 5) != 0  -> X == 0
1081            // (srl (ctlz x), 5) == 1  -> X == 0
1082            Cond = ISD::SETEQ;
1083          }
1084          SDOperand Zero = DAG.getConstant(0, N0.getValueType());
1085          return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
1086                              Zero, Cond);
1087        }
1088      }
1089
1090      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1091      if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1092        unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1093
1094        // If the comparison constant has bits in the upper part, the
1095        // zero-extended value could never match.
1096        if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1097                                                C1.getBitWidth() - InSize))) {
1098          switch (Cond) {
1099          case ISD::SETUGT:
1100          case ISD::SETUGE:
1101          case ISD::SETEQ: return DAG.getConstant(0, VT);
1102          case ISD::SETULT:
1103          case ISD::SETULE:
1104          case ISD::SETNE: return DAG.getConstant(1, VT);
1105          case ISD::SETGT:
1106          case ISD::SETGE:
1107            // True if the sign bit of C1 is set.
1108            return DAG.getConstant(C1.isNegative(), VT);
1109          case ISD::SETLT:
1110          case ISD::SETLE:
1111            // True if the sign bit of C1 isn't set.
1112            return DAG.getConstant(C1.isNonNegative(), VT);
1113          default:
1114            break;
1115          }
1116        }
1117
1118        // Otherwise, we can perform the comparison with the low bits.
1119        switch (Cond) {
1120        case ISD::SETEQ:
1121        case ISD::SETNE:
1122        case ISD::SETUGT:
1123        case ISD::SETUGE:
1124        case ISD::SETULT:
1125        case ISD::SETULE:
1126          return DAG.getSetCC(VT, N0.getOperand(0),
1127                          DAG.getConstant(APInt(C1).trunc(InSize),
1128                                          N0.getOperand(0).getValueType()),
1129                          Cond);
1130        default:
1131          break;   // todo, be more careful with signed comparisons
1132        }
1133      } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1134                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1135        MVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1136        unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1137        MVT ExtDstTy = N0.getValueType();
1138        unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1139
1140        // If the extended part has any inconsistent bits, it cannot ever
1141        // compare equal.  In other words, they have to be all ones or all
1142        // zeros.
1143        APInt ExtBits =
1144          APInt::getHighBitsSet(ExtDstTyBits, ExtDstTyBits - ExtSrcTyBits);
1145        if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1146          return DAG.getConstant(Cond == ISD::SETNE, VT);
1147
1148        SDOperand ZextOp;
1149        MVT Op0Ty = N0.getOperand(0).getValueType();
1150        if (Op0Ty == ExtSrcTy) {
1151          ZextOp = N0.getOperand(0);
1152        } else {
1153          APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1154          ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1155                               DAG.getConstant(Imm, Op0Ty));
1156        }
1157        if (!DCI.isCalledByLegalizer())
1158          DCI.AddToWorklist(ZextOp.Val);
1159        // Otherwise, make this a use of a zext.
1160        return DAG.getSetCC(VT, ZextOp,
1161                            DAG.getConstant(C1 & APInt::getLowBitsSet(
1162                                                               ExtDstTyBits,
1163                                                               ExtSrcTyBits),
1164                                            ExtDstTy),
1165                            Cond);
1166      } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1167                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1168
1169        // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1170        if (N0.getOpcode() == ISD::SETCC) {
1171          bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1172          if (TrueWhenTrue)
1173            return N0;
1174
1175          // Invert the condition.
1176          ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1177          CC = ISD::getSetCCInverse(CC,
1178                                   N0.getOperand(0).getValueType().isInteger());
1179          return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1180        }
1181
1182        if ((N0.getOpcode() == ISD::XOR ||
1183             (N0.getOpcode() == ISD::AND &&
1184              N0.getOperand(0).getOpcode() == ISD::XOR &&
1185              N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1186            isa<ConstantSDNode>(N0.getOperand(1)) &&
1187            cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1188          // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1189          // can only do this if the top bits are known zero.
1190          unsigned BitWidth = N0.getValueSizeInBits();
1191          if (DAG.MaskedValueIsZero(N0,
1192                                    APInt::getHighBitsSet(BitWidth,
1193                                                          BitWidth-1))) {
1194            // Okay, get the un-inverted input value.
1195            SDOperand Val;
1196            if (N0.getOpcode() == ISD::XOR)
1197              Val = N0.getOperand(0);
1198            else {
1199              assert(N0.getOpcode() == ISD::AND &&
1200                     N0.getOperand(0).getOpcode() == ISD::XOR);
1201              // ((X^1)&1)^1 -> X & 1
1202              Val = DAG.getNode(ISD::AND, N0.getValueType(),
1203                                N0.getOperand(0).getOperand(0),
1204                                N0.getOperand(1));
1205            }
1206            return DAG.getSetCC(VT, Val, N1,
1207                                Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1208          }
1209        }
1210      }
1211
1212      APInt MinVal, MaxVal;
1213      unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1214      if (ISD::isSignedIntSetCC(Cond)) {
1215        MinVal = APInt::getSignedMinValue(OperandBitSize);
1216        MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1217      } else {
1218        MinVal = APInt::getMinValue(OperandBitSize);
1219        MaxVal = APInt::getMaxValue(OperandBitSize);
1220      }
1221
1222      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1223      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1224        if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
1225        // X >= C0 --> X > (C0-1)
1226        return DAG.getSetCC(VT, N0, DAG.getConstant(C1-1, N1.getValueType()),
1227                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1228      }
1229
1230      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1231        if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
1232        // X <= C0 --> X < (C0+1)
1233        return DAG.getSetCC(VT, N0, DAG.getConstant(C1+1, N1.getValueType()),
1234                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1235      }
1236
1237      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1238        return DAG.getConstant(0, VT);      // X < MIN --> false
1239      if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1240        return DAG.getConstant(1, VT);      // X >= MIN --> true
1241      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1242        return DAG.getConstant(0, VT);      // X > MAX --> false
1243      if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1244        return DAG.getConstant(1, VT);      // X <= MAX --> true
1245
1246      // Canonicalize setgt X, Min --> setne X, Min
1247      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1248        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1249      // Canonicalize setlt X, Max --> setne X, Max
1250      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1251        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1252
1253      // If we have setult X, 1, turn it into seteq X, 0
1254      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1255        return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1256                        ISD::SETEQ);
1257      // If we have setugt X, Max-1, turn it into seteq X, Max
1258      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1259        return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1260                        ISD::SETEQ);
1261
1262      // If we have "setcc X, C0", check to see if we can shrink the immediate
1263      // by changing cc.
1264
1265      // SETUGT X, SINTMAX  -> SETLT X, 0
1266      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1267          C1 == (~0ULL >> (65-OperandBitSize)))
1268        return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1269                            ISD::SETLT);
1270
1271      // FIXME: Implement the rest of these.
1272
1273      // Fold bit comparisons when we can.
1274      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1275          VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1276        if (ConstantSDNode *AndRHS =
1277                    dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1278          if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1279            // Perform the xform if the AND RHS is a single bit.
1280            if (isPowerOf2_64(AndRHS->getValue())) {
1281              return DAG.getNode(ISD::SRL, VT, N0,
1282                             DAG.getConstant(Log2_64(AndRHS->getValue()),
1283                                             getShiftAmountTy()));
1284            }
1285          } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1286            // (X & 8) == 8  -->  (X & 8) >> 3
1287            // Perform the xform if C1 is a single bit.
1288            if (C1.isPowerOf2()) {
1289              return DAG.getNode(ISD::SRL, VT, N0,
1290                          DAG.getConstant(C1.logBase2(), getShiftAmountTy()));
1291            }
1292          }
1293        }
1294    }
1295  } else if (isa<ConstantSDNode>(N0.Val)) {
1296      // Ensure that the constant occurs on the RHS.
1297    return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1298  }
1299
1300  if (isa<ConstantFPSDNode>(N0.Val)) {
1301    // Constant fold or commute setcc.
1302    SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
1303    if (O.Val) return O;
1304  } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1305    // If the RHS of an FP comparison is a constant, simplify it away in
1306    // some cases.
1307    if (CFP->getValueAPF().isNaN()) {
1308      // If an operand is known to be a nan, we can fold it.
1309      switch (ISD::getUnorderedFlavor(Cond)) {
1310      default: assert(0 && "Unknown flavor!");
1311      case 0:  // Known false.
1312        return DAG.getConstant(0, VT);
1313      case 1:  // Known true.
1314        return DAG.getConstant(1, VT);
1315      case 2:  // Undefined.
1316        return DAG.getNode(ISD::UNDEF, VT);
1317      }
1318    }
1319
1320    // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
1321    // constant if knowing that the operand is non-nan is enough.  We prefer to
1322    // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1323    // materialize 0.0.
1324    if (Cond == ISD::SETO || Cond == ISD::SETUO)
1325      return DAG.getSetCC(VT, N0, N0, Cond);
1326  }
1327
1328  if (N0 == N1) {
1329    // We can always fold X == X for integer setcc's.
1330    if (N0.getValueType().isInteger())
1331      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1332    unsigned UOF = ISD::getUnorderedFlavor(Cond);
1333    if (UOF == 2)   // FP operators that are undefined on NaNs.
1334      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1335    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1336      return DAG.getConstant(UOF, VT);
1337    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
1338    // if it is not already.
1339    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1340    if (NewCond != Cond)
1341      return DAG.getSetCC(VT, N0, N1, NewCond);
1342  }
1343
1344  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1345      N0.getValueType().isInteger()) {
1346    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1347        N0.getOpcode() == ISD::XOR) {
1348      // Simplify (X+Y) == (X+Z) -->  Y == Z
1349      if (N0.getOpcode() == N1.getOpcode()) {
1350        if (N0.getOperand(0) == N1.getOperand(0))
1351          return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1352        if (N0.getOperand(1) == N1.getOperand(1))
1353          return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1354        if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1355          // If X op Y == Y op X, try other combinations.
1356          if (N0.getOperand(0) == N1.getOperand(1))
1357            return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1358          if (N0.getOperand(1) == N1.getOperand(0))
1359            return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1360        }
1361      }
1362
1363      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1364        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1365          // Turn (X+C1) == C2 --> X == C2-C1
1366          if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1367            return DAG.getSetCC(VT, N0.getOperand(0),
1368                              DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1369                                N0.getValueType()), Cond);
1370          }
1371
1372          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1373          if (N0.getOpcode() == ISD::XOR)
1374            // If we know that all of the inverted bits are zero, don't bother
1375            // performing the inversion.
1376            if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1377              return
1378                DAG.getSetCC(VT, N0.getOperand(0),
1379                             DAG.getConstant(LHSR->getAPIntValue() ^
1380                                               RHSC->getAPIntValue(),
1381                                             N0.getValueType()),
1382                             Cond);
1383        }
1384
1385        // Turn (C1-X) == C2 --> X == C1-C2
1386        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1387          if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
1388            return
1389              DAG.getSetCC(VT, N0.getOperand(1),
1390                           DAG.getConstant(SUBC->getAPIntValue() -
1391                                             RHSC->getAPIntValue(),
1392                                           N0.getValueType()),
1393                           Cond);
1394          }
1395        }
1396      }
1397
1398      // Simplify (X+Z) == X -->  Z == 0
1399      if (N0.getOperand(0) == N1)
1400        return DAG.getSetCC(VT, N0.getOperand(1),
1401                        DAG.getConstant(0, N0.getValueType()), Cond);
1402      if (N0.getOperand(1) == N1) {
1403        if (DAG.isCommutativeBinOp(N0.getOpcode()))
1404          return DAG.getSetCC(VT, N0.getOperand(0),
1405                          DAG.getConstant(0, N0.getValueType()), Cond);
1406        else if (N0.Val->hasOneUse()) {
1407          assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1408          // (Z-X) == X  --> Z == X<<1
1409          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1410                                     N1,
1411                                     DAG.getConstant(1, getShiftAmountTy()));
1412          if (!DCI.isCalledByLegalizer())
1413            DCI.AddToWorklist(SH.Val);
1414          return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1415        }
1416      }
1417    }
1418
1419    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1420        N1.getOpcode() == ISD::XOR) {
1421      // Simplify  X == (X+Z) -->  Z == 0
1422      if (N1.getOperand(0) == N0) {
1423        return DAG.getSetCC(VT, N1.getOperand(1),
1424                        DAG.getConstant(0, N1.getValueType()), Cond);
1425      } else if (N1.getOperand(1) == N0) {
1426        if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1427          return DAG.getSetCC(VT, N1.getOperand(0),
1428                          DAG.getConstant(0, N1.getValueType()), Cond);
1429        } else if (N1.Val->hasOneUse()) {
1430          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1431          // X == (Z-X)  --> X<<1 == Z
1432          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
1433                                     DAG.getConstant(1, getShiftAmountTy()));
1434          if (!DCI.isCalledByLegalizer())
1435            DCI.AddToWorklist(SH.Val);
1436          return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1437        }
1438      }
1439    }
1440  }
1441
1442  // Fold away ALL boolean setcc's.
1443  SDOperand Temp;
1444  if (N0.getValueType() == MVT::i1 && foldBooleans) {
1445    switch (Cond) {
1446    default: assert(0 && "Unknown integer setcc!");
1447    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
1448      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1449      N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1450      if (!DCI.isCalledByLegalizer())
1451        DCI.AddToWorklist(Temp.Val);
1452      break;
1453    case ISD::SETNE:  // X != Y   -->  (X^Y)
1454      N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1455      break;
1456    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
1457    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
1458      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1459      N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1460      if (!DCI.isCalledByLegalizer())
1461        DCI.AddToWorklist(Temp.Val);
1462      break;
1463    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
1464    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
1465      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1466      N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1467      if (!DCI.isCalledByLegalizer())
1468        DCI.AddToWorklist(Temp.Val);
1469      break;
1470    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
1471    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
1472      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1473      N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1474      if (!DCI.isCalledByLegalizer())
1475        DCI.AddToWorklist(Temp.Val);
1476      break;
1477    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
1478    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
1479      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1480      N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1481      break;
1482    }
1483    if (VT != MVT::i1) {
1484      if (!DCI.isCalledByLegalizer())
1485        DCI.AddToWorklist(N0.Val);
1486      // FIXME: If running after legalize, we probably can't do this.
1487      N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1488    }
1489    return N0;
1490  }
1491
1492  // Could not fold it.
1493  return SDOperand();
1494}
1495
1496/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
1497/// node is a GlobalAddress + offset.
1498bool TargetLowering::isGAPlusOffset(SDNode *N, GlobalValue* &GA,
1499                                    int64_t &Offset) const {
1500  if (isa<GlobalAddressSDNode>(N)) {
1501    GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
1502    GA = GASD->getGlobal();
1503    Offset += GASD->getOffset();
1504    return true;
1505  }
1506
1507  if (N->getOpcode() == ISD::ADD) {
1508    SDOperand N1 = N->getOperand(0);
1509    SDOperand N2 = N->getOperand(1);
1510    if (isGAPlusOffset(N1.Val, GA, Offset)) {
1511      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
1512      if (V) {
1513        Offset += V->getSignExtended();
1514        return true;
1515      }
1516    } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
1517      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
1518      if (V) {
1519        Offset += V->getSignExtended();
1520        return true;
1521      }
1522    }
1523  }
1524  return false;
1525}
1526
1527
1528/// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is
1529/// loading 'Bytes' bytes from a location that is 'Dist' units away from the
1530/// location that the 'Base' load is loading from.
1531bool TargetLowering::isConsecutiveLoad(SDNode *LD, SDNode *Base,
1532                                       unsigned Bytes, int Dist,
1533                                       const MachineFrameInfo *MFI) const {
1534  if (LD->getOperand(0).Val != Base->getOperand(0).Val)
1535    return false;
1536  MVT VT = LD->getValueType(0);
1537  if (VT.getSizeInBits() / 8 != Bytes)
1538    return false;
1539
1540  SDOperand Loc = LD->getOperand(1);
1541  SDOperand BaseLoc = Base->getOperand(1);
1542  if (Loc.getOpcode() == ISD::FrameIndex) {
1543    if (BaseLoc.getOpcode() != ISD::FrameIndex)
1544      return false;
1545    int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
1546    int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
1547    int FS  = MFI->getObjectSize(FI);
1548    int BFS = MFI->getObjectSize(BFI);
1549    if (FS != BFS || FS != (int)Bytes) return false;
1550    return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
1551  }
1552
1553  GlobalValue *GV1 = NULL;
1554  GlobalValue *GV2 = NULL;
1555  int64_t Offset1 = 0;
1556  int64_t Offset2 = 0;
1557  bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
1558  bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
1559  if (isGA1 && isGA2 && GV1 == GV2)
1560    return Offset1 == (Offset2 + Dist*Bytes);
1561  return false;
1562}
1563
1564
1565SDOperand TargetLowering::
1566PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1567  // Default implementation: no optimization.
1568  return SDOperand();
1569}
1570
1571//===----------------------------------------------------------------------===//
1572//  Inline Assembler Implementation Methods
1573//===----------------------------------------------------------------------===//
1574
1575
1576TargetLowering::ConstraintType
1577TargetLowering::getConstraintType(const std::string &Constraint) const {
1578  // FIXME: lots more standard ones to handle.
1579  if (Constraint.size() == 1) {
1580    switch (Constraint[0]) {
1581    default: break;
1582    case 'r': return C_RegisterClass;
1583    case 'm':    // memory
1584    case 'o':    // offsetable
1585    case 'V':    // not offsetable
1586      return C_Memory;
1587    case 'i':    // Simple Integer or Relocatable Constant
1588    case 'n':    // Simple Integer
1589    case 's':    // Relocatable Constant
1590    case 'X':    // Allow ANY value.
1591    case 'I':    // Target registers.
1592    case 'J':
1593    case 'K':
1594    case 'L':
1595    case 'M':
1596    case 'N':
1597    case 'O':
1598    case 'P':
1599      return C_Other;
1600    }
1601  }
1602
1603  if (Constraint.size() > 1 && Constraint[0] == '{' &&
1604      Constraint[Constraint.size()-1] == '}')
1605    return C_Register;
1606  return C_Unknown;
1607}
1608
1609/// LowerXConstraint - try to replace an X constraint, which matches anything,
1610/// with another that has more specific requirements based on the type of the
1611/// corresponding operand.
1612const char *TargetLowering::LowerXConstraint(MVT ConstraintVT) const{
1613  if (ConstraintVT.isInteger())
1614    return "r";
1615  if (ConstraintVT.isFloatingPoint())
1616    return "f";      // works for many targets
1617  return 0;
1618}
1619
1620/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1621/// vector.  If it is invalid, don't add anything to Ops.
1622void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
1623                                                  char ConstraintLetter,
1624                                                  std::vector<SDOperand> &Ops,
1625                                                  SelectionDAG &DAG) const {
1626  switch (ConstraintLetter) {
1627  default: break;
1628  case 'X':     // Allows any operand; labels (basic block) use this.
1629    if (Op.getOpcode() == ISD::BasicBlock) {
1630      Ops.push_back(Op);
1631      return;
1632    }
1633    // fall through
1634  case 'i':    // Simple Integer or Relocatable Constant
1635  case 'n':    // Simple Integer
1636  case 's': {  // Relocatable Constant
1637    // These operands are interested in values of the form (GV+C), where C may
1638    // be folded in as an offset of GV, or it may be explicitly added.  Also, it
1639    // is possible and fine if either GV or C are missing.
1640    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1641    GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1642
1643    // If we have "(add GV, C)", pull out GV/C
1644    if (Op.getOpcode() == ISD::ADD) {
1645      C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1646      GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1647      if (C == 0 || GA == 0) {
1648        C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1649        GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1650      }
1651      if (C == 0 || GA == 0)
1652        C = 0, GA = 0;
1653    }
1654
1655    // If we find a valid operand, map to the TargetXXX version so that the
1656    // value itself doesn't get selected.
1657    if (GA) {   // Either &GV   or   &GV+C
1658      if (ConstraintLetter != 'n') {
1659        int64_t Offs = GA->getOffset();
1660        if (C) Offs += C->getValue();
1661        Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1662                                                 Op.getValueType(), Offs));
1663        return;
1664      }
1665    }
1666    if (C) {   // just C, no GV.
1667      // Simple constants are not allowed for 's'.
1668      if (ConstraintLetter != 's') {
1669        Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType()));
1670        return;
1671      }
1672    }
1673    break;
1674  }
1675  }
1676}
1677
1678std::vector<unsigned> TargetLowering::
1679getRegClassForInlineAsmConstraint(const std::string &Constraint,
1680                                  MVT VT) const {
1681  return std::vector<unsigned>();
1682}
1683
1684
1685std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1686getRegForInlineAsmConstraint(const std::string &Constraint,
1687                             MVT VT) const {
1688  if (Constraint[0] != '{')
1689    return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1690  assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1691
1692  // Remove the braces from around the name.
1693  std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1694
1695  // Figure out which register class contains this reg.
1696  const TargetRegisterInfo *RI = TM.getRegisterInfo();
1697  for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1698       E = RI->regclass_end(); RCI != E; ++RCI) {
1699    const TargetRegisterClass *RC = *RCI;
1700
1701    // If none of the the value types for this register class are valid, we
1702    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1703    bool isLegal = false;
1704    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1705         I != E; ++I) {
1706      if (isTypeLegal(*I)) {
1707        isLegal = true;
1708        break;
1709      }
1710    }
1711
1712    if (!isLegal) continue;
1713
1714    for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1715         I != E; ++I) {
1716      if (StringsEqualNoCase(RegName, RI->get(*I).AsmName))
1717        return std::make_pair(*I, RC);
1718    }
1719  }
1720
1721  return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1722}
1723
1724//===----------------------------------------------------------------------===//
1725// Constraint Selection.
1726
1727/// getConstraintGenerality - Return an integer indicating how general CT
1728/// is.
1729static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
1730  switch (CT) {
1731  default: assert(0 && "Unknown constraint type!");
1732  case TargetLowering::C_Other:
1733  case TargetLowering::C_Unknown:
1734    return 0;
1735  case TargetLowering::C_Register:
1736    return 1;
1737  case TargetLowering::C_RegisterClass:
1738    return 2;
1739  case TargetLowering::C_Memory:
1740    return 3;
1741  }
1742}
1743
1744/// ChooseConstraint - If there are multiple different constraints that we
1745/// could pick for this operand (e.g. "imr") try to pick the 'best' one.
1746/// This is somewhat tricky: constraints fall into four classes:
1747///    Other         -> immediates and magic values
1748///    Register      -> one specific register
1749///    RegisterClass -> a group of regs
1750///    Memory        -> memory
1751/// Ideally, we would pick the most specific constraint possible: if we have
1752/// something that fits into a register, we would pick it.  The problem here
1753/// is that if we have something that could either be in a register or in
1754/// memory that use of the register could cause selection of *other*
1755/// operands to fail: they might only succeed if we pick memory.  Because of
1756/// this the heuristic we use is:
1757///
1758///  1) If there is an 'other' constraint, and if the operand is valid for
1759///     that constraint, use it.  This makes us take advantage of 'i'
1760///     constraints when available.
1761///  2) Otherwise, pick the most general constraint present.  This prefers
1762///     'm' over 'r', for example.
1763///
1764static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
1765                             const TargetLowering &TLI,
1766                             SDOperand Op, SelectionDAG *DAG) {
1767  assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
1768  unsigned BestIdx = 0;
1769  TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
1770  int BestGenerality = -1;
1771
1772  // Loop over the options, keeping track of the most general one.
1773  for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
1774    TargetLowering::ConstraintType CType =
1775      TLI.getConstraintType(OpInfo.Codes[i]);
1776
1777    // If this is an 'other' constraint, see if the operand is valid for it.
1778    // For example, on X86 we might have an 'rI' constraint.  If the operand
1779    // is an integer in the range [0..31] we want to use I (saving a load
1780    // of a register), otherwise we must use 'r'.
1781    if (CType == TargetLowering::C_Other && Op.Val) {
1782      assert(OpInfo.Codes[i].size() == 1 &&
1783             "Unhandled multi-letter 'other' constraint");
1784      std::vector<SDOperand> ResultOps;
1785      TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i][0],
1786                                       ResultOps, *DAG);
1787      if (!ResultOps.empty()) {
1788        BestType = CType;
1789        BestIdx = i;
1790        break;
1791      }
1792    }
1793
1794    // This constraint letter is more general than the previous one, use it.
1795    int Generality = getConstraintGenerality(CType);
1796    if (Generality > BestGenerality) {
1797      BestType = CType;
1798      BestIdx = i;
1799      BestGenerality = Generality;
1800    }
1801  }
1802
1803  OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
1804  OpInfo.ConstraintType = BestType;
1805}
1806
1807/// ComputeConstraintToUse - Determines the constraint code and constraint
1808/// type to use for the specific AsmOperandInfo, setting
1809/// OpInfo.ConstraintCode and OpInfo.ConstraintType.
1810void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1811                                            SDOperand Op,
1812                                            SelectionDAG *DAG) const {
1813  assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
1814
1815  // Single-letter constraints ('r') are very common.
1816  if (OpInfo.Codes.size() == 1) {
1817    OpInfo.ConstraintCode = OpInfo.Codes[0];
1818    OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
1819  } else {
1820    ChooseConstraint(OpInfo, *this, Op, DAG);
1821  }
1822
1823  // 'X' matches anything.
1824  if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
1825    // Labels and constants are handled elsewhere ('X' is the only thing
1826    // that matches labels).
1827    if (isa<BasicBlock>(OpInfo.CallOperandVal) ||
1828        isa<ConstantInt>(OpInfo.CallOperandVal))
1829      return;
1830
1831    // Otherwise, try to resolve it to something we know about by looking at
1832    // the actual operand type.
1833    if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
1834      OpInfo.ConstraintCode = Repl;
1835      OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
1836    }
1837  }
1838}
1839
1840//===----------------------------------------------------------------------===//
1841//  Loop Strength Reduction hooks
1842//===----------------------------------------------------------------------===//
1843
1844/// isLegalAddressingMode - Return true if the addressing mode represented
1845/// by AM is legal for this target, for a load/store of the specified type.
1846bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
1847                                           const Type *Ty) const {
1848  // The default implementation of this implements a conservative RISCy, r+r and
1849  // r+i addr mode.
1850
1851  // Allows a sign-extended 16-bit immediate field.
1852  if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1853    return false;
1854
1855  // No global is ever allowed as a base.
1856  if (AM.BaseGV)
1857    return false;
1858
1859  // Only support r+r,
1860  switch (AM.Scale) {
1861  case 0:  // "r+i" or just "i", depending on HasBaseReg.
1862    break;
1863  case 1:
1864    if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1865      return false;
1866    // Otherwise we have r+r or r+i.
1867    break;
1868  case 2:
1869    if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1870      return false;
1871    // Allow 2*r as r+r.
1872    break;
1873  }
1874
1875  return true;
1876}
1877
1878// Magic for divide replacement
1879
1880struct ms {
1881  int64_t m;  // magic number
1882  int64_t s;  // shift amount
1883};
1884
1885struct mu {
1886  uint64_t m; // magic number
1887  int64_t a;  // add indicator
1888  int64_t s;  // shift amount
1889};
1890
1891/// magic - calculate the magic numbers required to codegen an integer sdiv as
1892/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
1893/// or -1.
1894static ms magic32(int32_t d) {
1895  int32_t p;
1896  uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1897  const uint32_t two31 = 0x80000000U;
1898  struct ms mag;
1899
1900  ad = abs(d);
1901  t = two31 + ((uint32_t)d >> 31);
1902  anc = t - 1 - t%ad;   // absolute value of nc
1903  p = 31;               // initialize p
1904  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
1905  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
1906  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
1907  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
1908  do {
1909    p = p + 1;
1910    q1 = 2*q1;        // update q1 = 2p/abs(nc)
1911    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
1912    if (r1 >= anc) {  // must be unsigned comparison
1913      q1 = q1 + 1;
1914      r1 = r1 - anc;
1915    }
1916    q2 = 2*q2;        // update q2 = 2p/abs(d)
1917    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
1918    if (r2 >= ad) {   // must be unsigned comparison
1919      q2 = q2 + 1;
1920      r2 = r2 - ad;
1921    }
1922    delta = ad - r2;
1923  } while (q1 < delta || (q1 == delta && r1 == 0));
1924
1925  mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1926  if (d < 0) mag.m = -mag.m; // resulting magic number
1927  mag.s = p - 32;            // resulting shift
1928  return mag;
1929}
1930
1931/// magicu - calculate the magic numbers required to codegen an integer udiv as
1932/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
1933static mu magicu32(uint32_t d) {
1934  int32_t p;
1935  uint32_t nc, delta, q1, r1, q2, r2;
1936  struct mu magu;
1937  magu.a = 0;               // initialize "add" indicator
1938  nc = - 1 - (-d)%d;
1939  p = 31;                   // initialize p
1940  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
1941  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
1942  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
1943  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
1944  do {
1945    p = p + 1;
1946    if (r1 >= nc - r1 ) {
1947      q1 = 2*q1 + 1;  // update q1
1948      r1 = 2*r1 - nc; // update r1
1949    }
1950    else {
1951      q1 = 2*q1; // update q1
1952      r1 = 2*r1; // update r1
1953    }
1954    if (r2 + 1 >= d - r2) {
1955      if (q2 >= 0x7FFFFFFF) magu.a = 1;
1956      q2 = 2*q2 + 1;     // update q2
1957      r2 = 2*r2 + 1 - d; // update r2
1958    }
1959    else {
1960      if (q2 >= 0x80000000) magu.a = 1;
1961      q2 = 2*q2;     // update q2
1962      r2 = 2*r2 + 1; // update r2
1963    }
1964    delta = d - 1 - r2;
1965  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1966  magu.m = q2 + 1; // resulting magic number
1967  magu.s = p - 32;  // resulting shift
1968  return magu;
1969}
1970
1971/// magic - calculate the magic numbers required to codegen an integer sdiv as
1972/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
1973/// or -1.
1974static ms magic64(int64_t d) {
1975  int64_t p;
1976  uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1977  const uint64_t two63 = 9223372036854775808ULL; // 2^63
1978  struct ms mag;
1979
1980  ad = d >= 0 ? d : -d;
1981  t = two63 + ((uint64_t)d >> 63);
1982  anc = t - 1 - t%ad;   // absolute value of nc
1983  p = 63;               // initialize p
1984  q1 = two63/anc;       // initialize q1 = 2p/abs(nc)
1985  r1 = two63 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
1986  q2 = two63/ad;        // initialize q2 = 2p/abs(d)
1987  r2 = two63 - q2*ad;   // initialize r2 = rem(2p,abs(d))
1988  do {
1989    p = p + 1;
1990    q1 = 2*q1;        // update q1 = 2p/abs(nc)
1991    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
1992    if (r1 >= anc) {  // must be unsigned comparison
1993      q1 = q1 + 1;
1994      r1 = r1 - anc;
1995    }
1996    q2 = 2*q2;        // update q2 = 2p/abs(d)
1997    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
1998    if (r2 >= ad) {   // must be unsigned comparison
1999      q2 = q2 + 1;
2000      r2 = r2 - ad;
2001    }
2002    delta = ad - r2;
2003  } while (q1 < delta || (q1 == delta && r1 == 0));
2004
2005  mag.m = q2 + 1;
2006  if (d < 0) mag.m = -mag.m; // resulting magic number
2007  mag.s = p - 64;            // resulting shift
2008  return mag;
2009}
2010
2011/// magicu - calculate the magic numbers required to codegen an integer udiv as
2012/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
2013static mu magicu64(uint64_t d)
2014{
2015  int64_t p;
2016  uint64_t nc, delta, q1, r1, q2, r2;
2017  struct mu magu;
2018  magu.a = 0;               // initialize "add" indicator
2019  nc = - 1 - (-d)%d;
2020  p = 63;                   // initialize p
2021  q1 = 0x8000000000000000ull/nc;       // initialize q1 = 2p/nc
2022  r1 = 0x8000000000000000ull - q1*nc;  // initialize r1 = rem(2p,nc)
2023  q2 = 0x7FFFFFFFFFFFFFFFull/d;        // initialize q2 = (2p-1)/d
2024  r2 = 0x7FFFFFFFFFFFFFFFull - q2*d;   // initialize r2 = rem((2p-1),d)
2025  do {
2026    p = p + 1;
2027    if (r1 >= nc - r1 ) {
2028      q1 = 2*q1 + 1;  // update q1
2029      r1 = 2*r1 - nc; // update r1
2030    }
2031    else {
2032      q1 = 2*q1; // update q1
2033      r1 = 2*r1; // update r1
2034    }
2035    if (r2 + 1 >= d - r2) {
2036      if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
2037      q2 = 2*q2 + 1;     // update q2
2038      r2 = 2*r2 + 1 - d; // update r2
2039    }
2040    else {
2041      if (q2 >= 0x8000000000000000ull) magu.a = 1;
2042      q2 = 2*q2;     // update q2
2043      r2 = 2*r2 + 1; // update r2
2044    }
2045    delta = d - 1 - r2;
2046  } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
2047  magu.m = q2 + 1; // resulting magic number
2048  magu.s = p - 64;  // resulting shift
2049  return magu;
2050}
2051
2052/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
2053/// return a DAG expression to select that will generate the same value by
2054/// multiplying by a magic number.  See:
2055/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2056SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
2057                                    std::vector<SDNode*>* Created) const {
2058  MVT VT = N->getValueType(0);
2059
2060  // Check to see if we can do this.
2061  if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
2062    return SDOperand();       // BuildSDIV only operates on i32 or i64
2063
2064  int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
2065  ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
2066
2067  // Multiply the numerator (operand 0) by the magic value
2068  SDOperand Q;
2069  if (isOperationLegal(ISD::MULHS, VT))
2070    Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
2071                    DAG.getConstant(magics.m, VT));
2072  else if (isOperationLegal(ISD::SMUL_LOHI, VT))
2073    Q = SDOperand(DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(VT, VT),
2074                              N->getOperand(0),
2075                              DAG.getConstant(magics.m, VT)).Val, 1);
2076  else
2077    return SDOperand();       // No mulhs or equvialent
2078  // If d > 0 and m < 0, add the numerator
2079  if (d > 0 && magics.m < 0) {
2080    Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
2081    if (Created)
2082      Created->push_back(Q.Val);
2083  }
2084  // If d < 0 and m > 0, subtract the numerator.
2085  if (d < 0 && magics.m > 0) {
2086    Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
2087    if (Created)
2088      Created->push_back(Q.Val);
2089  }
2090  // Shift right algebraic if shift value is nonzero
2091  if (magics.s > 0) {
2092    Q = DAG.getNode(ISD::SRA, VT, Q,
2093                    DAG.getConstant(magics.s, getShiftAmountTy()));
2094    if (Created)
2095      Created->push_back(Q.Val);
2096  }
2097  // Extract the sign bit and add it to the quotient
2098  SDOperand T =
2099    DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
2100                                                 getShiftAmountTy()));
2101  if (Created)
2102    Created->push_back(T.Val);
2103  return DAG.getNode(ISD::ADD, VT, Q, T);
2104}
2105
2106/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
2107/// return a DAG expression to select that will generate the same value by
2108/// multiplying by a magic number.  See:
2109/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2110SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
2111                                    std::vector<SDNode*>* Created) const {
2112  MVT VT = N->getValueType(0);
2113
2114  // Check to see if we can do this.
2115  if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
2116    return SDOperand();       // BuildUDIV only operates on i32 or i64
2117
2118  uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
2119  mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
2120
2121  // Multiply the numerator (operand 0) by the magic value
2122  SDOperand Q;
2123  if (isOperationLegal(ISD::MULHU, VT))
2124    Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
2125                    DAG.getConstant(magics.m, VT));
2126  else if (isOperationLegal(ISD::UMUL_LOHI, VT))
2127    Q = SDOperand(DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(VT, VT),
2128                              N->getOperand(0),
2129                              DAG.getConstant(magics.m, VT)).Val, 1);
2130  else
2131    return SDOperand();       // No mulhu or equvialent
2132  if (Created)
2133    Created->push_back(Q.Val);
2134
2135  if (magics.a == 0) {
2136    return DAG.getNode(ISD::SRL, VT, Q,
2137                       DAG.getConstant(magics.s, getShiftAmountTy()));
2138  } else {
2139    SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
2140    if (Created)
2141      Created->push_back(NPQ.Val);
2142    NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
2143                      DAG.getConstant(1, getShiftAmountTy()));
2144    if (Created)
2145      Created->push_back(NPQ.Val);
2146    NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
2147    if (Created)
2148      Created->push_back(NPQ.Val);
2149    return DAG.getNode(ISD::SRL, VT, NPQ,
2150                       DAG.getConstant(magics.s-1, getShiftAmountTy()));
2151  }
2152}
2153