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