Misc. SSE2 intrinsics: clflush, lfench, mfence
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "PPCTargetMachine.h"
16 #include "llvm/ADT/VectorExtras.h"
17 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SSARegMap.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetOptions.h"
28 using namespace llvm;
29
30 PPCTargetLowering::PPCTargetLowering(TargetMachine &TM)
31   : TargetLowering(TM) {
32     
33   // Fold away setcc operations if possible.
34   setSetCCIsExpensive();
35   setPow2DivIsCheap();
36   
37   // Use _setjmp/_longjmp instead of setjmp/longjmp.
38   setUseUnderscoreSetJmpLongJmp(true);
39     
40   // Set up the register classes.
41   addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
42   addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
43   addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
44   
45   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
46   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
47
48   // PowerPC has no intrinsics for these particular operations
49   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
50   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
51   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
52   
53   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
54   setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
55   setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
56   
57   // PowerPC has no SREM/UREM instructions
58   setOperationAction(ISD::SREM, MVT::i32, Expand);
59   setOperationAction(ISD::UREM, MVT::i32, Expand);
60   
61   // We don't support sin/cos/sqrt/fmod
62   setOperationAction(ISD::FSIN , MVT::f64, Expand);
63   setOperationAction(ISD::FCOS , MVT::f64, Expand);
64   setOperationAction(ISD::FREM , MVT::f64, Expand);
65   setOperationAction(ISD::FSIN , MVT::f32, Expand);
66   setOperationAction(ISD::FCOS , MVT::f32, Expand);
67   setOperationAction(ISD::FREM , MVT::f32, Expand);
68   
69   // If we're enabling GP optimizations, use hardware square root
70   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
71     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
72     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
73   }
74   
75   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
76   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
77   
78   // PowerPC does not have BSWAP, CTPOP or CTTZ
79   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
80   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
81   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
82   
83   // PowerPC does not have ROTR
84   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
85   
86   // PowerPC does not have Select
87   setOperationAction(ISD::SELECT, MVT::i32, Expand);
88   setOperationAction(ISD::SELECT, MVT::f32, Expand);
89   setOperationAction(ISD::SELECT, MVT::f64, Expand);
90   setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
91   setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
92   setOperationAction(ISD::SELECT, MVT::v8i16, Expand);
93   setOperationAction(ISD::SELECT, MVT::v16i8, Expand);
94   
95   // PowerPC wants to turn select_cc of FP into fsel when possible.
96   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
97   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
98
99   // PowerPC wants to optimize integer setcc a bit
100   setOperationAction(ISD::SETCC, MVT::i32, Custom);
101   
102   // PowerPC does not have BRCOND which requires SetCC
103   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
104   
105   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
106   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
107
108   // PowerPC does not have [U|S]INT_TO_FP
109   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
110   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
111
112   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
113   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
114
115   // PowerPC does not have truncstore for i1.
116   setOperationAction(ISD::TRUNCSTORE, MVT::i1, Promote);
117
118   // Support label based line numbers.
119   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
120   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
121   // FIXME - use subtarget debug flags
122   if (!TM.getSubtarget<PPCSubtarget>().isDarwin())
123     setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
124   
125   // We want to legalize GlobalAddress and ConstantPool nodes into the 
126   // appropriate instructions to materialize the address.
127   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
129
130   // RET must be custom lowered, to meet ABI requirements
131   setOperationAction(ISD::RET               , MVT::Other, Custom);
132   
133   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
134   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
135   
136   // Use the default implementation.
137   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
138   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
139   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
140   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
141   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
142   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
143   
144   // We want to custom lower some of our intrinsics.
145   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
146   
147   if (TM.getSubtarget<PPCSubtarget>().is64Bit()) {
148     // They also have instructions for converting between i64 and fp.
149     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
150     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
151     
152     // FIXME: disable this lowered code.  This generates 64-bit register values,
153     // and we don't model the fact that the top part is clobbered by calls.  We
154     // need to flag these together so that the value isn't live across a call.
155     //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
156     
157     // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
158     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
159   } else {
160     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
161     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
162   }
163
164   if (TM.getSubtarget<PPCSubtarget>().has64BitRegs()) {
165     // 64 bit PowerPC implementations can support i64 types directly
166     addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
167     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
168     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
169   } else {
170     // 32 bit PowerPC wants to expand i64 shifts itself.
171     setOperationAction(ISD::SHL, MVT::i64, Custom);
172     setOperationAction(ISD::SRL, MVT::i64, Custom);
173     setOperationAction(ISD::SRA, MVT::i64, Custom);
174   }
175
176   if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
177     // First set operation action for all vector types to expand. Then we
178     // will selectively turn on ones that can be effectively codegen'd.
179     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
180          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
181       // add/sub/and/or/xor are legal for all supported vector VT's.
182       setOperationAction(ISD::ADD , (MVT::ValueType)VT, Legal);
183       setOperationAction(ISD::SUB , (MVT::ValueType)VT, Legal);
184       setOperationAction(ISD::AND , (MVT::ValueType)VT, Legal);
185       setOperationAction(ISD::OR  , (MVT::ValueType)VT, Legal);
186       setOperationAction(ISD::XOR , (MVT::ValueType)VT, Legal);
187       
188       // We promote all shuffles to v16i8.
189       setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Promote);
190       AddPromotedToType(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, MVT::v16i8);
191       
192       setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
193       setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
194       setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
195       setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
196       setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
197       setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
198       setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
199       setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Expand);
200
201       setOperationAction(ISD::SCALAR_TO_VECTOR, (MVT::ValueType)VT, Expand);
202     }
203
204     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
205     // with merges, splats, etc.
206     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
207
208     addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
209     addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
210     addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
211     addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
212     
213     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
214
215     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
216     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
217     
218     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
219     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
220     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
221     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
222   }
223   
224   setSetCCResultContents(ZeroOrOneSetCCResult);
225   setStackPointerRegisterToSaveRestore(PPC::R1);
226   
227   // We have target-specific dag combine patterns for the following nodes:
228   setTargetDAGCombine(ISD::SINT_TO_FP);
229   setTargetDAGCombine(ISD::STORE);
230   
231   computeRegisterProperties();
232 }
233
234 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
235   switch (Opcode) {
236   default: return 0;
237   case PPCISD::FSEL:          return "PPCISD::FSEL";
238   case PPCISD::FCFID:         return "PPCISD::FCFID";
239   case PPCISD::FCTIDZ:        return "PPCISD::FCTIDZ";
240   case PPCISD::FCTIWZ:        return "PPCISD::FCTIWZ";
241   case PPCISD::STFIWX:        return "PPCISD::STFIWX";
242   case PPCISD::VMADDFP:       return "PPCISD::VMADDFP";
243   case PPCISD::VNMSUBFP:      return "PPCISD::VNMSUBFP";
244   case PPCISD::VPERM:         return "PPCISD::VPERM";
245   case PPCISD::Hi:            return "PPCISD::Hi";
246   case PPCISD::Lo:            return "PPCISD::Lo";
247   case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
248   case PPCISD::SRL:           return "PPCISD::SRL";
249   case PPCISD::SRA:           return "PPCISD::SRA";
250   case PPCISD::SHL:           return "PPCISD::SHL";
251   case PPCISD::EXTSW_32:      return "PPCISD::EXTSW_32";
252   case PPCISD::STD_32:        return "PPCISD::STD_32";
253   case PPCISD::CALL:          return "PPCISD::CALL";
254   case PPCISD::RET_FLAG:      return "PPCISD::RET_FLAG";
255   case PPCISD::MFCR:          return "PPCISD::MFCR";
256   case PPCISD::VCMP:          return "PPCISD::VCMP";
257   case PPCISD::VCMPo:         return "PPCISD::VCMPo";
258   }
259 }
260
261 //===----------------------------------------------------------------------===//
262 // Node matching predicates, for use by the tblgen matching code.
263 //===----------------------------------------------------------------------===//
264
265 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
266 static bool isFloatingPointZero(SDOperand Op) {
267   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
268     return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
269   else if (Op.getOpcode() == ISD::EXTLOAD || Op.getOpcode() == ISD::LOAD) {
270     // Maybe this has already been legalized into the constant pool?
271     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
272       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->get()))
273         return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
274   }
275   return false;
276 }
277
278 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
279 /// true if Op is undef or if it matches the specified value.
280 static bool isConstantOrUndef(SDOperand Op, unsigned Val) {
281   return Op.getOpcode() == ISD::UNDEF || 
282          cast<ConstantSDNode>(Op)->getValue() == Val;
283 }
284
285 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
286 /// VPKUHUM instruction.
287 bool PPC::isVPKUHUMShuffleMask(SDNode *N, bool isUnary) {
288   if (!isUnary) {
289     for (unsigned i = 0; i != 16; ++i)
290       if (!isConstantOrUndef(N->getOperand(i),  i*2+1))
291         return false;
292   } else {
293     for (unsigned i = 0; i != 8; ++i)
294       if (!isConstantOrUndef(N->getOperand(i),  i*2+1) ||
295           !isConstantOrUndef(N->getOperand(i+8),  i*2+1))
296         return false;
297   }
298   return true;
299 }
300
301 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
302 /// VPKUWUM instruction.
303 bool PPC::isVPKUWUMShuffleMask(SDNode *N, bool isUnary) {
304   if (!isUnary) {
305     for (unsigned i = 0; i != 16; i += 2)
306       if (!isConstantOrUndef(N->getOperand(i  ),  i*2+2) ||
307           !isConstantOrUndef(N->getOperand(i+1),  i*2+3))
308         return false;
309   } else {
310     for (unsigned i = 0; i != 8; i += 2)
311       if (!isConstantOrUndef(N->getOperand(i  ),  i*2+2) ||
312           !isConstantOrUndef(N->getOperand(i+1),  i*2+3) ||
313           !isConstantOrUndef(N->getOperand(i+8),  i*2+2) ||
314           !isConstantOrUndef(N->getOperand(i+9),  i*2+3))
315         return false;
316   }
317   return true;
318 }
319
320 /// isVMerge - Common function, used to match vmrg* shuffles.
321 ///
322 static bool isVMerge(SDNode *N, unsigned UnitSize, 
323                      unsigned LHSStart, unsigned RHSStart) {
324   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
325          N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
326   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
327          "Unsupported merge size!");
328   
329   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
330     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
331       if (!isConstantOrUndef(N->getOperand(i*UnitSize*2+j),
332                              LHSStart+j+i*UnitSize) ||
333           !isConstantOrUndef(N->getOperand(i*UnitSize*2+UnitSize+j),
334                              RHSStart+j+i*UnitSize))
335         return false;
336     }
337       return true;
338 }
339
340 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
341 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
342 bool PPC::isVMRGLShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
343   if (!isUnary)
344     return isVMerge(N, UnitSize, 8, 24);
345   return isVMerge(N, UnitSize, 8, 8);
346 }
347
348 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
349 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
350 bool PPC::isVMRGHShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
351   if (!isUnary)
352     return isVMerge(N, UnitSize, 0, 16);
353   return isVMerge(N, UnitSize, 0, 0);
354 }
355
356
357 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
358 /// amount, otherwise return -1.
359 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
360   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
361          N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
362   // Find the first non-undef value in the shuffle mask.
363   unsigned i;
364   for (i = 0; i != 16 && N->getOperand(i).getOpcode() == ISD::UNDEF; ++i)
365     /*search*/;
366   
367   if (i == 16) return -1;  // all undef.
368   
369   // Otherwise, check to see if the rest of the elements are consequtively
370   // numbered from this value.
371   unsigned ShiftAmt = cast<ConstantSDNode>(N->getOperand(i))->getValue();
372   if (ShiftAmt < i) return -1;
373   ShiftAmt -= i;
374
375   if (!isUnary) {
376     // Check the rest of the elements to see if they are consequtive.
377     for (++i; i != 16; ++i)
378       if (!isConstantOrUndef(N->getOperand(i), ShiftAmt+i))
379         return -1;
380   } else {
381     // Check the rest of the elements to see if they are consequtive.
382     for (++i; i != 16; ++i)
383       if (!isConstantOrUndef(N->getOperand(i), (ShiftAmt+i) & 15))
384         return -1;
385   }
386   
387   return ShiftAmt;
388 }
389
390 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
391 /// specifies a splat of a single element that is suitable for input to
392 /// VSPLTB/VSPLTH/VSPLTW.
393 bool PPC::isSplatShuffleMask(SDNode *N, unsigned EltSize) {
394   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
395          N->getNumOperands() == 16 &&
396          (EltSize == 1 || EltSize == 2 || EltSize == 4));
397   
398   // This is a splat operation if each element of the permute is the same, and
399   // if the value doesn't reference the second vector.
400   unsigned ElementBase = 0;
401   SDOperand Elt = N->getOperand(0);
402   if (ConstantSDNode *EltV = dyn_cast<ConstantSDNode>(Elt))
403     ElementBase = EltV->getValue();
404   else
405     return false;   // FIXME: Handle UNDEF elements too!
406
407   if (cast<ConstantSDNode>(Elt)->getValue() >= 16)
408     return false;
409   
410   // Check that they are consequtive.
411   for (unsigned i = 1; i != EltSize; ++i) {
412     if (!isa<ConstantSDNode>(N->getOperand(i)) ||
413         cast<ConstantSDNode>(N->getOperand(i))->getValue() != i+ElementBase)
414       return false;
415   }
416   
417   assert(isa<ConstantSDNode>(Elt) && "Invalid VECTOR_SHUFFLE mask!");
418   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
419     assert(isa<ConstantSDNode>(N->getOperand(i)) &&
420            "Invalid VECTOR_SHUFFLE mask!");
421     for (unsigned j = 0; j != EltSize; ++j)
422       if (N->getOperand(i+j) != N->getOperand(j))
423         return false;
424   }
425
426   return true;
427 }
428
429 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
430 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
431 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
432   assert(isSplatShuffleMask(N, EltSize));
433   return cast<ConstantSDNode>(N->getOperand(0))->getValue() / EltSize;
434 }
435
436 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
437 /// by using a vspltis[bhw] instruction of the specified element size, return
438 /// the constant being splatted.  The ByteSize field indicates the number of
439 /// bytes of each element [124] -> [bhw].
440 SDOperand PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
441   SDOperand OpVal(0, 0);
442
443   // If ByteSize of the splat is bigger than the element size of the
444   // build_vector, then we have a case where we are checking for a splat where
445   // multiple elements of the buildvector are folded together into a single
446   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
447   unsigned EltSize = 16/N->getNumOperands();
448   if (EltSize < ByteSize) {
449     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
450     SDOperand UniquedVals[4];
451     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
452     
453     // See if all of the elements in the buildvector agree across.
454     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
455       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
456       // If the element isn't a constant, bail fully out.
457       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDOperand();
458
459           
460       if (UniquedVals[i&(Multiple-1)].Val == 0)
461         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
462       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
463         return SDOperand();  // no match.
464     }
465     
466     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
467     // either constant or undef values that are identical for each chunk.  See
468     // if these chunks can form into a larger vspltis*.
469     
470     // Check to see if all of the leading entries are either 0 or -1.  If
471     // neither, then this won't fit into the immediate field.
472     bool LeadingZero = true;
473     bool LeadingOnes = true;
474     for (unsigned i = 0; i != Multiple-1; ++i) {
475       if (UniquedVals[i].Val == 0) continue;  // Must have been undefs.
476       
477       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
478       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
479     }
480     // Finally, check the least significant entry.
481     if (LeadingZero) {
482       if (UniquedVals[Multiple-1].Val == 0)
483         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
484       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getValue();
485       if (Val < 16)
486         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
487     }
488     if (LeadingOnes) {
489       if (UniquedVals[Multiple-1].Val == 0)
490         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
491       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSignExtended();
492       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
493         return DAG.getTargetConstant(Val, MVT::i32);
494     }
495     
496     return SDOperand();
497   }
498   
499   // Check to see if this buildvec has a single non-undef value in its elements.
500   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
501     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
502     if (OpVal.Val == 0)
503       OpVal = N->getOperand(i);
504     else if (OpVal != N->getOperand(i))
505       return SDOperand();
506   }
507   
508   if (OpVal.Val == 0) return SDOperand();  // All UNDEF: use implicit def.
509   
510   unsigned ValSizeInBytes = 0;
511   uint64_t Value = 0;
512   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
513     Value = CN->getValue();
514     ValSizeInBytes = MVT::getSizeInBits(CN->getValueType(0))/8;
515   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
516     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
517     Value = FloatToBits(CN->getValue());
518     ValSizeInBytes = 4;
519   }
520
521   // If the splat value is larger than the element value, then we can never do
522   // this splat.  The only case that we could fit the replicated bits into our
523   // immediate field for would be zero, and we prefer to use vxor for it.
524   if (ValSizeInBytes < ByteSize) return SDOperand();
525   
526   // If the element value is larger than the splat value, cut it in half and
527   // check to see if the two halves are equal.  Continue doing this until we
528   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
529   while (ValSizeInBytes > ByteSize) {
530     ValSizeInBytes >>= 1;
531     
532     // If the top half equals the bottom half, we're still ok.
533     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
534          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
535       return SDOperand();
536   }
537
538   // Properly sign extend the value.
539   int ShAmt = (4-ByteSize)*8;
540   int MaskVal = ((int)Value << ShAmt) >> ShAmt;
541   
542   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
543   if (MaskVal == 0) return SDOperand();
544
545   // Finally, if this value fits in a 5 bit sext field, return it
546   if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
547     return DAG.getTargetConstant(MaskVal, MVT::i32);
548   return SDOperand();
549 }
550
551 //===----------------------------------------------------------------------===//
552 //  LowerOperation implementation
553 //===----------------------------------------------------------------------===//
554
555 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
556   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
557   Constant *C = CP->get();
558   SDOperand CPI = DAG.getTargetConstantPool(C, MVT::i32, CP->getAlignment());
559   SDOperand Zero = DAG.getConstant(0, MVT::i32);
560
561   const TargetMachine &TM = DAG.getTarget();
562   
563   // If this is a non-darwin platform, we don't support non-static relo models
564   // yet.
565   if (TM.getRelocationModel() == Reloc::Static ||
566       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
567     // Generate non-pic code that has direct accesses to the constant pool.
568     // The address of the global is just (hi(&g)+lo(&g)).
569     SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, CPI, Zero);
570     SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, CPI, Zero);
571     return DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
572   }
573   
574   SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, CPI, Zero);
575   if (TM.getRelocationModel() == Reloc::PIC) {
576     // With PIC, the first instruction is actually "GR+hi(&G)".
577     Hi = DAG.getNode(ISD::ADD, MVT::i32,
578                      DAG.getNode(PPCISD::GlobalBaseReg, MVT::i32), Hi);
579   }
580   
581   SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, CPI, Zero);
582   Lo = DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
583   return Lo;
584 }
585
586 static SDOperand LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
587   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
588   GlobalValue *GV = GSDN->getGlobal();
589   SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32, GSDN->getOffset());
590   SDOperand Zero = DAG.getConstant(0, MVT::i32);
591   
592   const TargetMachine &TM = DAG.getTarget();
593
594   // If this is a non-darwin platform, we don't support non-static relo models
595   // yet.
596   if (TM.getRelocationModel() == Reloc::Static ||
597       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
598     // Generate non-pic code that has direct accesses to globals.
599     // The address of the global is just (hi(&g)+lo(&g)).
600     SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, GA, Zero);
601     SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, GA, Zero);
602     return DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
603   }
604   
605   SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, GA, Zero);
606   if (TM.getRelocationModel() == Reloc::PIC) {
607     // With PIC, the first instruction is actually "GR+hi(&G)".
608     Hi = DAG.getNode(ISD::ADD, MVT::i32,
609                      DAG.getNode(PPCISD::GlobalBaseReg, MVT::i32), Hi);
610   }
611   
612   SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, GA, Zero);
613   Lo = DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
614   
615   if (!GV->hasWeakLinkage() && !GV->hasLinkOnceLinkage() &&
616       (!GV->isExternal() || GV->hasNotBeenReadFromBytecode()))
617     return Lo;
618   
619   // If the global is weak or external, we have to go through the lazy
620   // resolution stub.
621   return DAG.getLoad(MVT::i32, DAG.getEntryNode(), Lo, DAG.getSrcValue(0));
622 }
623
624 static SDOperand LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
625   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
626   
627   // If we're comparing for equality to zero, expose the fact that this is
628   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
629   // fold the new nodes.
630   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
631     if (C->isNullValue() && CC == ISD::SETEQ) {
632       MVT::ValueType VT = Op.getOperand(0).getValueType();
633       SDOperand Zext = Op.getOperand(0);
634       if (VT < MVT::i32) {
635         VT = MVT::i32;
636         Zext = DAG.getNode(ISD::ZERO_EXTEND, VT, Op.getOperand(0));
637       } 
638       unsigned Log2b = Log2_32(MVT::getSizeInBits(VT));
639       SDOperand Clz = DAG.getNode(ISD::CTLZ, VT, Zext);
640       SDOperand Scc = DAG.getNode(ISD::SRL, VT, Clz,
641                                   DAG.getConstant(Log2b, MVT::i32));
642       return DAG.getNode(ISD::TRUNCATE, MVT::i32, Scc);
643     }
644     // Leave comparisons against 0 and -1 alone for now, since they're usually 
645     // optimized.  FIXME: revisit this when we can custom lower all setcc
646     // optimizations.
647     if (C->isAllOnesValue() || C->isNullValue())
648       return SDOperand();
649   }
650   
651   // If we have an integer seteq/setne, turn it into a compare against zero
652   // by subtracting the rhs from the lhs, which is faster than setting a
653   // condition register, reading it back out, and masking the correct bit.
654   MVT::ValueType LHSVT = Op.getOperand(0).getValueType();
655   if (MVT::isInteger(LHSVT) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
656     MVT::ValueType VT = Op.getValueType();
657     SDOperand Sub = DAG.getNode(ISD::SUB, LHSVT, Op.getOperand(0), 
658                                 Op.getOperand(1));
659     return DAG.getSetCC(VT, Sub, DAG.getConstant(0, LHSVT), CC);
660   }
661   return SDOperand();
662 }
663
664 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
665                               unsigned VarArgsFrameIndex) {
666   // vastart just stores the address of the VarArgsFrameIndex slot into the
667   // memory location argument.
668   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
669   return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
670                      Op.getOperand(1), Op.getOperand(2));
671 }
672
673 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
674   SDOperand Copy;
675   switch(Op.getNumOperands()) {
676   default:
677     assert(0 && "Do not know how to return this many arguments!");
678     abort();
679   case 1: 
680     return SDOperand(); // ret void is legal
681   case 2: {
682     MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
683     unsigned ArgReg;
684     if (MVT::isVector(ArgVT))
685       ArgReg = PPC::V2;
686     else if (MVT::isInteger(ArgVT))
687       ArgReg = PPC::R3;
688     else {
689       assert(MVT::isFloatingPoint(ArgVT));
690       ArgReg = PPC::F1;
691     }
692     
693     Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
694                             SDOperand());
695     
696     // If we haven't noted the R3/F1 are live out, do so now.
697     if (DAG.getMachineFunction().liveout_empty())
698       DAG.getMachineFunction().addLiveOut(ArgReg);
699     break;
700   }
701   case 3:
702     Copy = DAG.getCopyToReg(Op.getOperand(0), PPC::R3, Op.getOperand(2), 
703                             SDOperand());
704     Copy = DAG.getCopyToReg(Copy, PPC::R4, Op.getOperand(1),Copy.getValue(1));
705     // If we haven't noted the R3+R4 are live out, do so now.
706     if (DAG.getMachineFunction().liveout_empty()) {
707       DAG.getMachineFunction().addLiveOut(PPC::R3);
708       DAG.getMachineFunction().addLiveOut(PPC::R4);
709     }
710     break;
711   }
712   return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
713 }
714
715 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
716 /// possible.
717 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) {
718   // Not FP? Not a fsel.
719   if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
720       !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
721     return SDOperand();
722   
723   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
724   
725   // Cannot handle SETEQ/SETNE.
726   if (CC == ISD::SETEQ || CC == ISD::SETNE) return SDOperand();
727   
728   MVT::ValueType ResVT = Op.getValueType();
729   MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
730   SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
731   SDOperand TV  = Op.getOperand(2), FV  = Op.getOperand(3);
732   
733   // If the RHS of the comparison is a 0.0, we don't need to do the
734   // subtraction at all.
735   if (isFloatingPointZero(RHS))
736     switch (CC) {
737     default: break;       // SETUO etc aren't handled by fsel.
738     case ISD::SETULT:
739     case ISD::SETLT:
740       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
741     case ISD::SETUGE:
742     case ISD::SETGE:
743       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
744         LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
745       return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
746     case ISD::SETUGT:
747     case ISD::SETGT:
748       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
749     case ISD::SETULE:
750     case ISD::SETLE:
751       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
752         LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
753       return DAG.getNode(PPCISD::FSEL, ResVT,
754                          DAG.getNode(ISD::FNEG, MVT::f64, LHS), TV, FV);
755     }
756       
757       SDOperand Cmp;
758   switch (CC) {
759   default: break;       // SETUO etc aren't handled by fsel.
760   case ISD::SETULT:
761   case ISD::SETLT:
762     Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
763     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
764       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
765       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
766   case ISD::SETUGE:
767   case ISD::SETGE:
768     Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
769     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
770       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
771       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
772   case ISD::SETUGT:
773   case ISD::SETGT:
774     Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
775     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
776       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
777       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
778   case ISD::SETULE:
779   case ISD::SETLE:
780     Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
781     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
782       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
783       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
784   }
785   return SDOperand();
786 }
787
788 static SDOperand LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
789   assert(MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
790   SDOperand Src = Op.getOperand(0);
791   if (Src.getValueType() == MVT::f32)
792     Src = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Src);
793   
794   SDOperand Tmp;
795   switch (Op.getValueType()) {
796   default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
797   case MVT::i32:
798     Tmp = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Src);
799     break;
800   case MVT::i64:
801     Tmp = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Src);
802     break;
803   }
804   
805   // Convert the FP value to an int value through memory.
806   SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Tmp);
807   if (Op.getValueType() == MVT::i32)
808     Bits = DAG.getNode(ISD::TRUNCATE, MVT::i32, Bits);
809   return Bits;
810 }
811
812 static SDOperand LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
813   if (Op.getOperand(0).getValueType() == MVT::i64) {
814     SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, Op.getOperand(0));
815     SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Bits);
816     if (Op.getValueType() == MVT::f32)
817       FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
818     return FP;
819   }
820   
821   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
822          "Unhandled SINT_TO_FP type in custom expander!");
823   // Since we only generate this in 64-bit mode, we can take advantage of
824   // 64-bit registers.  In particular, sign extend the input value into the
825   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
826   // then lfd it and fcfid it.
827   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
828   int FrameIdx = FrameInfo->CreateStackObject(8, 8);
829   SDOperand FIdx = DAG.getFrameIndex(FrameIdx, MVT::i32);
830   
831   SDOperand Ext64 = DAG.getNode(PPCISD::EXTSW_32, MVT::i32,
832                                 Op.getOperand(0));
833   
834   // STD the extended value into the stack slot.
835   SDOperand Store = DAG.getNode(PPCISD::STD_32, MVT::Other,
836                                 DAG.getEntryNode(), Ext64, FIdx,
837                                 DAG.getSrcValue(NULL));
838   // Load the value as a double.
839   SDOperand Ld = DAG.getLoad(MVT::f64, Store, FIdx, DAG.getSrcValue(NULL));
840   
841   // FCFID it and return it.
842   SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Ld);
843   if (Op.getValueType() == MVT::f32)
844     FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
845   return FP;
846 }
847
848 static SDOperand LowerSHL(SDOperand Op, SelectionDAG &DAG) {
849   assert(Op.getValueType() == MVT::i64 &&
850          Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
851   // The generic code does a fine job expanding shift by a constant.
852   if (isa<ConstantSDNode>(Op.getOperand(1))) return SDOperand();
853   
854   // Otherwise, expand into a bunch of logical ops.  Note that these ops
855   // depend on the PPC behavior for oversized shift amounts.
856   SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
857                              DAG.getConstant(0, MVT::i32));
858   SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
859                              DAG.getConstant(1, MVT::i32));
860   SDOperand Amt = Op.getOperand(1);
861   
862   SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
863                                DAG.getConstant(32, MVT::i32), Amt);
864   SDOperand Tmp2 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Amt);
865   SDOperand Tmp3 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Tmp1);
866   SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
867   SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
868                                DAG.getConstant(-32U, MVT::i32));
869   SDOperand Tmp6 = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Tmp5);
870   SDOperand OutHi = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
871   SDOperand OutLo = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Amt);
872   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
873 }
874
875 static SDOperand LowerSRL(SDOperand Op, SelectionDAG &DAG) {
876   assert(Op.getValueType() == MVT::i64 &&
877          Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
878   // The generic code does a fine job expanding shift by a constant.
879   if (isa<ConstantSDNode>(Op.getOperand(1))) return SDOperand();
880   
881   // Otherwise, expand into a bunch of logical ops.  Note that these ops
882   // depend on the PPC behavior for oversized shift amounts.
883   SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
884                              DAG.getConstant(0, MVT::i32));
885   SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
886                              DAG.getConstant(1, MVT::i32));
887   SDOperand Amt = Op.getOperand(1);
888   
889   SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
890                                DAG.getConstant(32, MVT::i32), Amt);
891   SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
892   SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
893   SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
894   SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
895                                DAG.getConstant(-32U, MVT::i32));
896   SDOperand Tmp6 = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Tmp5);
897   SDOperand OutLo = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
898   SDOperand OutHi = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Amt);
899   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
900 }
901
902 static SDOperand LowerSRA(SDOperand Op, SelectionDAG &DAG) {
903   assert(Op.getValueType() == MVT::i64 &&
904          Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRA!");
905   // The generic code does a fine job expanding shift by a constant.
906   if (isa<ConstantSDNode>(Op.getOperand(1))) return SDOperand();
907   
908   // Otherwise, expand into a bunch of logical ops, followed by a select_cc.
909   SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
910                              DAG.getConstant(0, MVT::i32));
911   SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
912                              DAG.getConstant(1, MVT::i32));
913   SDOperand Amt = Op.getOperand(1);
914   
915   SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
916                                DAG.getConstant(32, MVT::i32), Amt);
917   SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
918   SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
919   SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
920   SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
921                                DAG.getConstant(-32U, MVT::i32));
922   SDOperand Tmp6 = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Tmp5);
923   SDOperand OutHi = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Amt);
924   SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, MVT::i32),
925                                     Tmp4, Tmp6, ISD::SETLE);
926   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
927 }
928
929 //===----------------------------------------------------------------------===//
930 // Vector related lowering.
931 //
932
933 // If this is a vector of constants or undefs, get the bits.  A bit in
934 // UndefBits is set if the corresponding element of the vector is an 
935 // ISD::UNDEF value.  For undefs, the corresponding VectorBits values are
936 // zero.   Return true if this is not an array of constants, false if it is.
937 //
938 // Note that VectorBits/UndefBits are returned in 'little endian' form, so
939 // elements 0,1 go in VectorBits[0] and 2,3 go in VectorBits[1] for a v4i32.
940 static bool GetConstantBuildVectorBits(SDNode *BV, uint64_t VectorBits[2],
941                                        uint64_t UndefBits[2]) {
942   // Start with zero'd results.
943   VectorBits[0] = VectorBits[1] = UndefBits[0] = UndefBits[1] = 0;
944   
945   unsigned EltBitSize = MVT::getSizeInBits(BV->getOperand(0).getValueType());
946   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
947     SDOperand OpVal = BV->getOperand(i);
948     
949     unsigned PartNo = i >= e/2;     // In the upper 128 bits?
950     unsigned SlotNo = i & (e/2-1);  // Which subpiece of the uint64_t it is.
951
952     uint64_t EltBits = 0;
953     if (OpVal.getOpcode() == ISD::UNDEF) {
954       uint64_t EltUndefBits = ~0U >> (32-EltBitSize);
955       UndefBits[PartNo] |= EltUndefBits << (SlotNo*EltBitSize);
956       continue;
957     } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
958       EltBits = CN->getValue() & (~0U >> (32-EltBitSize));
959     } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
960       assert(CN->getValueType(0) == MVT::f32 &&
961              "Only one legal FP vector type!");
962       EltBits = FloatToBits(CN->getValue());
963     } else {
964       // Nonconstant element.
965       return true;
966     }
967     
968     VectorBits[PartNo] |= EltBits << (SlotNo*EltBitSize);
969   }
970   
971   //printf("%llx %llx  %llx %llx\n", 
972   //       VectorBits[0], VectorBits[1], UndefBits[0], UndefBits[1]);
973   return false;
974 }
975
976 // If this is a case we can't handle, return null and let the default
977 // expansion code take care of it.  If we CAN select this case, and if it
978 // selects to a single instruction, return Op.  Otherwise, if we can codegen
979 // this case more efficiently than a constant pool load, lower it to the
980 // sequence of ops that should be used.
981 static SDOperand LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
982   // If this is a vector of constants or undefs, get the bits.  A bit in
983   // UndefBits is set if the corresponding element of the vector is an 
984   // ISD::UNDEF value.  For undefs, the corresponding VectorBits values are
985   // zero. 
986   uint64_t VectorBits[2];
987   uint64_t UndefBits[2];
988   if (GetConstantBuildVectorBits(Op.Val, VectorBits, UndefBits))
989     return SDOperand();   // Not a constant vector.
990   
991   // See if this is all zeros.
992   if ((VectorBits[0] | VectorBits[1]) == 0) {
993     // Canonicalize all zero vectors to be v4i32.
994     if (Op.getValueType() != MVT::v4i32) {
995       SDOperand Z = DAG.getConstant(0, MVT::i32);
996       Z = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Z, Z, Z, Z);
997       Op = DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Z);
998     }
999     return Op;
1000   }
1001   
1002   // Check to see if this is something we can use VSPLTI* to form.
1003   MVT::ValueType CanonicalVT = MVT::Other;
1004   SDNode *CST = 0;
1005   
1006   if ((CST = PPC::get_VSPLTI_elt(Op.Val, 4, DAG).Val))       // vspltisw
1007     CanonicalVT = MVT::v4i32;
1008   else if ((CST = PPC::get_VSPLTI_elt(Op.Val, 2, DAG).Val))  // vspltish
1009     CanonicalVT = MVT::v8i16;
1010   else if ((CST = PPC::get_VSPLTI_elt(Op.Val, 1, DAG).Val))  // vspltisb
1011     CanonicalVT = MVT::v16i8;
1012   
1013   // If this matches one of the vsplti* patterns, force it to the canonical
1014   // type for the pattern.
1015   if (CST) {
1016     if (Op.getValueType() != CanonicalVT) {
1017       // Convert the splatted element to the right element type.
1018       SDOperand Elt = DAG.getNode(ISD::TRUNCATE, 
1019                                   MVT::getVectorBaseType(CanonicalVT), 
1020                                   SDOperand(CST, 0));
1021       std::vector<SDOperand> Ops(MVT::getVectorNumElements(CanonicalVT), Elt);
1022       SDOperand Res = DAG.getNode(ISD::BUILD_VECTOR, CanonicalVT, Ops);
1023       Op = DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
1024     }
1025     return Op;
1026   }
1027   
1028   // If this is some other splat of 4-byte elements, see if we can handle it
1029   // in another way.
1030   // FIXME: Make this more undef happy and work with other widths (1,2 bytes).
1031   if (VectorBits[0] == VectorBits[1] &&
1032       unsigned(VectorBits[0]) == unsigned(VectorBits[0] >> 32)) {
1033     unsigned Bits = unsigned(VectorBits[0]);
1034     
1035     // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is 
1036     // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  These are important
1037     // for fneg/fabs.
1038     if (Bits == 0x80000000 || Bits == 0x7FFFFFFF) {
1039       // Make -1 and vspltisw -1:
1040       SDOperand OnesI = DAG.getConstant(~0U, MVT::i32);
1041       SDOperand OnesV = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32,
1042                                     OnesI, OnesI, OnesI, OnesI);
1043       
1044       // Make the VSLW intrinsic, computing 0x8000_0000.
1045       SDOperand Res
1046         = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, MVT::v4i32,
1047                       DAG.getConstant(Intrinsic::ppc_altivec_vslw, MVT::i32),
1048                       OnesV, OnesV);
1049       
1050       // If this is 0x7FFF_FFFF, xor by OnesV to invert it.
1051       if (Bits == 0x7FFFFFFF)
1052         Res = DAG.getNode(ISD::XOR, MVT::v4i32, Res, OnesV);
1053       
1054       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
1055     }
1056   }
1057   
1058   return SDOperand();
1059 }
1060
1061 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
1062 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
1063 /// return the code it can be lowered into.  Worst case, it can always be
1064 /// lowered into a vperm.
1065 static SDOperand LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
1066   SDOperand V1 = Op.getOperand(0);
1067   SDOperand V2 = Op.getOperand(1);
1068   SDOperand PermMask = Op.getOperand(2);
1069   
1070   // Cases that are handled by instructions that take permute immediates
1071   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
1072   // selected by the instruction selector.
1073   if (V2.getOpcode() == ISD::UNDEF) {
1074     if (PPC::isSplatShuffleMask(PermMask.Val, 1) ||
1075         PPC::isSplatShuffleMask(PermMask.Val, 2) ||
1076         PPC::isSplatShuffleMask(PermMask.Val, 4) ||
1077         PPC::isVPKUWUMShuffleMask(PermMask.Val, true) ||
1078         PPC::isVPKUHUMShuffleMask(PermMask.Val, true) ||
1079         PPC::isVSLDOIShuffleMask(PermMask.Val, true) != -1 ||
1080         PPC::isVMRGLShuffleMask(PermMask.Val, 1, true) ||
1081         PPC::isVMRGLShuffleMask(PermMask.Val, 2, true) ||
1082         PPC::isVMRGLShuffleMask(PermMask.Val, 4, true) ||
1083         PPC::isVMRGHShuffleMask(PermMask.Val, 1, true) ||
1084         PPC::isVMRGHShuffleMask(PermMask.Val, 2, true) ||
1085         PPC::isVMRGHShuffleMask(PermMask.Val, 4, true)) {
1086       return Op;
1087     }
1088   }
1089   
1090   // Altivec has a variety of "shuffle immediates" that take two vector inputs
1091   // and produce a fixed permutation.  If any of these match, do not lower to
1092   // VPERM.
1093   if (PPC::isVPKUWUMShuffleMask(PermMask.Val, false) ||
1094       PPC::isVPKUHUMShuffleMask(PermMask.Val, false) ||
1095       PPC::isVSLDOIShuffleMask(PermMask.Val, false) != -1 ||
1096       PPC::isVMRGLShuffleMask(PermMask.Val, 1, false) ||
1097       PPC::isVMRGLShuffleMask(PermMask.Val, 2, false) ||
1098       PPC::isVMRGLShuffleMask(PermMask.Val, 4, false) ||
1099       PPC::isVMRGHShuffleMask(PermMask.Val, 1, false) ||
1100       PPC::isVMRGHShuffleMask(PermMask.Val, 2, false) ||
1101       PPC::isVMRGHShuffleMask(PermMask.Val, 4, false))
1102     return Op;
1103   
1104   // TODO: Handle more cases, and also handle cases that are cheaper to do as
1105   // multiple such instructions than as a constant pool load/vperm pair.
1106   
1107   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
1108   // vector that will get spilled to the constant pool.
1109   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
1110   
1111   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
1112   // that it is in input element units, not in bytes.  Convert now.
1113   MVT::ValueType EltVT = MVT::getVectorBaseType(V1.getValueType());
1114   unsigned BytesPerElement = MVT::getSizeInBits(EltVT)/8;
1115   
1116   std::vector<SDOperand> ResultMask;
1117   for (unsigned i = 0, e = PermMask.getNumOperands(); i != e; ++i) {
1118     unsigned SrcElt =cast<ConstantSDNode>(PermMask.getOperand(i))->getValue();
1119     
1120     for (unsigned j = 0; j != BytesPerElement; ++j)
1121       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
1122                                            MVT::i8));
1123   }
1124   
1125   SDOperand VPermMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, ResultMask);
1126   return DAG.getNode(PPCISD::VPERM, V1.getValueType(), V1, V2, VPermMask);
1127 }
1128
1129 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
1130 /// lower, do it, otherwise return null.
1131 static SDOperand LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
1132   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
1133   
1134   // If this is a lowered altivec predicate compare, CompareOpc is set to the
1135   // opcode number of the comparison.
1136   int CompareOpc = -1;
1137   bool isDot = false;
1138   switch (IntNo) {
1139   default: return SDOperand();    // Don't custom lower most intrinsics.
1140   // Comparison predicates.
1141   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
1142   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
1143   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
1144   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
1145   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
1146   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
1147   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
1148   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
1149   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
1150   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
1151   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
1152   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
1153   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
1154     
1155     // Normal Comparisons.
1156   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
1157   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
1158   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
1159   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
1160   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
1161   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
1162   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
1163   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
1164   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
1165   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
1166   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
1167   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
1168   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
1169   }
1170   
1171   assert(CompareOpc>0 && "We only lower altivec predicate compares so far!");
1172   
1173   // If this is a non-dot comparison, make the VCMP node.
1174   if (!isDot) {
1175     SDOperand Tmp = DAG.getNode(PPCISD::VCMP, Op.getOperand(2).getValueType(),
1176                                 Op.getOperand(1), Op.getOperand(2),
1177                                 DAG.getConstant(CompareOpc, MVT::i32));
1178     return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Tmp);
1179   }
1180   
1181   // Create the PPCISD altivec 'dot' comparison node.
1182   std::vector<SDOperand> Ops;
1183   std::vector<MVT::ValueType> VTs;
1184   Ops.push_back(Op.getOperand(2));  // LHS
1185   Ops.push_back(Op.getOperand(3));  // RHS
1186   Ops.push_back(DAG.getConstant(CompareOpc, MVT::i32));
1187   VTs.push_back(Op.getOperand(2).getValueType());
1188   VTs.push_back(MVT::Flag);
1189   SDOperand CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops);
1190   
1191   // Now that we have the comparison, emit a copy from the CR to a GPR.
1192   // This is flagged to the above dot comparison.
1193   SDOperand Flags = DAG.getNode(PPCISD::MFCR, MVT::i32,
1194                                 DAG.getRegister(PPC::CR6, MVT::i32),
1195                                 CompNode.getValue(1)); 
1196   
1197   // Unpack the result based on how the target uses it.
1198   unsigned BitNo;   // Bit # of CR6.
1199   bool InvertBit;   // Invert result?
1200   switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1201   default:  // Can't happen, don't crash on invalid number though.
1202   case 0:   // Return the value of the EQ bit of CR6.
1203     BitNo = 0; InvertBit = false;
1204     break;
1205   case 1:   // Return the inverted value of the EQ bit of CR6.
1206     BitNo = 0; InvertBit = true;
1207     break;
1208   case 2:   // Return the value of the LT bit of CR6.
1209     BitNo = 2; InvertBit = false;
1210     break;
1211   case 3:   // Return the inverted value of the LT bit of CR6.
1212     BitNo = 2; InvertBit = true;
1213     break;
1214   }
1215   
1216   // Shift the bit into the low position.
1217   Flags = DAG.getNode(ISD::SRL, MVT::i32, Flags,
1218                       DAG.getConstant(8-(3-BitNo), MVT::i32));
1219   // Isolate the bit.
1220   Flags = DAG.getNode(ISD::AND, MVT::i32, Flags,
1221                       DAG.getConstant(1, MVT::i32));
1222   
1223   // If we are supposed to, toggle the bit.
1224   if (InvertBit)
1225     Flags = DAG.getNode(ISD::XOR, MVT::i32, Flags,
1226                         DAG.getConstant(1, MVT::i32));
1227   return Flags;
1228 }
1229
1230 static SDOperand LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
1231   // Create a stack slot that is 16-byte aligned.
1232   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
1233   int FrameIdx = FrameInfo->CreateStackObject(16, 16);
1234   SDOperand FIdx = DAG.getFrameIndex(FrameIdx, MVT::i32);
1235   
1236   // Store the input value into Value#0 of the stack slot.
1237   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
1238                                 Op.getOperand(0), FIdx,DAG.getSrcValue(NULL));
1239   // Load it out.
1240   return DAG.getLoad(Op.getValueType(), Store, FIdx, DAG.getSrcValue(NULL));
1241 }
1242
1243 /// LowerOperation - Provide custom lowering hooks for some operations.
1244 ///
1245 SDOperand PPCTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1246   switch (Op.getOpcode()) {
1247   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
1248   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1249   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1250   case ISD::SETCC:              return LowerSETCC(Op, DAG);
1251   case ISD::VASTART:            return LowerVASTART(Op, DAG, VarArgsFrameIndex);
1252   case ISD::RET:                return LowerRET(Op, DAG);
1253     
1254   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1255   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1256   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1257
1258   // Lower 64-bit shifts.
1259   case ISD::SHL:                return LowerSHL(Op, DAG);
1260   case ISD::SRL:                return LowerSRL(Op, DAG);
1261   case ISD::SRA:                return LowerSRA(Op, DAG);
1262
1263   // Vector-related lowering.
1264   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
1265   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
1266   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1267   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
1268   }
1269   return SDOperand();
1270 }
1271
1272 //===----------------------------------------------------------------------===//
1273 //  Other Lowering Code
1274 //===----------------------------------------------------------------------===//
1275
1276 std::vector<SDOperand>
1277 PPCTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
1278   //
1279   // add beautiful description of PPC stack frame format, or at least some docs
1280   //
1281   MachineFunction &MF = DAG.getMachineFunction();
1282   MachineFrameInfo *MFI = MF.getFrameInfo();
1283   MachineBasicBlock& BB = MF.front();
1284   SSARegMap *RegMap = MF.getSSARegMap();
1285   std::vector<SDOperand> ArgValues;
1286   
1287   unsigned ArgOffset = 24;
1288   unsigned GPR_remaining = 8;
1289   unsigned FPR_remaining = 13;
1290   unsigned GPR_idx = 0, FPR_idx = 0;
1291   static const unsigned GPR[] = {
1292     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1293     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1294   };
1295   static const unsigned FPR[] = {
1296     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1297     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1298   };
1299   
1300   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
1301   // the arguments start at offset 24, although they are likely to be passed
1302   // in registers.
1303   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
1304     SDOperand newroot, argt;
1305     unsigned ObjSize;
1306     bool needsLoad = false;
1307     bool ArgLive = !I->use_empty();
1308     MVT::ValueType ObjectVT = getValueType(I->getType());
1309     
1310     switch (ObjectVT) {
1311     default: assert(0 && "Unhandled argument type!");
1312     case MVT::i1:
1313     case MVT::i8:
1314     case MVT::i16:
1315     case MVT::i32:
1316       ObjSize = 4;
1317       if (!ArgLive) break;
1318       if (GPR_remaining > 0) {
1319         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
1320         MF.addLiveIn(GPR[GPR_idx], VReg);
1321         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
1322         if (ObjectVT != MVT::i32) {
1323           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
1324                                                        : ISD::AssertZext;
1325           argt = DAG.getNode(AssertOp, MVT::i32, argt, 
1326                              DAG.getValueType(ObjectVT));
1327           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, argt);
1328         }
1329       } else {
1330         needsLoad = true;
1331       }
1332       break;
1333     case MVT::i64:
1334       ObjSize = 8;
1335       if (!ArgLive) break;
1336       if (GPR_remaining > 0) {
1337         SDOperand argHi, argLo;
1338         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
1339         MF.addLiveIn(GPR[GPR_idx], VReg);
1340         argHi = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
1341         // If we have two or more remaining argument registers, then both halves
1342         // of the i64 can be sourced from there.  Otherwise, the lower half will
1343         // have to come off the stack.  This can happen when an i64 is preceded
1344         // by 28 bytes of arguments.
1345         if (GPR_remaining > 1) {
1346           unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
1347           MF.addLiveIn(GPR[GPR_idx+1], VReg);
1348           argLo = DAG.getCopyFromReg(argHi, VReg, MVT::i32);
1349         } else {
1350           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
1351           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
1352           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
1353                               DAG.getSrcValue(NULL));
1354         }
1355         // Build the outgoing arg thingy
1356         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
1357         newroot = argLo;
1358       } else {
1359         needsLoad = true;
1360       }
1361       break;
1362     case MVT::f32:
1363     case MVT::f64:
1364       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
1365       if (!ArgLive) {
1366         if (FPR_remaining > 0) {
1367           --FPR_remaining;
1368           ++FPR_idx;
1369         }        
1370         break;
1371       }
1372       if (FPR_remaining > 0) {
1373         unsigned VReg;
1374         if (ObjectVT == MVT::f32)
1375           VReg = RegMap->createVirtualRegister(&PPC::F4RCRegClass);
1376         else
1377           VReg = RegMap->createVirtualRegister(&PPC::F8RCRegClass);
1378         MF.addLiveIn(FPR[FPR_idx], VReg);
1379         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, ObjectVT);
1380         --FPR_remaining;
1381         ++FPR_idx;
1382       } else {
1383         needsLoad = true;
1384       }
1385       break;
1386     }
1387     
1388     // We need to load the argument to a virtual register if we determined above
1389     // that we ran out of physical registers of the appropriate type
1390     if (needsLoad) {
1391       unsigned SubregOffset = 0;
1392       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
1393       if (ObjectVT == MVT::i16) SubregOffset = 2;
1394       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
1395       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
1396       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
1397                         DAG.getConstant(SubregOffset, MVT::i32));
1398       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
1399                                    DAG.getSrcValue(NULL));
1400     }
1401     
1402     // Every 4 bytes of argument space consumes one of the GPRs available for
1403     // argument passing.
1404     if (GPR_remaining > 0) {
1405       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
1406       GPR_remaining -= delta;
1407       GPR_idx += delta;
1408     }
1409     ArgOffset += ObjSize;
1410     if (newroot.Val)
1411       DAG.setRoot(newroot.getValue(1));
1412     
1413     ArgValues.push_back(argt);
1414   }
1415   
1416   // If the function takes variable number of arguments, make a frame index for
1417   // the start of the first vararg value... for expansion of llvm.va_start.
1418   if (F.isVarArg()) {
1419     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1420     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
1421     // If this function is vararg, store any remaining integer argument regs
1422     // to their spots on the stack so that they may be loaded by deferencing the
1423     // result of va_next.
1424     std::vector<SDOperand> MemOps;
1425     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
1426       unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
1427       MF.addLiveIn(GPR[GPR_idx], VReg);
1428       SDOperand Val = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
1429       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
1430                                     Val, FIN, DAG.getSrcValue(NULL));
1431       MemOps.push_back(Store);
1432       // Increment the address by four for the next argument to store
1433       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
1434       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
1435     }
1436     if (!MemOps.empty()) {
1437       MemOps.push_back(DAG.getRoot());
1438       DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
1439     }
1440   }
1441   
1442   return ArgValues;
1443 }
1444
1445 std::pair<SDOperand, SDOperand>
1446 PPCTargetLowering::LowerCallTo(SDOperand Chain,
1447                                const Type *RetTy, bool isVarArg,
1448                                unsigned CallingConv, bool isTailCall,
1449                                SDOperand Callee, ArgListTy &Args,
1450                                SelectionDAG &DAG) {
1451   // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
1452   // SelectExpr to use to put the arguments in the appropriate registers.
1453   std::vector<SDOperand> args_to_use;
1454   
1455   // Count how many bytes are to be pushed on the stack, including the linkage
1456   // area, and parameter passing area.
1457   unsigned NumBytes = 24;
1458   
1459   if (Args.empty()) {
1460     Chain = DAG.getCALLSEQ_START(Chain,
1461                                  DAG.getConstant(NumBytes, getPointerTy()));
1462   } else {
1463     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1464       switch (getValueType(Args[i].second)) {
1465       default: assert(0 && "Unknown value type!");
1466       case MVT::i1:
1467       case MVT::i8:
1468       case MVT::i16:
1469       case MVT::i32:
1470       case MVT::f32:
1471         NumBytes += 4;
1472         break;
1473       case MVT::i64:
1474       case MVT::f64:
1475         NumBytes += 8;
1476         break;
1477       }
1478     }
1479         
1480     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
1481     // plus 32 bytes of argument space in case any called code gets funky on us.
1482     // (Required by ABI to support var arg)
1483     if (NumBytes < 56) NumBytes = 56;
1484     
1485     // Adjust the stack pointer for the new arguments...
1486     // These operations are automatically eliminated by the prolog/epilog pass
1487     Chain = DAG.getCALLSEQ_START(Chain,
1488                                  DAG.getConstant(NumBytes, getPointerTy()));
1489     
1490     // Set up a copy of the stack pointer for use loading and storing any
1491     // arguments that may not fit in the registers available for argument
1492     // passing.
1493     SDOperand StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
1494     
1495     // Figure out which arguments are going to go in registers, and which in
1496     // memory.  Also, if this is a vararg function, floating point operations
1497     // must be stored to our stack, and loaded into integer regs as well, if
1498     // any integer regs are available for argument passing.
1499     unsigned ArgOffset = 24;
1500     unsigned GPR_remaining = 8;
1501     unsigned FPR_remaining = 13;
1502     
1503     std::vector<SDOperand> MemOps;
1504     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1505       // PtrOff will be used to store the current argument to the stack if a
1506       // register cannot be found for it.
1507       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1508       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
1509       MVT::ValueType ArgVT = getValueType(Args[i].second);
1510       
1511       switch (ArgVT) {
1512       default: assert(0 && "Unexpected ValueType for argument!");
1513       case MVT::i1:
1514       case MVT::i8:
1515       case MVT::i16:
1516         // Promote the integer to 32 bits.  If the input type is signed use a
1517         // sign extend, otherwise use a zero extend.
1518         if (Args[i].second->isSigned())
1519           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
1520         else
1521           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
1522         // FALL THROUGH
1523       case MVT::i32:
1524         if (GPR_remaining > 0) {
1525           args_to_use.push_back(Args[i].first);
1526           --GPR_remaining;
1527         } else {
1528           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1529                                        Args[i].first, PtrOff,
1530                                        DAG.getSrcValue(NULL)));
1531         }
1532         ArgOffset += 4;
1533         break;
1534       case MVT::i64:
1535         // If we have one free GPR left, we can place the upper half of the i64
1536         // in it, and store the other half to the stack.  If we have two or more
1537         // free GPRs, then we can pass both halves of the i64 in registers.
1538         if (GPR_remaining > 0) {
1539           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
1540                                      Args[i].first, DAG.getConstant(1, MVT::i32));
1541           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
1542                                      Args[i].first, DAG.getConstant(0, MVT::i32));
1543           args_to_use.push_back(Hi);
1544           --GPR_remaining;
1545           if (GPR_remaining > 0) {
1546             args_to_use.push_back(Lo);
1547             --GPR_remaining;
1548           } else {
1549             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
1550             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
1551             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1552                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
1553           }
1554         } else {
1555           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1556                                        Args[i].first, PtrOff,
1557                                        DAG.getSrcValue(NULL)));
1558         }
1559         ArgOffset += 8;
1560         break;
1561       case MVT::f32:
1562       case MVT::f64:
1563         if (FPR_remaining > 0) {
1564           args_to_use.push_back(Args[i].first);
1565           --FPR_remaining;
1566           if (isVarArg) {
1567             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
1568                                           Args[i].first, PtrOff,
1569                                           DAG.getSrcValue(NULL));
1570             MemOps.push_back(Store);
1571             // Float varargs are always shadowed in available integer registers
1572             if (GPR_remaining > 0) {
1573               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
1574                                            DAG.getSrcValue(NULL));
1575               MemOps.push_back(Load.getValue(1));
1576               args_to_use.push_back(Load);
1577               --GPR_remaining;
1578             }
1579             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
1580               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
1581               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
1582               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
1583                                            DAG.getSrcValue(NULL));
1584               MemOps.push_back(Load.getValue(1));
1585               args_to_use.push_back(Load);
1586               --GPR_remaining;
1587             }
1588           } else {
1589             // If we have any FPRs remaining, we may also have GPRs remaining.
1590             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
1591             // GPRs.
1592             if (GPR_remaining > 0) {
1593               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
1594               --GPR_remaining;
1595             }
1596             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
1597               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
1598               --GPR_remaining;
1599             }
1600           }
1601         } else {
1602           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1603                                        Args[i].first, PtrOff,
1604                                        DAG.getSrcValue(NULL)));
1605         }
1606         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
1607         break;
1608       }
1609     }
1610     if (!MemOps.empty())
1611       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
1612   }
1613   
1614   std::vector<MVT::ValueType> RetVals;
1615   MVT::ValueType RetTyVT = getValueType(RetTy);
1616   MVT::ValueType ActualRetTyVT = RetTyVT;
1617   if (RetTyVT >= MVT::i1 && RetTyVT <= MVT::i16)
1618     ActualRetTyVT = MVT::i32;   // Promote result to i32.
1619     
1620   if (RetTyVT == MVT::i64) {
1621     RetVals.push_back(MVT::i32);
1622     RetVals.push_back(MVT::i32);
1623   } else if (RetTyVT != MVT::isVoid) {
1624     RetVals.push_back(ActualRetTyVT);
1625   }
1626   RetVals.push_back(MVT::Other);
1627   
1628   // If the callee is a GlobalAddress node (quite common, every direct call is)
1629   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1630   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1631     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
1632   
1633   std::vector<SDOperand> Ops;
1634   Ops.push_back(Chain);
1635   Ops.push_back(Callee);
1636   Ops.insert(Ops.end(), args_to_use.begin(), args_to_use.end());
1637   SDOperand TheCall = DAG.getNode(PPCISD::CALL, RetVals, Ops);
1638   Chain = TheCall.getValue(TheCall.Val->getNumValues()-1);
1639   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
1640                       DAG.getConstant(NumBytes, getPointerTy()));
1641   SDOperand RetVal = TheCall;
1642   
1643   // If the result is a small value, add a note so that we keep track of the
1644   // information about whether it is sign or zero extended.
1645   if (RetTyVT != ActualRetTyVT) {
1646     RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext : ISD::AssertZext,
1647                          MVT::i32, RetVal, DAG.getValueType(RetTyVT));
1648     RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
1649   } else if (RetTyVT == MVT::i64) {
1650     RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, RetVal, RetVal.getValue(1));
1651   }
1652   
1653   return std::make_pair(RetVal, Chain);
1654 }
1655
1656 MachineBasicBlock *
1657 PPCTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1658                                            MachineBasicBlock *BB) {
1659   assert((MI->getOpcode() == PPC::SELECT_CC_Int ||
1660           MI->getOpcode() == PPC::SELECT_CC_F4 ||
1661           MI->getOpcode() == PPC::SELECT_CC_F8 ||
1662           MI->getOpcode() == PPC::SELECT_CC_VRRC) &&
1663          "Unexpected instr type to insert");
1664   
1665   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1666   // control-flow pattern.  The incoming instruction knows the destination vreg
1667   // to set, the condition code register to branch on, the true/false values to
1668   // select between, and a branch opcode to use.
1669   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1670   ilist<MachineBasicBlock>::iterator It = BB;
1671   ++It;
1672   
1673   //  thisMBB:
1674   //  ...
1675   //   TrueVal = ...
1676   //   cmpTY ccX, r1, r2
1677   //   bCC copy1MBB
1678   //   fallthrough --> copy0MBB
1679   MachineBasicBlock *thisMBB = BB;
1680   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1681   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1682   BuildMI(BB, MI->getOperand(4).getImmedValue(), 2)
1683     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1684   MachineFunction *F = BB->getParent();
1685   F->getBasicBlockList().insert(It, copy0MBB);
1686   F->getBasicBlockList().insert(It, sinkMBB);
1687   // Update machine-CFG edges by first adding all successors of the current
1688   // block to the new block which will contain the Phi node for the select.
1689   for(MachineBasicBlock::succ_iterator i = BB->succ_begin(), 
1690       e = BB->succ_end(); i != e; ++i)
1691     sinkMBB->addSuccessor(*i);
1692   // Next, remove all successors of the current block, and add the true
1693   // and fallthrough blocks as its successors.
1694   while(!BB->succ_empty())
1695     BB->removeSuccessor(BB->succ_begin());
1696   BB->addSuccessor(copy0MBB);
1697   BB->addSuccessor(sinkMBB);
1698   
1699   //  copy0MBB:
1700   //   %FalseValue = ...
1701   //   # fallthrough to sinkMBB
1702   BB = copy0MBB;
1703   
1704   // Update machine-CFG edges
1705   BB->addSuccessor(sinkMBB);
1706   
1707   //  sinkMBB:
1708   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1709   //  ...
1710   BB = sinkMBB;
1711   BuildMI(BB, PPC::PHI, 4, MI->getOperand(0).getReg())
1712     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1713     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1714
1715   delete MI;   // The pseudo instruction is gone now.
1716   return BB;
1717 }
1718
1719 //===----------------------------------------------------------------------===//
1720 // Target Optimization Hooks
1721 //===----------------------------------------------------------------------===//
1722
1723 SDOperand PPCTargetLowering::PerformDAGCombine(SDNode *N, 
1724                                                DAGCombinerInfo &DCI) const {
1725   TargetMachine &TM = getTargetMachine();
1726   SelectionDAG &DAG = DCI.DAG;
1727   switch (N->getOpcode()) {
1728   default: break;
1729   case ISD::SINT_TO_FP:
1730     if (TM.getSubtarget<PPCSubtarget>().is64Bit()) {
1731       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
1732         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
1733         // We allow the src/dst to be either f32/f64, but the intermediate
1734         // type must be i64.
1735         if (N->getOperand(0).getValueType() == MVT::i64) {
1736           SDOperand Val = N->getOperand(0).getOperand(0);
1737           if (Val.getValueType() == MVT::f32) {
1738             Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
1739             DCI.AddToWorklist(Val.Val);
1740           }
1741             
1742           Val = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Val);
1743           DCI.AddToWorklist(Val.Val);
1744           Val = DAG.getNode(PPCISD::FCFID, MVT::f64, Val);
1745           DCI.AddToWorklist(Val.Val);
1746           if (N->getValueType(0) == MVT::f32) {
1747             Val = DAG.getNode(ISD::FP_ROUND, MVT::f32, Val);
1748             DCI.AddToWorklist(Val.Val);
1749           }
1750           return Val;
1751         } else if (N->getOperand(0).getValueType() == MVT::i32) {
1752           // If the intermediate type is i32, we can avoid the load/store here
1753           // too.
1754         }
1755       }
1756     }
1757     break;
1758   case ISD::STORE:
1759     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
1760     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
1761         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
1762         N->getOperand(1).getValueType() == MVT::i32) {
1763       SDOperand Val = N->getOperand(1).getOperand(0);
1764       if (Val.getValueType() == MVT::f32) {
1765         Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
1766         DCI.AddToWorklist(Val.Val);
1767       }
1768       Val = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Val);
1769       DCI.AddToWorklist(Val.Val);
1770
1771       Val = DAG.getNode(PPCISD::STFIWX, MVT::Other, N->getOperand(0), Val,
1772                         N->getOperand(2), N->getOperand(3));
1773       DCI.AddToWorklist(Val.Val);
1774       return Val;
1775     }
1776     break;
1777   case PPCISD::VCMP: {
1778     // If a VCMPo node already exists with exactly the same operands as this
1779     // node, use its result instead of this node (VCMPo computes both a CR6 and
1780     // a normal output).
1781     //
1782     if (!N->getOperand(0).hasOneUse() &&
1783         !N->getOperand(1).hasOneUse() &&
1784         !N->getOperand(2).hasOneUse()) {
1785       
1786       // Scan all of the users of the LHS, looking for VCMPo's that match.
1787       SDNode *VCMPoNode = 0;
1788       
1789       SDNode *LHSN = N->getOperand(0).Val;
1790       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
1791            UI != E; ++UI)
1792         if ((*UI)->getOpcode() == PPCISD::VCMPo &&
1793             (*UI)->getOperand(1) == N->getOperand(1) &&
1794             (*UI)->getOperand(2) == N->getOperand(2) &&
1795             (*UI)->getOperand(0) == N->getOperand(0)) {
1796           VCMPoNode = *UI;
1797           break;
1798         }
1799       
1800       // If there are non-zero uses of the flag value, use the VCMPo node!
1801       if (VCMPoNode && !VCMPoNode->hasNUsesOfValue(0, 1))
1802         return SDOperand(VCMPoNode, 0);
1803     }
1804     break;
1805   }
1806   }
1807   
1808   return SDOperand();
1809 }
1810
1811 //===----------------------------------------------------------------------===//
1812 // Inline Assembly Support
1813 //===----------------------------------------------------------------------===//
1814
1815 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
1816                                                        uint64_t Mask,
1817                                                        uint64_t &KnownZero, 
1818                                                        uint64_t &KnownOne,
1819                                                        unsigned Depth) const {
1820   KnownZero = 0;
1821   KnownOne = 0;
1822   switch (Op.getOpcode()) {
1823   default: break;
1824   case ISD::INTRINSIC_WO_CHAIN: {
1825     switch (cast<ConstantSDNode>(Op.getOperand(0))->getValue()) {
1826     default: break;
1827     case Intrinsic::ppc_altivec_vcmpbfp_p:
1828     case Intrinsic::ppc_altivec_vcmpeqfp_p:
1829     case Intrinsic::ppc_altivec_vcmpequb_p:
1830     case Intrinsic::ppc_altivec_vcmpequh_p:
1831     case Intrinsic::ppc_altivec_vcmpequw_p:
1832     case Intrinsic::ppc_altivec_vcmpgefp_p:
1833     case Intrinsic::ppc_altivec_vcmpgtfp_p:
1834     case Intrinsic::ppc_altivec_vcmpgtsb_p:
1835     case Intrinsic::ppc_altivec_vcmpgtsh_p:
1836     case Intrinsic::ppc_altivec_vcmpgtsw_p:
1837     case Intrinsic::ppc_altivec_vcmpgtub_p:
1838     case Intrinsic::ppc_altivec_vcmpgtuh_p:
1839     case Intrinsic::ppc_altivec_vcmpgtuw_p:
1840       KnownZero = ~1U;  // All bits but the low one are known to be zero.
1841       break;
1842     }        
1843   }
1844   }
1845 }
1846
1847
1848 /// getConstraintType - Given a constraint letter, return the type of
1849 /// constraint it is for this target.
1850 PPCTargetLowering::ConstraintType 
1851 PPCTargetLowering::getConstraintType(char ConstraintLetter) const {
1852   switch (ConstraintLetter) {
1853   default: break;
1854   case 'b':
1855   case 'r':
1856   case 'f':
1857   case 'v':
1858   case 'y':
1859     return C_RegisterClass;
1860   }  
1861   return TargetLowering::getConstraintType(ConstraintLetter);
1862 }
1863
1864
1865 std::vector<unsigned> PPCTargetLowering::
1866 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1867                                   MVT::ValueType VT) const {
1868   if (Constraint.size() == 1) {
1869     switch (Constraint[0]) {      // GCC RS6000 Constraint Letters
1870     default: break;  // Unknown constriant letter
1871     case 'b': 
1872       return make_vector<unsigned>(/*no R0*/ PPC::R1 , PPC::R2 , PPC::R3 ,
1873                                    PPC::R4 , PPC::R5 , PPC::R6 , PPC::R7 ,
1874                                    PPC::R8 , PPC::R9 , PPC::R10, PPC::R11, 
1875                                    PPC::R12, PPC::R13, PPC::R14, PPC::R15, 
1876                                    PPC::R16, PPC::R17, PPC::R18, PPC::R19, 
1877                                    PPC::R20, PPC::R21, PPC::R22, PPC::R23, 
1878                                    PPC::R24, PPC::R25, PPC::R26, PPC::R27, 
1879                                    PPC::R28, PPC::R29, PPC::R30, PPC::R31, 
1880                                    0);
1881     case 'r': 
1882       return make_vector<unsigned>(PPC::R0 , PPC::R1 , PPC::R2 , PPC::R3 ,
1883                                    PPC::R4 , PPC::R5 , PPC::R6 , PPC::R7 ,
1884                                    PPC::R8 , PPC::R9 , PPC::R10, PPC::R11, 
1885                                    PPC::R12, PPC::R13, PPC::R14, PPC::R15, 
1886                                    PPC::R16, PPC::R17, PPC::R18, PPC::R19, 
1887                                    PPC::R20, PPC::R21, PPC::R22, PPC::R23, 
1888                                    PPC::R24, PPC::R25, PPC::R26, PPC::R27, 
1889                                    PPC::R28, PPC::R29, PPC::R30, PPC::R31, 
1890                                    0);
1891     case 'f': 
1892       return make_vector<unsigned>(PPC::F0 , PPC::F1 , PPC::F2 , PPC::F3 ,
1893                                    PPC::F4 , PPC::F5 , PPC::F6 , PPC::F7 ,
1894                                    PPC::F8 , PPC::F9 , PPC::F10, PPC::F11, 
1895                                    PPC::F12, PPC::F13, PPC::F14, PPC::F15, 
1896                                    PPC::F16, PPC::F17, PPC::F18, PPC::F19, 
1897                                    PPC::F20, PPC::F21, PPC::F22, PPC::F23, 
1898                                    PPC::F24, PPC::F25, PPC::F26, PPC::F27, 
1899                                    PPC::F28, PPC::F29, PPC::F30, PPC::F31, 
1900                                    0);
1901     case 'v': 
1902       return make_vector<unsigned>(PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 ,
1903                                    PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
1904                                    PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, 
1905                                    PPC::V12, PPC::V13, PPC::V14, PPC::V15, 
1906                                    PPC::V16, PPC::V17, PPC::V18, PPC::V19, 
1907                                    PPC::V20, PPC::V21, PPC::V22, PPC::V23, 
1908                                    PPC::V24, PPC::V25, PPC::V26, PPC::V27, 
1909                                    PPC::V28, PPC::V29, PPC::V30, PPC::V31, 
1910                                    0);
1911     case 'y': 
1912       return make_vector<unsigned>(PPC::CR0, PPC::CR1, PPC::CR2, PPC::CR3,
1913                                    PPC::CR4, PPC::CR5, PPC::CR6, PPC::CR7,
1914                                    0);
1915     }
1916   }
1917   
1918   return std::vector<unsigned>();
1919 }
1920
1921 // isOperandValidForConstraint
1922 bool PPCTargetLowering::
1923 isOperandValidForConstraint(SDOperand Op, char Letter) {
1924   switch (Letter) {
1925   default: break;
1926   case 'I':
1927   case 'J':
1928   case 'K':
1929   case 'L':
1930   case 'M':
1931   case 'N':
1932   case 'O':
1933   case 'P': {
1934     if (!isa<ConstantSDNode>(Op)) return false;  // Must be an immediate.
1935     unsigned Value = cast<ConstantSDNode>(Op)->getValue();
1936     switch (Letter) {
1937     default: assert(0 && "Unknown constraint letter!");
1938     case 'I':  // "I" is a signed 16-bit constant.
1939       return (short)Value == (int)Value;
1940     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
1941     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
1942       return (short)Value == 0;
1943     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
1944       return (Value >> 16) == 0;
1945     case 'M':  // "M" is a constant that is greater than 31.
1946       return Value > 31;
1947     case 'N':  // "N" is a positive constant that is an exact power of two.
1948       return (int)Value > 0 && isPowerOf2_32(Value);
1949     case 'O':  // "O" is the constant zero. 
1950       return Value == 0;
1951     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
1952       return (short)-Value == (int)-Value;
1953     }
1954     break;
1955   }
1956   }
1957   
1958   // Handle standard constraint letters.
1959   return TargetLowering::isOperandValidForConstraint(Op, Letter);
1960 }
1961
1962 /// isLegalAddressImmediate - Return true if the integer value can be used
1963 /// as the offset of the target addressing mode.
1964 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V) const {
1965   // PPC allows a sign-extended 16-bit immediate field.
1966   return (V > -(1 << 16) && V < (1 << 16)-1);
1967 }