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