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