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