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