Change LowerFP_TO_SINT to create the specific code it needs instead of
[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 "PPCMachineFunctionInfo.h"
16 #include "PPCPredicates.h"
17 #include "PPCTargetMachine.h"
18 #include "PPCPerfectShuffle.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/VectorExtras.h"
21 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/Intrinsics.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/CommandLine.h"
34 using namespace llvm;
35
36 static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc", 
37 cl::desc("enable preincrement load/store generation on PPC (experimental)"),
38                                      cl::Hidden);
39
40 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
41   : TargetLowering(TM), PPCSubTarget(*TM.getSubtargetImpl()) {
42     
43   setPow2DivIsCheap();
44   
45   // Use _setjmp/_longjmp instead of setjmp/longjmp.
46   setUseUnderscoreSetJmp(true);
47   setUseUnderscoreLongJmp(true);
48     
49   // Set up the register classes.
50   addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
51   addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
52   addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
53   
54   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
55   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
56   setLoadXAction(ISD::SEXTLOAD, MVT::i8, Expand);
57   
58   // PowerPC does not have truncstore for i1.
59   setStoreXAction(MVT::i1, Promote);
60
61   // PowerPC has pre-inc load and store's.
62   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
63   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
64   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
65   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
66   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
67   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
68   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
69   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
70   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
71   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
72
73   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
74   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
75
76   // Shortening conversions involving ppcf128 get expanded (2 regs -> 1 reg)
77   setConvertAction(MVT::ppcf128, MVT::f64, Expand);
78   setConvertAction(MVT::ppcf128, MVT::f32, Expand);
79   // This is used in the ppcf128->int sequence.  Note it has different semantics
80   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
81   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
82
83   // PowerPC has no intrinsics for these particular operations
84   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
85   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
86   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
87   
88   // PowerPC has no SREM/UREM instructions
89   setOperationAction(ISD::SREM, MVT::i32, Expand);
90   setOperationAction(ISD::UREM, MVT::i32, Expand);
91   setOperationAction(ISD::SREM, MVT::i64, Expand);
92   setOperationAction(ISD::UREM, MVT::i64, Expand);
93
94   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
95   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
96   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
97   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
98   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
99   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
100   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
101   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
102   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
103   
104   // We don't support sin/cos/sqrt/fmod/pow
105   setOperationAction(ISD::FSIN , MVT::f64, Expand);
106   setOperationAction(ISD::FCOS , MVT::f64, Expand);
107   setOperationAction(ISD::FREM , MVT::f64, Expand);
108   setOperationAction(ISD::FPOW , MVT::f64, Expand);
109   setOperationAction(ISD::FSIN , MVT::f32, Expand);
110   setOperationAction(ISD::FCOS , MVT::f32, Expand);
111   setOperationAction(ISD::FREM , MVT::f32, Expand);
112   setOperationAction(ISD::FPOW , MVT::f32, Expand);
113   
114   // If we're enabling GP optimizations, use hardware square root
115   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
116     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
117     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
118   }
119   
120   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
121   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
122   
123   // PowerPC does not have BSWAP, CTPOP or CTTZ
124   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
125   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
126   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
127   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
128   setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
129   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
130   
131   // PowerPC does not have ROTR
132   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
133   
134   // PowerPC does not have Select
135   setOperationAction(ISD::SELECT, MVT::i32, Expand);
136   setOperationAction(ISD::SELECT, MVT::i64, Expand);
137   setOperationAction(ISD::SELECT, MVT::f32, Expand);
138   setOperationAction(ISD::SELECT, MVT::f64, Expand);
139   
140   // PowerPC wants to turn select_cc of FP into fsel when possible.
141   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
142   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
143
144   // PowerPC wants to optimize integer setcc a bit
145   setOperationAction(ISD::SETCC, MVT::i32, Custom);
146   
147   // PowerPC does not have BRCOND which requires SetCC
148   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
149
150   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
151   
152   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
153   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
154
155   // PowerPC does not have [U|S]INT_TO_FP
156   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
157   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
158
159   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
160   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
161   setOperationAction(ISD::BIT_CONVERT, MVT::i64, Expand);
162   setOperationAction(ISD::BIT_CONVERT, MVT::f64, Expand);
163
164   // We cannot sextinreg(i1).  Expand to shifts.
165   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
166
167   // Support label based line numbers.
168   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
169   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
170   if (!TM.getSubtarget<PPCSubtarget>().isDarwin()) {
171     setOperationAction(ISD::LABEL, MVT::Other, Expand);
172   } else {
173     setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
174     setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
175     setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
176     setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
177   }
178   
179   // We want to legalize GlobalAddress and ConstantPool nodes into the 
180   // appropriate instructions to materialize the address.
181   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
182   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
183   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
184   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
185   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
186   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
187   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
188   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
189   
190   // RET must be custom lowered, to meet ABI requirements
191   setOperationAction(ISD::RET               , MVT::Other, Custom);
192
193   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
194   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
195   
196   // VAARG is custom lowered with ELF 32 ABI
197   if (TM.getSubtarget<PPCSubtarget>().isELF32_ABI())
198     setOperationAction(ISD::VAARG, MVT::Other, Custom);
199   else
200     setOperationAction(ISD::VAARG, MVT::Other, Expand);
201   
202   // Use the default implementation.
203   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
204   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
205   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
206   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
207   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
208   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
209
210   // We want to custom lower some of our intrinsics.
211   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
212   
213   if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
214     // They also have instructions for converting between i64 and fp.
215     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
216     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
217     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
218     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
219     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
220  
221     // FIXME: disable this lowered code.  This generates 64-bit register values,
222     // and we don't model the fact that the top part is clobbered by calls.  We
223     // need to flag these together so that the value isn't live across a call.
224     //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
225     
226     // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
227     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
228   } else {
229     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
230     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
231   }
232
233   if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
234     // 64 bit PowerPC implementations can support i64 types directly
235     addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
236     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
237     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
238   } else {
239     // 32 bit PowerPC wants to expand i64 shifts itself.
240     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
241     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
242     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
243   }
244
245   if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
246     // First set operation action for all vector types to expand. Then we
247     // will selectively turn on ones that can be effectively codegen'd.
248     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
249          VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
250       // add/sub are legal for all supported vector VT's.
251       setOperationAction(ISD::ADD , (MVT::ValueType)VT, Legal);
252       setOperationAction(ISD::SUB , (MVT::ValueType)VT, Legal);
253       
254       // We promote all shuffles to v16i8.
255       setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Promote);
256       AddPromotedToType (ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, MVT::v16i8);
257
258       // We promote all non-typed operations to v4i32.
259       setOperationAction(ISD::AND   , (MVT::ValueType)VT, Promote);
260       AddPromotedToType (ISD::AND   , (MVT::ValueType)VT, MVT::v4i32);
261       setOperationAction(ISD::OR    , (MVT::ValueType)VT, Promote);
262       AddPromotedToType (ISD::OR    , (MVT::ValueType)VT, MVT::v4i32);
263       setOperationAction(ISD::XOR   , (MVT::ValueType)VT, Promote);
264       AddPromotedToType (ISD::XOR   , (MVT::ValueType)VT, MVT::v4i32);
265       setOperationAction(ISD::LOAD  , (MVT::ValueType)VT, Promote);
266       AddPromotedToType (ISD::LOAD  , (MVT::ValueType)VT, MVT::v4i32);
267       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
268       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v4i32);
269       setOperationAction(ISD::STORE, (MVT::ValueType)VT, Promote);
270       AddPromotedToType (ISD::STORE, (MVT::ValueType)VT, MVT::v4i32);
271       
272       // No other operations are legal.
273       setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
274       setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
275       setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
276       setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
277       setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
278       setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
279       setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
280       setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
281       setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
282       setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Expand);
283       setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
284       setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
285       setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
286       setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
287       setOperationAction(ISD::SCALAR_TO_VECTOR, (MVT::ValueType)VT, Expand);
288       setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
289       setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
290       setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
291       setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
292     }
293
294     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
295     // with merges, splats, etc.
296     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
297
298     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
299     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
300     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
301     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
302     setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
303     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
304     
305     addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
306     addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
307     addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
308     addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
309     
310     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
311     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
312     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
313     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
314
315     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
316     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
317     
318     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
319     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
320     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
321     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
322   }
323   
324   setSetCCResultType(MVT::i32);
325   setShiftAmountType(MVT::i32);
326   setSetCCResultContents(ZeroOrOneSetCCResult);
327   
328   if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
329     setStackPointerRegisterToSaveRestore(PPC::X1);
330     setExceptionPointerRegister(PPC::X3);
331     setExceptionSelectorRegister(PPC::X4);
332   } else {
333     setStackPointerRegisterToSaveRestore(PPC::R1);
334     setExceptionPointerRegister(PPC::R3);
335     setExceptionSelectorRegister(PPC::R4);
336   }
337   
338   // We have target-specific dag combine patterns for the following nodes:
339   setTargetDAGCombine(ISD::SINT_TO_FP);
340   setTargetDAGCombine(ISD::STORE);
341   setTargetDAGCombine(ISD::BR_CC);
342   setTargetDAGCombine(ISD::BSWAP);
343   
344   computeRegisterProperties();
345 }
346
347 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
348   switch (Opcode) {
349   default: return 0;
350   case PPCISD::FSEL:          return "PPCISD::FSEL";
351   case PPCISD::FCFID:         return "PPCISD::FCFID";
352   case PPCISD::FCTIDZ:        return "PPCISD::FCTIDZ";
353   case PPCISD::FCTIWZ:        return "PPCISD::FCTIWZ";
354   case PPCISD::STFIWX:        return "PPCISD::STFIWX";
355   case PPCISD::VMADDFP:       return "PPCISD::VMADDFP";
356   case PPCISD::VNMSUBFP:      return "PPCISD::VNMSUBFP";
357   case PPCISD::VPERM:         return "PPCISD::VPERM";
358   case PPCISD::Hi:            return "PPCISD::Hi";
359   case PPCISD::Lo:            return "PPCISD::Lo";
360   case PPCISD::DYNALLOC:      return "PPCISD::DYNALLOC";
361   case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
362   case PPCISD::SRL:           return "PPCISD::SRL";
363   case PPCISD::SRA:           return "PPCISD::SRA";
364   case PPCISD::SHL:           return "PPCISD::SHL";
365   case PPCISD::EXTSW_32:      return "PPCISD::EXTSW_32";
366   case PPCISD::STD_32:        return "PPCISD::STD_32";
367   case PPCISD::CALL_ELF:      return "PPCISD::CALL_ELF";
368   case PPCISD::CALL_Macho:    return "PPCISD::CALL_Macho";
369   case PPCISD::MTCTR:         return "PPCISD::MTCTR";
370   case PPCISD::BCTRL_Macho:   return "PPCISD::BCTRL_Macho";
371   case PPCISD::BCTRL_ELF:     return "PPCISD::BCTRL_ELF";
372   case PPCISD::RET_FLAG:      return "PPCISD::RET_FLAG";
373   case PPCISD::MFCR:          return "PPCISD::MFCR";
374   case PPCISD::VCMP:          return "PPCISD::VCMP";
375   case PPCISD::VCMPo:         return "PPCISD::VCMPo";
376   case PPCISD::LBRX:          return "PPCISD::LBRX";
377   case PPCISD::STBRX:         return "PPCISD::STBRX";
378   case PPCISD::COND_BRANCH:   return "PPCISD::COND_BRANCH";
379   }
380 }
381
382 //===----------------------------------------------------------------------===//
383 // Node matching predicates, for use by the tblgen matching code.
384 //===----------------------------------------------------------------------===//
385
386 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
387 static bool isFloatingPointZero(SDOperand Op) {
388   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
389     return CFP->getValueAPF().isZero();
390   else if (ISD::isEXTLoad(Op.Val) || ISD::isNON_EXTLoad(Op.Val)) {
391     // Maybe this has already been legalized into the constant pool?
392     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
393       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
394         return CFP->getValueAPF().isZero();
395   }
396   return false;
397 }
398
399 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
400 /// true if Op is undef or if it matches the specified value.
401 static bool isConstantOrUndef(SDOperand Op, unsigned Val) {
402   return Op.getOpcode() == ISD::UNDEF || 
403          cast<ConstantSDNode>(Op)->getValue() == Val;
404 }
405
406 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
407 /// VPKUHUM instruction.
408 bool PPC::isVPKUHUMShuffleMask(SDNode *N, bool isUnary) {
409   if (!isUnary) {
410     for (unsigned i = 0; i != 16; ++i)
411       if (!isConstantOrUndef(N->getOperand(i),  i*2+1))
412         return false;
413   } else {
414     for (unsigned i = 0; i != 8; ++i)
415       if (!isConstantOrUndef(N->getOperand(i),  i*2+1) ||
416           !isConstantOrUndef(N->getOperand(i+8),  i*2+1))
417         return false;
418   }
419   return true;
420 }
421
422 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
423 /// VPKUWUM instruction.
424 bool PPC::isVPKUWUMShuffleMask(SDNode *N, bool isUnary) {
425   if (!isUnary) {
426     for (unsigned i = 0; i != 16; i += 2)
427       if (!isConstantOrUndef(N->getOperand(i  ),  i*2+2) ||
428           !isConstantOrUndef(N->getOperand(i+1),  i*2+3))
429         return false;
430   } else {
431     for (unsigned i = 0; i != 8; i += 2)
432       if (!isConstantOrUndef(N->getOperand(i  ),  i*2+2) ||
433           !isConstantOrUndef(N->getOperand(i+1),  i*2+3) ||
434           !isConstantOrUndef(N->getOperand(i+8),  i*2+2) ||
435           !isConstantOrUndef(N->getOperand(i+9),  i*2+3))
436         return false;
437   }
438   return true;
439 }
440
441 /// isVMerge - Common function, used to match vmrg* shuffles.
442 ///
443 static bool isVMerge(SDNode *N, unsigned UnitSize, 
444                      unsigned LHSStart, unsigned RHSStart) {
445   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
446          N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
447   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
448          "Unsupported merge size!");
449   
450   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
451     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
452       if (!isConstantOrUndef(N->getOperand(i*UnitSize*2+j),
453                              LHSStart+j+i*UnitSize) ||
454           !isConstantOrUndef(N->getOperand(i*UnitSize*2+UnitSize+j),
455                              RHSStart+j+i*UnitSize))
456         return false;
457     }
458       return true;
459 }
460
461 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
462 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
463 bool PPC::isVMRGLShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
464   if (!isUnary)
465     return isVMerge(N, UnitSize, 8, 24);
466   return isVMerge(N, UnitSize, 8, 8);
467 }
468
469 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
470 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
471 bool PPC::isVMRGHShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
472   if (!isUnary)
473     return isVMerge(N, UnitSize, 0, 16);
474   return isVMerge(N, UnitSize, 0, 0);
475 }
476
477
478 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
479 /// amount, otherwise return -1.
480 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
481   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
482          N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
483   // Find the first non-undef value in the shuffle mask.
484   unsigned i;
485   for (i = 0; i != 16 && N->getOperand(i).getOpcode() == ISD::UNDEF; ++i)
486     /*search*/;
487   
488   if (i == 16) return -1;  // all undef.
489   
490   // Otherwise, check to see if the rest of the elements are consequtively
491   // numbered from this value.
492   unsigned ShiftAmt = cast<ConstantSDNode>(N->getOperand(i))->getValue();
493   if (ShiftAmt < i) return -1;
494   ShiftAmt -= i;
495
496   if (!isUnary) {
497     // Check the rest of the elements to see if they are consequtive.
498     for (++i; i != 16; ++i)
499       if (!isConstantOrUndef(N->getOperand(i), ShiftAmt+i))
500         return -1;
501   } else {
502     // Check the rest of the elements to see if they are consequtive.
503     for (++i; i != 16; ++i)
504       if (!isConstantOrUndef(N->getOperand(i), (ShiftAmt+i) & 15))
505         return -1;
506   }
507   
508   return ShiftAmt;
509 }
510
511 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
512 /// specifies a splat of a single element that is suitable for input to
513 /// VSPLTB/VSPLTH/VSPLTW.
514 bool PPC::isSplatShuffleMask(SDNode *N, unsigned EltSize) {
515   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
516          N->getNumOperands() == 16 &&
517          (EltSize == 1 || EltSize == 2 || EltSize == 4));
518   
519   // This is a splat operation if each element of the permute is the same, and
520   // if the value doesn't reference the second vector.
521   unsigned ElementBase = 0;
522   SDOperand Elt = N->getOperand(0);
523   if (ConstantSDNode *EltV = dyn_cast<ConstantSDNode>(Elt))
524     ElementBase = EltV->getValue();
525   else
526     return false;   // FIXME: Handle UNDEF elements too!
527
528   if (cast<ConstantSDNode>(Elt)->getValue() >= 16)
529     return false;
530   
531   // Check that they are consequtive.
532   for (unsigned i = 1; i != EltSize; ++i) {
533     if (!isa<ConstantSDNode>(N->getOperand(i)) ||
534         cast<ConstantSDNode>(N->getOperand(i))->getValue() != i+ElementBase)
535       return false;
536   }
537   
538   assert(isa<ConstantSDNode>(Elt) && "Invalid VECTOR_SHUFFLE mask!");
539   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
540     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
541     assert(isa<ConstantSDNode>(N->getOperand(i)) &&
542            "Invalid VECTOR_SHUFFLE mask!");
543     for (unsigned j = 0; j != EltSize; ++j)
544       if (N->getOperand(i+j) != N->getOperand(j))
545         return false;
546   }
547
548   return true;
549 }
550
551 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
552 /// are -0.0.
553 bool PPC::isAllNegativeZeroVector(SDNode *N) {
554   assert(N->getOpcode() == ISD::BUILD_VECTOR);
555   if (PPC::isSplatShuffleMask(N, N->getNumOperands()))
556     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N))
557       return CFP->getValueAPF().isNegZero();
558   return false;
559 }
560
561 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
562 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
563 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
564   assert(isSplatShuffleMask(N, EltSize));
565   return cast<ConstantSDNode>(N->getOperand(0))->getValue() / EltSize;
566 }
567
568 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
569 /// by using a vspltis[bhw] instruction of the specified element size, return
570 /// the constant being splatted.  The ByteSize field indicates the number of
571 /// bytes of each element [124] -> [bhw].
572 SDOperand PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
573   SDOperand OpVal(0, 0);
574
575   // If ByteSize of the splat is bigger than the element size of the
576   // build_vector, then we have a case where we are checking for a splat where
577   // multiple elements of the buildvector are folded together into a single
578   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
579   unsigned EltSize = 16/N->getNumOperands();
580   if (EltSize < ByteSize) {
581     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
582     SDOperand UniquedVals[4];
583     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
584     
585     // See if all of the elements in the buildvector agree across.
586     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
587       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
588       // If the element isn't a constant, bail fully out.
589       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDOperand();
590
591           
592       if (UniquedVals[i&(Multiple-1)].Val == 0)
593         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
594       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
595         return SDOperand();  // no match.
596     }
597     
598     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
599     // either constant or undef values that are identical for each chunk.  See
600     // if these chunks can form into a larger vspltis*.
601     
602     // Check to see if all of the leading entries are either 0 or -1.  If
603     // neither, then this won't fit into the immediate field.
604     bool LeadingZero = true;
605     bool LeadingOnes = true;
606     for (unsigned i = 0; i != Multiple-1; ++i) {
607       if (UniquedVals[i].Val == 0) continue;  // Must have been undefs.
608       
609       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
610       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
611     }
612     // Finally, check the least significant entry.
613     if (LeadingZero) {
614       if (UniquedVals[Multiple-1].Val == 0)
615         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
616       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getValue();
617       if (Val < 16)
618         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
619     }
620     if (LeadingOnes) {
621       if (UniquedVals[Multiple-1].Val == 0)
622         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
623       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSignExtended();
624       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
625         return DAG.getTargetConstant(Val, MVT::i32);
626     }
627     
628     return SDOperand();
629   }
630   
631   // Check to see if this buildvec has a single non-undef value in its elements.
632   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
633     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
634     if (OpVal.Val == 0)
635       OpVal = N->getOperand(i);
636     else if (OpVal != N->getOperand(i))
637       return SDOperand();
638   }
639   
640   if (OpVal.Val == 0) return SDOperand();  // All UNDEF: use implicit def.
641   
642   unsigned ValSizeInBytes = 0;
643   uint64_t Value = 0;
644   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
645     Value = CN->getValue();
646     ValSizeInBytes = MVT::getSizeInBits(CN->getValueType(0))/8;
647   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
648     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
649     Value = FloatToBits(CN->getValueAPF().convertToFloat());
650     ValSizeInBytes = 4;
651   }
652
653   // If the splat value is larger than the element value, then we can never do
654   // this splat.  The only case that we could fit the replicated bits into our
655   // immediate field for would be zero, and we prefer to use vxor for it.
656   if (ValSizeInBytes < ByteSize) return SDOperand();
657   
658   // If the element value is larger than the splat value, cut it in half and
659   // check to see if the two halves are equal.  Continue doing this until we
660   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
661   while (ValSizeInBytes > ByteSize) {
662     ValSizeInBytes >>= 1;
663     
664     // If the top half equals the bottom half, we're still ok.
665     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
666          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
667       return SDOperand();
668   }
669
670   // Properly sign extend the value.
671   int ShAmt = (4-ByteSize)*8;
672   int MaskVal = ((int)Value << ShAmt) >> ShAmt;
673   
674   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
675   if (MaskVal == 0) return SDOperand();
676
677   // Finally, if this value fits in a 5 bit sext field, return it
678   if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
679     return DAG.getTargetConstant(MaskVal, MVT::i32);
680   return SDOperand();
681 }
682
683 //===----------------------------------------------------------------------===//
684 //  Addressing Mode Selection
685 //===----------------------------------------------------------------------===//
686
687 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
688 /// or 64-bit immediate, and if the value can be accurately represented as a
689 /// sign extension from a 16-bit value.  If so, this returns true and the
690 /// immediate.
691 static bool isIntS16Immediate(SDNode *N, short &Imm) {
692   if (N->getOpcode() != ISD::Constant)
693     return false;
694   
695   Imm = (short)cast<ConstantSDNode>(N)->getValue();
696   if (N->getValueType(0) == MVT::i32)
697     return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
698   else
699     return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
700 }
701 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
702   return isIntS16Immediate(Op.Val, Imm);
703 }
704
705
706 /// SelectAddressRegReg - Given the specified addressed, check to see if it
707 /// can be represented as an indexed [r+r] operation.  Returns false if it
708 /// can be more efficiently represented with [r+imm].
709 bool PPCTargetLowering::SelectAddressRegReg(SDOperand N, SDOperand &Base,
710                                             SDOperand &Index,
711                                             SelectionDAG &DAG) {
712   short imm = 0;
713   if (N.getOpcode() == ISD::ADD) {
714     if (isIntS16Immediate(N.getOperand(1), imm))
715       return false;    // r+i
716     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
717       return false;    // r+i
718     
719     Base = N.getOperand(0);
720     Index = N.getOperand(1);
721     return true;
722   } else if (N.getOpcode() == ISD::OR) {
723     if (isIntS16Immediate(N.getOperand(1), imm))
724       return false;    // r+i can fold it if we can.
725     
726     // If this is an or of disjoint bitfields, we can codegen this as an add
727     // (for better address arithmetic) if the LHS and RHS of the OR are provably
728     // disjoint.
729     uint64_t LHSKnownZero, LHSKnownOne;
730     uint64_t RHSKnownZero, RHSKnownOne;
731     DAG.ComputeMaskedBits(N.getOperand(0), ~0U, LHSKnownZero, LHSKnownOne);
732     
733     if (LHSKnownZero) {
734       DAG.ComputeMaskedBits(N.getOperand(1), ~0U, RHSKnownZero, RHSKnownOne);
735       // If all of the bits are known zero on the LHS or RHS, the add won't
736       // carry.
737       if ((LHSKnownZero | RHSKnownZero) == ~0U) {
738         Base = N.getOperand(0);
739         Index = N.getOperand(1);
740         return true;
741       }
742     }
743   }
744   
745   return false;
746 }
747
748 /// Returns true if the address N can be represented by a base register plus
749 /// a signed 16-bit displacement [r+imm], and if it is not better
750 /// represented as reg+reg.
751 bool PPCTargetLowering::SelectAddressRegImm(SDOperand N, SDOperand &Disp,
752                                             SDOperand &Base, SelectionDAG &DAG){
753   // If this can be more profitably realized as r+r, fail.
754   if (SelectAddressRegReg(N, Disp, Base, DAG))
755     return false;
756   
757   if (N.getOpcode() == ISD::ADD) {
758     short imm = 0;
759     if (isIntS16Immediate(N.getOperand(1), imm)) {
760       Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
761       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
762         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
763       } else {
764         Base = N.getOperand(0);
765       }
766       return true; // [r+i]
767     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
768       // Match LOAD (ADD (X, Lo(G))).
769       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
770              && "Cannot handle constant offsets yet!");
771       Disp = N.getOperand(1).getOperand(0);  // The global address.
772       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
773              Disp.getOpcode() == ISD::TargetConstantPool ||
774              Disp.getOpcode() == ISD::TargetJumpTable);
775       Base = N.getOperand(0);
776       return true;  // [&g+r]
777     }
778   } else if (N.getOpcode() == ISD::OR) {
779     short imm = 0;
780     if (isIntS16Immediate(N.getOperand(1), imm)) {
781       // If this is an or of disjoint bitfields, we can codegen this as an add
782       // (for better address arithmetic) if the LHS and RHS of the OR are
783       // provably disjoint.
784       uint64_t LHSKnownZero, LHSKnownOne;
785       DAG.ComputeMaskedBits(N.getOperand(0), ~0U, LHSKnownZero, LHSKnownOne);
786       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
787         // If all of the bits are known zero on the LHS or RHS, the add won't
788         // carry.
789         Base = N.getOperand(0);
790         Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
791         return true;
792       }
793     }
794   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
795     // Loading from a constant address.
796     
797     // If this address fits entirely in a 16-bit sext immediate field, codegen
798     // this as "d, 0"
799     short Imm;
800     if (isIntS16Immediate(CN, Imm)) {
801       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
802       Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
803       return true;
804     }
805
806     // Handle 32-bit sext immediates with LIS + addr mode.
807     if (CN->getValueType(0) == MVT::i32 ||
808         (int64_t)CN->getValue() == (int)CN->getValue()) {
809       int Addr = (int)CN->getValue();
810       
811       // Otherwise, break this down into an LIS + disp.
812       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
813       
814       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
815       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
816       Base = SDOperand(DAG.getTargetNode(Opc, CN->getValueType(0), Base), 0);
817       return true;
818     }
819   }
820   
821   Disp = DAG.getTargetConstant(0, getPointerTy());
822   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
823     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
824   else
825     Base = N;
826   return true;      // [r+0]
827 }
828
829 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
830 /// represented as an indexed [r+r] operation.
831 bool PPCTargetLowering::SelectAddressRegRegOnly(SDOperand N, SDOperand &Base,
832                                                 SDOperand &Index,
833                                                 SelectionDAG &DAG) {
834   // Check to see if we can easily represent this as an [r+r] address.  This
835   // will fail if it thinks that the address is more profitably represented as
836   // reg+imm, e.g. where imm = 0.
837   if (SelectAddressRegReg(N, Base, Index, DAG))
838     return true;
839   
840   // If the operand is an addition, always emit this as [r+r], since this is
841   // better (for code size, and execution, as the memop does the add for free)
842   // than emitting an explicit add.
843   if (N.getOpcode() == ISD::ADD) {
844     Base = N.getOperand(0);
845     Index = N.getOperand(1);
846     return true;
847   }
848   
849   // Otherwise, do it the hard way, using R0 as the base register.
850   Base = DAG.getRegister(PPC::R0, N.getValueType());
851   Index = N;
852   return true;
853 }
854
855 /// SelectAddressRegImmShift - Returns true if the address N can be
856 /// represented by a base register plus a signed 14-bit displacement
857 /// [r+imm*4].  Suitable for use by STD and friends.
858 bool PPCTargetLowering::SelectAddressRegImmShift(SDOperand N, SDOperand &Disp,
859                                                  SDOperand &Base,
860                                                  SelectionDAG &DAG) {
861   // If this can be more profitably realized as r+r, fail.
862   if (SelectAddressRegReg(N, Disp, Base, DAG))
863     return false;
864   
865   if (N.getOpcode() == ISD::ADD) {
866     short imm = 0;
867     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
868       Disp =  DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
869       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
870         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
871       } else {
872         Base = N.getOperand(0);
873       }
874       return true; // [r+i]
875     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
876       // Match LOAD (ADD (X, Lo(G))).
877       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
878              && "Cannot handle constant offsets yet!");
879       Disp = N.getOperand(1).getOperand(0);  // The global address.
880       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
881              Disp.getOpcode() == ISD::TargetConstantPool ||
882              Disp.getOpcode() == ISD::TargetJumpTable);
883       Base = N.getOperand(0);
884       return true;  // [&g+r]
885     }
886   } else if (N.getOpcode() == ISD::OR) {
887     short imm = 0;
888     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
889       // If this is an or of disjoint bitfields, we can codegen this as an add
890       // (for better address arithmetic) if the LHS and RHS of the OR are
891       // provably disjoint.
892       uint64_t LHSKnownZero, LHSKnownOne;
893       DAG.ComputeMaskedBits(N.getOperand(0), ~0U, LHSKnownZero, LHSKnownOne);
894       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
895         // If all of the bits are known zero on the LHS or RHS, the add won't
896         // carry.
897         Base = N.getOperand(0);
898         Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
899         return true;
900       }
901     }
902   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
903     // Loading from a constant address.  Verify low two bits are clear.
904     if ((CN->getValue() & 3) == 0) {
905       // If this address fits entirely in a 14-bit sext immediate field, codegen
906       // this as "d, 0"
907       short Imm;
908       if (isIntS16Immediate(CN, Imm)) {
909         Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
910         Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
911         return true;
912       }
913     
914       // Fold the low-part of 32-bit absolute addresses into addr mode.
915       if (CN->getValueType(0) == MVT::i32 ||
916           (int64_t)CN->getValue() == (int)CN->getValue()) {
917         int Addr = (int)CN->getValue();
918       
919         // Otherwise, break this down into an LIS + disp.
920         Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
921         
922         Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
923         unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
924         Base = SDOperand(DAG.getTargetNode(Opc, CN->getValueType(0), Base), 0);
925         return true;
926       }
927     }
928   }
929   
930   Disp = DAG.getTargetConstant(0, getPointerTy());
931   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
932     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
933   else
934     Base = N;
935   return true;      // [r+0]
936 }
937
938
939 /// getPreIndexedAddressParts - returns true by value, base pointer and
940 /// offset pointer and addressing mode by reference if the node's address
941 /// can be legally represented as pre-indexed load / store address.
942 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
943                                                   SDOperand &Offset,
944                                                   ISD::MemIndexedMode &AM,
945                                                   SelectionDAG &DAG) {
946   // Disabled by default for now.
947   if (!EnablePPCPreinc) return false;
948   
949   SDOperand Ptr;
950   MVT::ValueType VT;
951   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
952     Ptr = LD->getBasePtr();
953     VT = LD->getLoadedVT();
954     
955   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
956     ST = ST;
957     Ptr = ST->getBasePtr();
958     VT  = ST->getStoredVT();
959   } else
960     return false;
961
962   // PowerPC doesn't have preinc load/store instructions for vectors.
963   if (MVT::isVector(VT))
964     return false;
965   
966   // TODO: Check reg+reg first.
967   
968   // LDU/STU use reg+imm*4, others use reg+imm.
969   if (VT != MVT::i64) {
970     // reg + imm
971     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
972       return false;
973   } else {
974     // reg + imm * 4.
975     if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
976       return false;
977   }
978
979   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
980     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
981     // sext i32 to i64 when addr mode is r+i.
982     if (LD->getValueType(0) == MVT::i64 && LD->getLoadedVT() == MVT::i32 &&
983         LD->getExtensionType() == ISD::SEXTLOAD &&
984         isa<ConstantSDNode>(Offset))
985       return false;
986   }    
987   
988   AM = ISD::PRE_INC;
989   return true;
990 }
991
992 //===----------------------------------------------------------------------===//
993 //  LowerOperation implementation
994 //===----------------------------------------------------------------------===//
995
996 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
997   MVT::ValueType PtrVT = Op.getValueType();
998   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
999   Constant *C = CP->getConstVal();
1000   SDOperand CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
1001   SDOperand Zero = DAG.getConstant(0, PtrVT);
1002
1003   const TargetMachine &TM = DAG.getTarget();
1004   
1005   SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, CPI, Zero);
1006   SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, CPI, Zero);
1007
1008   // If this is a non-darwin platform, we don't support non-static relo models
1009   // yet.
1010   if (TM.getRelocationModel() == Reloc::Static ||
1011       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1012     // Generate non-pic code that has direct accesses to the constant pool.
1013     // The address of the global is just (hi(&g)+lo(&g)).
1014     return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1015   }
1016   
1017   if (TM.getRelocationModel() == Reloc::PIC_) {
1018     // With PIC, the first instruction is actually "GR+hi(&G)".
1019     Hi = DAG.getNode(ISD::ADD, PtrVT,
1020                      DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
1021   }
1022   
1023   Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1024   return Lo;
1025 }
1026
1027 static SDOperand LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
1028   MVT::ValueType PtrVT = Op.getValueType();
1029   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1030   SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1031   SDOperand Zero = DAG.getConstant(0, PtrVT);
1032   
1033   const TargetMachine &TM = DAG.getTarget();
1034
1035   SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, JTI, Zero);
1036   SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, JTI, Zero);
1037
1038   // If this is a non-darwin platform, we don't support non-static relo models
1039   // yet.
1040   if (TM.getRelocationModel() == Reloc::Static ||
1041       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1042     // Generate non-pic code that has direct accesses to the constant pool.
1043     // The address of the global is just (hi(&g)+lo(&g)).
1044     return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1045   }
1046   
1047   if (TM.getRelocationModel() == Reloc::PIC_) {
1048     // With PIC, the first instruction is actually "GR+hi(&G)".
1049     Hi = DAG.getNode(ISD::ADD, PtrVT,
1050                      DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
1051   }
1052   
1053   Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1054   return Lo;
1055 }
1056
1057 static SDOperand LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
1058   assert(0 && "TLS not implemented for PPC.");
1059 }
1060
1061 static SDOperand LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
1062   MVT::ValueType PtrVT = Op.getValueType();
1063   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1064   GlobalValue *GV = GSDN->getGlobal();
1065   SDOperand GA = DAG.getTargetGlobalAddress(GV, PtrVT, GSDN->getOffset());
1066   SDOperand Zero = DAG.getConstant(0, PtrVT);
1067   
1068   const TargetMachine &TM = DAG.getTarget();
1069
1070   SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, GA, Zero);
1071   SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, GA, Zero);
1072
1073   // If this is a non-darwin platform, we don't support non-static relo models
1074   // yet.
1075   if (TM.getRelocationModel() == Reloc::Static ||
1076       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1077     // Generate non-pic code that has direct accesses to globals.
1078     // The address of the global is just (hi(&g)+lo(&g)).
1079     return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1080   }
1081   
1082   if (TM.getRelocationModel() == Reloc::PIC_) {
1083     // With PIC, the first instruction is actually "GR+hi(&G)".
1084     Hi = DAG.getNode(ISD::ADD, PtrVT,
1085                      DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
1086   }
1087   
1088   Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1089   
1090   if (!TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV))
1091     return Lo;
1092   
1093   // If the global is weak or external, we have to go through the lazy
1094   // resolution stub.
1095   return DAG.getLoad(PtrVT, DAG.getEntryNode(), Lo, NULL, 0);
1096 }
1097
1098 static SDOperand LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
1099   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1100   
1101   // If we're comparing for equality to zero, expose the fact that this is
1102   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1103   // fold the new nodes.
1104   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1105     if (C->isNullValue() && CC == ISD::SETEQ) {
1106       MVT::ValueType VT = Op.getOperand(0).getValueType();
1107       SDOperand Zext = Op.getOperand(0);
1108       if (VT < MVT::i32) {
1109         VT = MVT::i32;
1110         Zext = DAG.getNode(ISD::ZERO_EXTEND, VT, Op.getOperand(0));
1111       } 
1112       unsigned Log2b = Log2_32(MVT::getSizeInBits(VT));
1113       SDOperand Clz = DAG.getNode(ISD::CTLZ, VT, Zext);
1114       SDOperand Scc = DAG.getNode(ISD::SRL, VT, Clz,
1115                                   DAG.getConstant(Log2b, MVT::i32));
1116       return DAG.getNode(ISD::TRUNCATE, MVT::i32, Scc);
1117     }
1118     // Leave comparisons against 0 and -1 alone for now, since they're usually 
1119     // optimized.  FIXME: revisit this when we can custom lower all setcc
1120     // optimizations.
1121     if (C->isAllOnesValue() || C->isNullValue())
1122       return SDOperand();
1123   }
1124   
1125   // If we have an integer seteq/setne, turn it into a compare against zero
1126   // by xor'ing the rhs with the lhs, which is faster than setting a
1127   // condition register, reading it back out, and masking the correct bit.  The
1128   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1129   // the result to other bit-twiddling opportunities.
1130   MVT::ValueType LHSVT = Op.getOperand(0).getValueType();
1131   if (MVT::isInteger(LHSVT) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1132     MVT::ValueType VT = Op.getValueType();
1133     SDOperand Sub = DAG.getNode(ISD::XOR, LHSVT, Op.getOperand(0), 
1134                                 Op.getOperand(1));
1135     return DAG.getSetCC(VT, Sub, DAG.getConstant(0, LHSVT), CC);
1136   }
1137   return SDOperand();
1138 }
1139
1140 static SDOperand LowerVAARG(SDOperand Op, SelectionDAG &DAG,
1141                               int VarArgsFrameIndex,
1142                               int VarArgsStackOffset,
1143                               unsigned VarArgsNumGPR,
1144                               unsigned VarArgsNumFPR,
1145                               const PPCSubtarget &Subtarget) {
1146   
1147   assert(0 && "VAARG in ELF32 ABI not implemented yet!");
1148 }
1149
1150 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
1151                               int VarArgsFrameIndex,
1152                               int VarArgsStackOffset,
1153                               unsigned VarArgsNumGPR,
1154                               unsigned VarArgsNumFPR,
1155                               const PPCSubtarget &Subtarget) {
1156
1157   if (Subtarget.isMachoABI()) {
1158     // vastart just stores the address of the VarArgsFrameIndex slot into the
1159     // memory location argument.
1160     MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1161     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1162     SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
1163     return DAG.getStore(Op.getOperand(0), FR, Op.getOperand(1), SV->getValue(),
1164                         SV->getOffset());
1165   }
1166
1167   // For ELF 32 ABI we follow the layout of the va_list struct.
1168   // We suppose the given va_list is already allocated.
1169   //
1170   // typedef struct {
1171   //  char gpr;     /* index into the array of 8 GPRs
1172   //                 * stored in the register save area
1173   //                 * gpr=0 corresponds to r3,
1174   //                 * gpr=1 to r4, etc.
1175   //                 */
1176   //  char fpr;     /* index into the array of 8 FPRs
1177   //                 * stored in the register save area
1178   //                 * fpr=0 corresponds to f1,
1179   //                 * fpr=1 to f2, etc.
1180   //                 */
1181   //  char *overflow_arg_area;
1182   //                /* location on stack that holds
1183   //                 * the next overflow argument
1184   //                 */
1185   //  char *reg_save_area;
1186   //               /* where r3:r10 and f1:f8 (if saved)
1187   //                * are stored
1188   //                */
1189   // } va_list[1];
1190
1191
1192   SDOperand ArgGPR = DAG.getConstant(VarArgsNumGPR, MVT::i8);
1193   SDOperand ArgFPR = DAG.getConstant(VarArgsNumFPR, MVT::i8);
1194   
1195
1196   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1197   
1198   SDOperand StackOffset = DAG.getFrameIndex(VarArgsStackOffset, PtrVT);
1199   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1200   
1201   SDOperand ConstFrameOffset = DAG.getConstant(MVT::getSizeInBits(PtrVT)/8,
1202                                                PtrVT);
1203   SDOperand ConstStackOffset = DAG.getConstant(MVT::getSizeInBits(PtrVT)/8 - 1,
1204                                                PtrVT);
1205   SDOperand ConstFPROffset   = DAG.getConstant(1, PtrVT);
1206   
1207   SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
1208   
1209   // Store first byte : number of int regs
1210   SDOperand firstStore = DAG.getStore(Op.getOperand(0), ArgGPR,
1211                                       Op.getOperand(1), SV->getValue(),
1212                                       SV->getOffset());
1213   SDOperand nextPtr = DAG.getNode(ISD::ADD, PtrVT, Op.getOperand(1),
1214                                   ConstFPROffset);
1215   
1216   // Store second byte : number of float regs
1217   SDOperand secondStore = DAG.getStore(firstStore, ArgFPR, nextPtr,
1218                                        SV->getValue(), SV->getOffset());
1219   nextPtr = DAG.getNode(ISD::ADD, PtrVT, nextPtr, ConstStackOffset);
1220   
1221   // Store second word : arguments given on stack
1222   SDOperand thirdStore = DAG.getStore(secondStore, StackOffset, nextPtr,
1223                                       SV->getValue(), SV->getOffset());
1224   nextPtr = DAG.getNode(ISD::ADD, PtrVT, nextPtr, ConstFrameOffset);
1225
1226   // Store third word : arguments given in registers
1227   return DAG.getStore(thirdStore, FR, nextPtr, SV->getValue(),
1228                       SV->getOffset());
1229
1230 }
1231
1232 #include "PPCGenCallingConv.inc"
1233
1234 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1235 /// depending on which subtarget is selected.
1236 static const unsigned *GetFPR(const PPCSubtarget &Subtarget) {
1237   if (Subtarget.isMachoABI()) {
1238     static const unsigned FPR[] = {
1239       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1240       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1241     };
1242     return FPR;
1243   }
1244   
1245   
1246   static const unsigned FPR[] = {
1247     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1248     PPC::F8
1249   };
1250   return FPR;
1251 }
1252
1253 static SDOperand LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG,
1254                                        int &VarArgsFrameIndex,
1255                                        int &VarArgsStackOffset,
1256                                        unsigned &VarArgsNumGPR,
1257                                        unsigned &VarArgsNumFPR,
1258                                        const PPCSubtarget &Subtarget) {
1259   // TODO: add description of PPC stack frame format, or at least some docs.
1260   //
1261   MachineFunction &MF = DAG.getMachineFunction();
1262   MachineFrameInfo *MFI = MF.getFrameInfo();
1263   SSARegMap *RegMap = MF.getSSARegMap();
1264   SmallVector<SDOperand, 8> ArgValues;
1265   SDOperand Root = Op.getOperand(0);
1266   
1267   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1268   bool isPPC64 = PtrVT == MVT::i64;
1269   bool isMachoABI = Subtarget.isMachoABI();
1270   bool isELF32_ABI = Subtarget.isELF32_ABI();
1271   unsigned PtrByteSize = isPPC64 ? 8 : 4;
1272
1273   unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1274   
1275   static const unsigned GPR_32[] = {           // 32-bit registers.
1276     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1277     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1278   };
1279   static const unsigned GPR_64[] = {           // 64-bit registers.
1280     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1281     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1282   };
1283   
1284   static const unsigned *FPR = GetFPR(Subtarget);
1285   
1286   static const unsigned VR[] = {
1287     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1288     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1289   };
1290
1291   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
1292   const unsigned Num_FPR_Regs = isMachoABI ? 13 : 8;
1293   const unsigned Num_VR_Regs  = array_lengthof( VR);
1294
1295   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1296   
1297   const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1298   
1299   // Add DAG nodes to load the arguments or copy them out of registers.  On
1300   // entry to a function on PPC, the arguments start after the linkage area,
1301   // although the first ones are often in registers.
1302   // 
1303   // In the ELF 32 ABI, GPRs and stack are double word align: an argument
1304   // represented with two words (long long or double) must be copied to an
1305   // even GPR_idx value or to an even ArgOffset value.
1306
1307   for (unsigned ArgNo = 0, e = Op.Val->getNumValues()-1; ArgNo != e; ++ArgNo) {
1308     SDOperand ArgVal;
1309     bool needsLoad = false;
1310     MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
1311     unsigned ObjSize = MVT::getSizeInBits(ObjectVT)/8;
1312     unsigned ArgSize = ObjSize;
1313     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(ArgNo+3))->getValue();
1314     unsigned AlignFlag = 1 << ISD::ParamFlags::OrigAlignmentOffs;
1315     // See if next argument requires stack alignment in ELF
1316     bool Expand = (ObjectVT == MVT::f64) || ((ArgNo + 1 < e) &&
1317       (cast<ConstantSDNode>(Op.getOperand(ArgNo+4))->getValue() & AlignFlag) &&
1318       (!(Flags & AlignFlag)));
1319
1320     unsigned CurArgOffset = ArgOffset;
1321     switch (ObjectVT) {
1322     default: assert(0 && "Unhandled argument type!");
1323     case MVT::i32:
1324       // Double word align in ELF
1325       if (Expand && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1326       if (GPR_idx != Num_GPR_Regs) {
1327         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
1328         MF.addLiveIn(GPR[GPR_idx], VReg);
1329         ArgVal = DAG.getCopyFromReg(Root, VReg, MVT::i32);
1330         ++GPR_idx;
1331       } else {
1332         needsLoad = true;
1333         ArgSize = PtrByteSize;
1334       }
1335       // Stack align in ELF
1336       if (needsLoad && Expand && isELF32_ABI) 
1337         ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1338       // All int arguments reserve stack space in Macho ABI.
1339       if (isMachoABI || needsLoad) ArgOffset += PtrByteSize;
1340       break;
1341       
1342     case MVT::i64:  // PPC64
1343       if (GPR_idx != Num_GPR_Regs) {
1344         unsigned VReg = RegMap->createVirtualRegister(&PPC::G8RCRegClass);
1345         MF.addLiveIn(GPR[GPR_idx], VReg);
1346         ArgVal = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1347         ++GPR_idx;
1348       } else {
1349         needsLoad = true;
1350       }
1351       // All int arguments reserve stack space in Macho ABI.
1352       if (isMachoABI || needsLoad) ArgOffset += 8;
1353       break;
1354       
1355     case MVT::f32:
1356     case MVT::f64:
1357       // Every 4 bytes of argument space consumes one of the GPRs available for
1358       // argument passing.
1359       if (GPR_idx != Num_GPR_Regs && isMachoABI) {
1360         ++GPR_idx;
1361         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
1362           ++GPR_idx;
1363       }
1364       if (FPR_idx != Num_FPR_Regs) {
1365         unsigned VReg;
1366         if (ObjectVT == MVT::f32)
1367           VReg = RegMap->createVirtualRegister(&PPC::F4RCRegClass);
1368         else
1369           VReg = RegMap->createVirtualRegister(&PPC::F8RCRegClass);
1370         MF.addLiveIn(FPR[FPR_idx], VReg);
1371         ArgVal = DAG.getCopyFromReg(Root, VReg, ObjectVT);
1372         ++FPR_idx;
1373       } else {
1374         needsLoad = true;
1375       }
1376       
1377       // Stack align in ELF
1378       if (needsLoad && Expand && isELF32_ABI)
1379         ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1380       // All FP arguments reserve stack space in Macho ABI.
1381       if (isMachoABI || needsLoad) ArgOffset += isPPC64 ? 8 : ObjSize;
1382       break;
1383     case MVT::v4f32:
1384     case MVT::v4i32:
1385     case MVT::v8i16:
1386     case MVT::v16i8:
1387       // Note that vector arguments in registers don't reserve stack space.
1388       if (VR_idx != Num_VR_Regs) {
1389         unsigned VReg = RegMap->createVirtualRegister(&PPC::VRRCRegClass);
1390         MF.addLiveIn(VR[VR_idx], VReg);
1391         ArgVal = DAG.getCopyFromReg(Root, VReg, ObjectVT);
1392         ++VR_idx;
1393       } else {
1394         // This should be simple, but requires getting 16-byte aligned stack
1395         // values.
1396         assert(0 && "Loading VR argument not implemented yet!");
1397         needsLoad = true;
1398       }
1399       break;
1400     }
1401     
1402     // We need to load the argument to a virtual register if we determined above
1403     // that we ran out of physical registers of the appropriate type
1404     if (needsLoad) {
1405       // If the argument is actually used, emit a load from the right stack
1406       // slot.
1407       if (!Op.Val->hasNUsesOfValue(0, ArgNo)) {
1408         int FI = MFI->CreateFixedObject(ObjSize,
1409                                         CurArgOffset + (ArgSize - ObjSize));
1410         SDOperand FIN = DAG.getFrameIndex(FI, PtrVT);
1411         ArgVal = DAG.getLoad(ObjectVT, Root, FIN, NULL, 0);
1412       } else {
1413         // Don't emit a dead load.
1414         ArgVal = DAG.getNode(ISD::UNDEF, ObjectVT);
1415       }
1416     }
1417     
1418     ArgValues.push_back(ArgVal);
1419   }
1420   
1421   // If the function takes variable number of arguments, make a frame index for
1422   // the start of the first vararg value... for expansion of llvm.va_start.
1423   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1424   if (isVarArg) {
1425     
1426     int depth;
1427     if (isELF32_ABI) {
1428       VarArgsNumGPR = GPR_idx;
1429       VarArgsNumFPR = FPR_idx;
1430    
1431       // Make room for Num_GPR_Regs, Num_FPR_Regs and for a possible frame
1432       // pointer.
1433       depth = -(Num_GPR_Regs * MVT::getSizeInBits(PtrVT)/8 +
1434                 Num_FPR_Regs * MVT::getSizeInBits(MVT::f64)/8 +
1435                 MVT::getSizeInBits(PtrVT)/8);
1436       
1437       VarArgsStackOffset = MFI->CreateFixedObject(MVT::getSizeInBits(PtrVT)/8,
1438                                                   ArgOffset);
1439
1440     }
1441     else
1442       depth = ArgOffset;
1443     
1444     VarArgsFrameIndex = MFI->CreateFixedObject(MVT::getSizeInBits(PtrVT)/8,
1445                                                depth);
1446     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1447     
1448     SmallVector<SDOperand, 8> MemOps;
1449     
1450     // In ELF 32 ABI, the fixed integer arguments of a variadic function are
1451     // stored to the VarArgsFrameIndex on the stack.
1452     if (isELF32_ABI) {
1453       for (GPR_idx = 0; GPR_idx != VarArgsNumGPR; ++GPR_idx) {
1454         SDOperand Val = DAG.getRegister(GPR[GPR_idx], PtrVT);
1455         SDOperand Store = DAG.getStore(Root, Val, FIN, NULL, 0);
1456         MemOps.push_back(Store);
1457         // Increment the address by four for the next argument to store
1458         SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(PtrVT)/8, PtrVT);
1459         FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1460       }
1461     }
1462
1463     // If this function is vararg, store any remaining integer argument regs
1464     // to their spots on the stack so that they may be loaded by deferencing the
1465     // result of va_next.
1466     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
1467       unsigned VReg;
1468       if (isPPC64)
1469         VReg = RegMap->createVirtualRegister(&PPC::G8RCRegClass);
1470       else
1471         VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
1472
1473       MF.addLiveIn(GPR[GPR_idx], VReg);
1474       SDOperand Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
1475       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1476       MemOps.push_back(Store);
1477       // Increment the address by four for the next argument to store
1478       SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(PtrVT)/8, PtrVT);
1479       FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1480     }
1481
1482     // In ELF 32 ABI, the double arguments are stored to the VarArgsFrameIndex
1483     // on the stack.
1484     if (isELF32_ABI) {
1485       for (FPR_idx = 0; FPR_idx != VarArgsNumFPR; ++FPR_idx) {
1486         SDOperand Val = DAG.getRegister(FPR[FPR_idx], MVT::f64);
1487         SDOperand Store = DAG.getStore(Root, Val, FIN, NULL, 0);
1488         MemOps.push_back(Store);
1489         // Increment the address by eight for the next argument to store
1490         SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(MVT::f64)/8,
1491                                            PtrVT);
1492         FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1493       }
1494
1495       for (; FPR_idx != Num_FPR_Regs; ++FPR_idx) {
1496         unsigned VReg;
1497         VReg = RegMap->createVirtualRegister(&PPC::F8RCRegClass);
1498
1499         MF.addLiveIn(FPR[FPR_idx], VReg);
1500         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::f64);
1501         SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1502         MemOps.push_back(Store);
1503         // Increment the address by eight for the next argument to store
1504         SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(MVT::f64)/8,
1505                                            PtrVT);
1506         FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1507       }
1508     }
1509
1510     if (!MemOps.empty())
1511       Root = DAG.getNode(ISD::TokenFactor, MVT::Other,&MemOps[0],MemOps.size());
1512   }
1513   
1514   ArgValues.push_back(Root);
1515  
1516   // Return the new list of results.
1517   std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
1518                                     Op.Val->value_end());
1519   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
1520 }
1521
1522 /// isCallCompatibleAddress - Return the immediate to use if the specified
1523 /// 32-bit value is representable in the immediate field of a BxA instruction.
1524 static SDNode *isBLACompatibleAddress(SDOperand Op, SelectionDAG &DAG) {
1525   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1526   if (!C) return 0;
1527   
1528   int Addr = C->getValue();
1529   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
1530       (Addr << 6 >> 6) != Addr)
1531     return 0;  // Top 6 bits have to be sext of immediate.
1532   
1533   return DAG.getConstant((int)C->getValue() >> 2, MVT::i32).Val;
1534 }
1535
1536
1537 static SDOperand LowerCALL(SDOperand Op, SelectionDAG &DAG,
1538                            const PPCSubtarget &Subtarget) {
1539   SDOperand Chain  = Op.getOperand(0);
1540   bool isVarArg    = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1541   SDOperand Callee = Op.getOperand(4);
1542   unsigned NumOps  = (Op.getNumOperands() - 5) / 2;
1543   
1544   bool isMachoABI = Subtarget.isMachoABI();
1545   bool isELF32_ABI  = Subtarget.isELF32_ABI();
1546
1547   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1548   bool isPPC64 = PtrVT == MVT::i64;
1549   unsigned PtrByteSize = isPPC64 ? 8 : 4;
1550   
1551   // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
1552   // SelectExpr to use to put the arguments in the appropriate registers.
1553   std::vector<SDOperand> args_to_use;
1554   
1555   // Count how many bytes are to be pushed on the stack, including the linkage
1556   // area, and parameter passing area.  We start with 24/48 bytes, which is
1557   // prereserved space for [SP][CR][LR][3 x unused].
1558   unsigned NumBytes = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1559   
1560   // Add up all the space actually used.
1561   for (unsigned i = 0; i != NumOps; ++i) {
1562     unsigned ArgSize =MVT::getSizeInBits(Op.getOperand(5+2*i).getValueType())/8;
1563     ArgSize = std::max(ArgSize, PtrByteSize);
1564     NumBytes += ArgSize;
1565   }
1566
1567   // The prolog code of the callee may store up to 8 GPR argument registers to
1568   // the stack, allowing va_start to index over them in memory if its varargs.
1569   // Because we cannot tell if this is needed on the caller side, we have to
1570   // conservatively assume that it is needed.  As such, make sure we have at
1571   // least enough stack space for the caller to store the 8 GPRs.
1572   NumBytes = std::max(NumBytes,
1573                       PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
1574   
1575   // Adjust the stack pointer for the new arguments...
1576   // These operations are automatically eliminated by the prolog/epilog pass
1577   Chain = DAG.getCALLSEQ_START(Chain,
1578                                DAG.getConstant(NumBytes, PtrVT));
1579   
1580   // Set up a copy of the stack pointer for use loading and storing any
1581   // arguments that may not fit in the registers available for argument
1582   // passing.
1583   SDOperand StackPtr;
1584   if (isPPC64)
1585     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
1586   else
1587     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
1588   
1589   // Figure out which arguments are going to go in registers, and which in
1590   // memory.  Also, if this is a vararg function, floating point operations
1591   // must be stored to our stack, and loaded into integer regs as well, if
1592   // any integer regs are available for argument passing.
1593   unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1594   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1595   
1596   static const unsigned GPR_32[] = {           // 32-bit registers.
1597     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1598     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1599   };
1600   static const unsigned GPR_64[] = {           // 64-bit registers.
1601     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1602     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1603   };
1604   static const unsigned *FPR = GetFPR(Subtarget);
1605   
1606   static const unsigned VR[] = {
1607     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1608     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1609   };
1610   const unsigned NumGPRs = array_lengthof(GPR_32);
1611   const unsigned NumFPRs = isMachoABI ? 13 : 8;
1612   const unsigned NumVRs  = array_lengthof( VR);
1613   
1614   const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1615
1616   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
1617   SmallVector<SDOperand, 8> MemOpChains;
1618   for (unsigned i = 0; i != NumOps; ++i) {
1619     bool inMem = false;
1620     SDOperand Arg = Op.getOperand(5+2*i);
1621     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(5+2*i+1))->getValue();
1622     unsigned AlignFlag = 1 << ISD::ParamFlags::OrigAlignmentOffs;
1623     // See if next argument requires stack alignment in ELF
1624     unsigned next = 5+2*(i+1)+1;
1625     bool Expand = (Arg.getValueType() == MVT::f64) || ((i + 1 < NumOps) &&
1626       (cast<ConstantSDNode>(Op.getOperand(next))->getValue() & AlignFlag) &&
1627       (!(Flags & AlignFlag)));
1628
1629     // PtrOff will be used to store the current argument to the stack if a
1630     // register cannot be found for it.
1631     SDOperand PtrOff;
1632     
1633     // Stack align in ELF 32
1634     if (isELF32_ABI && Expand)
1635       PtrOff = DAG.getConstant(ArgOffset + ((ArgOffset/4) % 2) * PtrByteSize,
1636                                StackPtr.getValueType());
1637     else
1638       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
1639
1640     PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr, PtrOff);
1641
1642     // On PPC64, promote integers to 64-bit values.
1643     if (isPPC64 && Arg.getValueType() == MVT::i32) {
1644       unsigned ExtOp = (Flags & 1) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1645
1646       Arg = DAG.getNode(ExtOp, MVT::i64, Arg);
1647     }
1648     
1649     switch (Arg.getValueType()) {
1650     default: assert(0 && "Unexpected ValueType for argument!");
1651     case MVT::i32:
1652     case MVT::i64:
1653       // Double word align in ELF
1654       if (isELF32_ABI && Expand) GPR_idx += (GPR_idx % 2);
1655       if (GPR_idx != NumGPRs) {
1656         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
1657       } else {
1658         MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1659         inMem = true;
1660       }
1661       if (inMem || isMachoABI) {
1662         // Stack align in ELF
1663         if (isELF32_ABI && Expand)
1664           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1665
1666         ArgOffset += PtrByteSize;
1667       }
1668       break;
1669     case MVT::f32:
1670     case MVT::f64:
1671       if (isVarArg) {
1672         // Float varargs need to be promoted to double.
1673         if (Arg.getValueType() == MVT::f32)
1674           Arg = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Arg);
1675       }
1676     
1677       if (FPR_idx != NumFPRs) {
1678         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
1679
1680         if (isVarArg) {
1681           SDOperand Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1682           MemOpChains.push_back(Store);
1683
1684           // Float varargs are always shadowed in available integer registers
1685           if (GPR_idx != NumGPRs) {
1686             SDOperand Load = DAG.getLoad(PtrVT, Store, PtrOff, NULL, 0);
1687             MemOpChains.push_back(Load.getValue(1));
1688             if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
1689                                                                 Load));
1690           }
1691           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
1692             SDOperand ConstFour = DAG.getConstant(4, PtrOff.getValueType());
1693             PtrOff = DAG.getNode(ISD::ADD, PtrVT, PtrOff, ConstFour);
1694             SDOperand Load = DAG.getLoad(PtrVT, Store, PtrOff, NULL, 0);
1695             MemOpChains.push_back(Load.getValue(1));
1696             if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
1697                                                                 Load));
1698           }
1699         } else {
1700           // If we have any FPRs remaining, we may also have GPRs remaining.
1701           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
1702           // GPRs.
1703           if (isMachoABI) {
1704             if (GPR_idx != NumGPRs)
1705               ++GPR_idx;
1706             if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
1707                 !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
1708               ++GPR_idx;
1709           }
1710         }
1711       } else {
1712         MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1713         inMem = true;
1714       }
1715       if (inMem || isMachoABI) {
1716         // Stack align in ELF
1717         if (isELF32_ABI && Expand)
1718           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1719         if (isPPC64)
1720           ArgOffset += 8;
1721         else
1722           ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
1723       }
1724       break;
1725     case MVT::v4f32:
1726     case MVT::v4i32:
1727     case MVT::v8i16:
1728     case MVT::v16i8:
1729       assert(!isVarArg && "Don't support passing vectors to varargs yet!");
1730       assert(VR_idx != NumVRs &&
1731              "Don't support passing more than 12 vector args yet!");
1732       RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
1733       break;
1734     }
1735   }
1736   if (!MemOpChains.empty())
1737     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1738                         &MemOpChains[0], MemOpChains.size());
1739   
1740   // Build a sequence of copy-to-reg nodes chained together with token chain
1741   // and flag operands which copy the outgoing args into the appropriate regs.
1742   SDOperand InFlag;
1743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1744     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1745                              InFlag);
1746     InFlag = Chain.getValue(1);
1747   }
1748  
1749   // With the ELF 32 ABI, set CR6 to true if this is a vararg call.
1750   if (isVarArg && isELF32_ABI) {
1751     SDOperand SetCR(DAG.getTargetNode(PPC::SETCR, MVT::i32), 0);
1752     Chain = DAG.getCopyToReg(Chain, PPC::CR6, SetCR, InFlag);
1753     InFlag = Chain.getValue(1);
1754   }
1755
1756   std::vector<MVT::ValueType> NodeTys;
1757   NodeTys.push_back(MVT::Other);   // Returns a chain
1758   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
1759
1760   SmallVector<SDOperand, 8> Ops;
1761   unsigned CallOpc = isMachoABI? PPCISD::CALL_Macho : PPCISD::CALL_ELF;
1762   
1763   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1764   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1765   // node so that legalize doesn't hack it.
1766   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1767     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
1768   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1769     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
1770   else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
1771     // If this is an absolute destination address, use the munged value.
1772     Callee = SDOperand(Dest, 0);
1773   else {
1774     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
1775     // to do the call, we can't use PPCISD::CALL.
1776     SDOperand MTCTROps[] = {Chain, Callee, InFlag};
1777     Chain = DAG.getNode(PPCISD::MTCTR, NodeTys, MTCTROps, 2+(InFlag.Val!=0));
1778     InFlag = Chain.getValue(1);
1779     
1780     // Copy the callee address into R12 on darwin.
1781     if (isMachoABI) {
1782       Chain = DAG.getCopyToReg(Chain, PPC::R12, Callee, InFlag);
1783       InFlag = Chain.getValue(1);
1784     }
1785
1786     NodeTys.clear();
1787     NodeTys.push_back(MVT::Other);
1788     NodeTys.push_back(MVT::Flag);
1789     Ops.push_back(Chain);
1790     CallOpc = isMachoABI ? PPCISD::BCTRL_Macho : PPCISD::BCTRL_ELF;
1791     Callee.Val = 0;
1792   }
1793
1794   // If this is a direct call, pass the chain and the callee.
1795   if (Callee.Val) {
1796     Ops.push_back(Chain);
1797     Ops.push_back(Callee);
1798   }
1799   
1800   // Add argument registers to the end of the list so that they are known live
1801   // into the call.
1802   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1803     Ops.push_back(DAG.getRegister(RegsToPass[i].first, 
1804                                   RegsToPass[i].second.getValueType()));
1805   
1806   if (InFlag.Val)
1807     Ops.push_back(InFlag);
1808   Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
1809   InFlag = Chain.getValue(1);
1810
1811   SDOperand ResultVals[3];
1812   unsigned NumResults = 0;
1813   NodeTys.clear();
1814   
1815   // If the call has results, copy the values out of the ret val registers.
1816   switch (Op.Val->getValueType(0)) {
1817   default: assert(0 && "Unexpected ret value!");
1818   case MVT::Other: break;
1819   case MVT::i32:
1820     if (Op.Val->getValueType(1) == MVT::i32) {
1821       Chain = DAG.getCopyFromReg(Chain, PPC::R3, MVT::i32, InFlag).getValue(1);
1822       ResultVals[0] = Chain.getValue(0);
1823       Chain = DAG.getCopyFromReg(Chain, PPC::R4, MVT::i32,
1824                                  Chain.getValue(2)).getValue(1);
1825       ResultVals[1] = Chain.getValue(0);
1826       NumResults = 2;
1827       NodeTys.push_back(MVT::i32);
1828     } else {
1829       Chain = DAG.getCopyFromReg(Chain, PPC::R3, MVT::i32, InFlag).getValue(1);
1830       ResultVals[0] = Chain.getValue(0);
1831       NumResults = 1;
1832     }
1833     NodeTys.push_back(MVT::i32);
1834     break;
1835   case MVT::i64:
1836     Chain = DAG.getCopyFromReg(Chain, PPC::X3, MVT::i64, InFlag).getValue(1);
1837     ResultVals[0] = Chain.getValue(0);
1838     NumResults = 1;
1839     NodeTys.push_back(MVT::i64);
1840     break;
1841   case MVT::f64:
1842     if (Op.Val->getValueType(1) == MVT::f64) {
1843       Chain = DAG.getCopyFromReg(Chain, PPC::F1, MVT::f64, InFlag).getValue(1);
1844       ResultVals[0] = Chain.getValue(0);
1845       Chain = DAG.getCopyFromReg(Chain, PPC::F2, MVT::f64,
1846                                  Chain.getValue(2)).getValue(1);
1847       ResultVals[1] = Chain.getValue(0);
1848       NumResults = 2;
1849       NodeTys.push_back(MVT::f64);
1850       NodeTys.push_back(MVT::f64);
1851       break;
1852     } 
1853     // else fall through
1854   case MVT::f32:
1855     Chain = DAG.getCopyFromReg(Chain, PPC::F1, Op.Val->getValueType(0),
1856                                InFlag).getValue(1);
1857     ResultVals[0] = Chain.getValue(0);
1858     NumResults = 1;
1859     NodeTys.push_back(Op.Val->getValueType(0));
1860     break;
1861   case MVT::v4f32:
1862   case MVT::v4i32:
1863   case MVT::v8i16:
1864   case MVT::v16i8:
1865     Chain = DAG.getCopyFromReg(Chain, PPC::V2, Op.Val->getValueType(0),
1866                                    InFlag).getValue(1);
1867     ResultVals[0] = Chain.getValue(0);
1868     NumResults = 1;
1869     NodeTys.push_back(Op.Val->getValueType(0));
1870     break;
1871   }
1872   
1873   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
1874                       DAG.getConstant(NumBytes, PtrVT));
1875   NodeTys.push_back(MVT::Other);
1876   
1877   // If the function returns void, just return the chain.
1878   if (NumResults == 0)
1879     return Chain;
1880   
1881   // Otherwise, merge everything together with a MERGE_VALUES node.
1882   ResultVals[NumResults++] = Chain;
1883   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys,
1884                               ResultVals, NumResults);
1885   return Res.getValue(Op.ResNo);
1886 }
1887
1888 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG, TargetMachine &TM) {
1889   SmallVector<CCValAssign, 16> RVLocs;
1890   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
1891   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1892   CCState CCInfo(CC, isVarArg, TM, RVLocs);
1893   CCInfo.AnalyzeReturn(Op.Val, RetCC_PPC);
1894   
1895   // If this is the first return lowered for this function, add the regs to the
1896   // liveout set for the function.
1897   if (DAG.getMachineFunction().liveout_empty()) {
1898     for (unsigned i = 0; i != RVLocs.size(); ++i)
1899       DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
1900   }
1901
1902   SDOperand Chain = Op.getOperand(0);
1903   SDOperand Flag;
1904   
1905   // Copy the result values into the output registers.
1906   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1907     CCValAssign &VA = RVLocs[i];
1908     assert(VA.isRegLoc() && "Can only return in registers!");
1909     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
1910     Flag = Chain.getValue(1);
1911   }
1912
1913   if (Flag.Val)
1914     return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Chain, Flag);
1915   else
1916     return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Chain);
1917 }
1918
1919 static SDOperand LowerSTACKRESTORE(SDOperand Op, SelectionDAG &DAG,
1920                                    const PPCSubtarget &Subtarget) {
1921   // When we pop the dynamic allocation we need to restore the SP link.
1922   
1923   // Get the corect type for pointers.
1924   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1925
1926   // Construct the stack pointer operand.
1927   bool IsPPC64 = Subtarget.isPPC64();
1928   unsigned SP = IsPPC64 ? PPC::X1 : PPC::R1;
1929   SDOperand StackPtr = DAG.getRegister(SP, PtrVT);
1930
1931   // Get the operands for the STACKRESTORE.
1932   SDOperand Chain = Op.getOperand(0);
1933   SDOperand SaveSP = Op.getOperand(1);
1934   
1935   // Load the old link SP.
1936   SDOperand LoadLinkSP = DAG.getLoad(PtrVT, Chain, StackPtr, NULL, 0);
1937   
1938   // Restore the stack pointer.
1939   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), SP, SaveSP);
1940   
1941   // Store the old link SP.
1942   return DAG.getStore(Chain, LoadLinkSP, StackPtr, NULL, 0);
1943 }
1944
1945 static SDOperand LowerDYNAMIC_STACKALLOC(SDOperand Op, SelectionDAG &DAG,
1946                                          const PPCSubtarget &Subtarget) {
1947   MachineFunction &MF = DAG.getMachineFunction();
1948   bool IsPPC64 = Subtarget.isPPC64();
1949   bool isMachoABI = Subtarget.isMachoABI();
1950
1951   // Get current frame pointer save index.  The users of this index will be
1952   // primarily DYNALLOC instructions.
1953   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1954   int FPSI = FI->getFramePointerSaveIndex();
1955    
1956   // If the frame pointer save index hasn't been defined yet.
1957   if (!FPSI) {
1958     // Find out what the fix offset of the frame pointer save area.
1959     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isMachoABI);
1960     
1961     // Allocate the frame index for frame pointer save area.
1962     FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset); 
1963     // Save the result.
1964     FI->setFramePointerSaveIndex(FPSI);                      
1965   }
1966
1967   // Get the inputs.
1968   SDOperand Chain = Op.getOperand(0);
1969   SDOperand Size  = Op.getOperand(1);
1970   
1971   // Get the corect type for pointers.
1972   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1973   // Negate the size.
1974   SDOperand NegSize = DAG.getNode(ISD::SUB, PtrVT,
1975                                   DAG.getConstant(0, PtrVT), Size);
1976   // Construct a node for the frame pointer save index.
1977   SDOperand FPSIdx = DAG.getFrameIndex(FPSI, PtrVT);
1978   // Build a DYNALLOC node.
1979   SDOperand Ops[3] = { Chain, NegSize, FPSIdx };
1980   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
1981   return DAG.getNode(PPCISD::DYNALLOC, VTs, Ops, 3);
1982 }
1983
1984
1985 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
1986 /// possible.
1987 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) {
1988   // Not FP? Not a fsel.
1989   if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
1990       !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
1991     return SDOperand();
1992   
1993   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1994   
1995   // Cannot handle SETEQ/SETNE.
1996   if (CC == ISD::SETEQ || CC == ISD::SETNE) return SDOperand();
1997   
1998   MVT::ValueType ResVT = Op.getValueType();
1999   MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
2000   SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2001   SDOperand TV  = Op.getOperand(2), FV  = Op.getOperand(3);
2002   
2003   // If the RHS of the comparison is a 0.0, we don't need to do the
2004   // subtraction at all.
2005   if (isFloatingPointZero(RHS))
2006     switch (CC) {
2007     default: break;       // SETUO etc aren't handled by fsel.
2008     case ISD::SETULT:
2009     case ISD::SETOLT:
2010     case ISD::SETLT:
2011       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2012     case ISD::SETUGE:
2013     case ISD::SETOGE:
2014     case ISD::SETGE:
2015       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
2016         LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
2017       return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
2018     case ISD::SETUGT:
2019     case ISD::SETOGT:
2020     case ISD::SETGT:
2021       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2022     case ISD::SETULE:
2023     case ISD::SETOLE:
2024     case ISD::SETLE:
2025       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
2026         LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
2027       return DAG.getNode(PPCISD::FSEL, ResVT,
2028                          DAG.getNode(ISD::FNEG, MVT::f64, LHS), TV, FV);
2029     }
2030       
2031   SDOperand Cmp;
2032   switch (CC) {
2033   default: break;       // SETUO etc aren't handled by fsel.
2034   case ISD::SETULT:
2035   case ISD::SETOLT:
2036   case ISD::SETLT:
2037     Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
2038     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2039       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2040       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
2041   case ISD::SETUGE:
2042   case ISD::SETOGE:
2043   case ISD::SETGE:
2044     Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
2045     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2046       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2047       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
2048   case ISD::SETUGT:
2049   case ISD::SETOGT:
2050   case ISD::SETGT:
2051     Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
2052     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2053       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2054       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
2055   case ISD::SETULE:
2056   case ISD::SETOLE:
2057   case ISD::SETLE:
2058     Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
2059     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2060       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2061       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
2062   }
2063   return SDOperand();
2064 }
2065
2066 static SDOperand LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
2067   assert(MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
2068   SDOperand Src = Op.getOperand(0);
2069   if (Src.getValueType() == MVT::f32)
2070     Src = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Src);
2071   
2072   SDOperand Tmp;
2073   switch (Op.getValueType()) {
2074   default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
2075   case MVT::i32:
2076     Tmp = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Src);
2077     break;
2078   case MVT::i64:
2079     Tmp = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Src);
2080     break;
2081   }
2082   
2083   // Convert the FP value to an int value through memory.
2084   SDOperand FIPtr = DAG.CreateStackTemporary(MVT::f64);
2085   
2086   // Emit a store to the stack slot.
2087   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Tmp, FIPtr, NULL, 0);
2088
2089   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
2090   // add in a bias.
2091   if (Op.getValueType() == MVT::i32)
2092     FIPtr = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr,
2093                         DAG.getConstant(4, FIPtr.getValueType()));
2094   return DAG.getLoad(Op.getValueType(), Chain, FIPtr, NULL, 0);
2095 }
2096
2097 static SDOperand LowerFP_ROUND_INREG(SDOperand Op, SelectionDAG &DAG) {
2098   assert(Op.getValueType() == MVT::ppcf128);
2099   SDNode *Node = Op.Val;
2100   assert(Node->getOperand(0).getValueType() == MVT::ppcf128);
2101   assert(Node->getOperand(0).Val->getOpcode()==ISD::BUILD_PAIR);
2102   SDOperand Lo = Node->getOperand(0).Val->getOperand(0);
2103   SDOperand Hi = Node->getOperand(0).Val->getOperand(1);
2104
2105   // This sequence changes FPSCR to do round-to-zero, adds the two halves
2106   // of the long double, and puts FPSCR back the way it was.  We do not
2107   // actually model FPSCR.
2108   std::vector<MVT::ValueType> NodeTys;
2109   SDOperand Ops[4], Result, MFFSreg, InFlag, FPreg;
2110
2111   NodeTys.push_back(MVT::f64);   // Return register
2112   NodeTys.push_back(MVT::Flag);    // Returns a flag for later insns
2113   Result = DAG.getNode(PPCISD::MFFS, NodeTys, &InFlag, 0);
2114   MFFSreg = Result.getValue(0);
2115   InFlag = Result.getValue(1);
2116
2117   NodeTys.clear();
2118   NodeTys.push_back(MVT::Flag);   // Returns a flag
2119   Ops[0] = DAG.getConstant(31, MVT::i32);
2120   Ops[1] = InFlag;
2121   Result = DAG.getNode(PPCISD::MTFSB1, NodeTys, Ops, 2);
2122   InFlag = Result.getValue(0);
2123
2124   NodeTys.clear();
2125   NodeTys.push_back(MVT::Flag);   // Returns a flag
2126   Ops[0] = DAG.getConstant(30, MVT::i32);
2127   Ops[1] = InFlag;
2128   Result = DAG.getNode(PPCISD::MTFSB0, NodeTys, Ops, 2);
2129   InFlag = Result.getValue(0);
2130
2131   NodeTys.clear();
2132   NodeTys.push_back(MVT::f64);    // result of add
2133   NodeTys.push_back(MVT::Flag);   // Returns a flag
2134   Ops[0] = Lo;
2135   Ops[1] = Hi;
2136   Ops[2] = InFlag;
2137   Result = DAG.getNode(PPCISD::FADDRTZ, NodeTys, Ops, 3);
2138   FPreg = Result.getValue(0);
2139   InFlag = Result.getValue(1);
2140
2141   NodeTys.clear();
2142   NodeTys.push_back(MVT::f64);
2143   Ops[0] = DAG.getConstant(1, MVT::i32);
2144   Ops[1] = MFFSreg;
2145   Ops[2] = FPreg;
2146   Ops[3] = InFlag;
2147   Result = DAG.getNode(PPCISD::MTFSF, NodeTys, Ops, 4);
2148   FPreg = Result.getValue(0);
2149
2150   // We know the low half is about to be thrown away, so just use something
2151   // convenient.
2152   return DAG.getNode(ISD::BUILD_PAIR, Lo.getValueType(), FPreg, FPreg);
2153 }
2154
2155 static SDOperand LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
2156   if (Op.getOperand(0).getValueType() == MVT::i64) {
2157     SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, Op.getOperand(0));
2158     SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Bits);
2159     if (Op.getValueType() == MVT::f32)
2160       FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
2161     return FP;
2162   }
2163   
2164   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2165          "Unhandled SINT_TO_FP type in custom expander!");
2166   // Since we only generate this in 64-bit mode, we can take advantage of
2167   // 64-bit registers.  In particular, sign extend the input value into the
2168   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
2169   // then lfd it and fcfid it.
2170   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2171   int FrameIdx = FrameInfo->CreateStackObject(8, 8);
2172   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2173   SDOperand FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
2174   
2175   SDOperand Ext64 = DAG.getNode(PPCISD::EXTSW_32, MVT::i32,
2176                                 Op.getOperand(0));
2177   
2178   // STD the extended value into the stack slot.
2179   SDOperand Store = DAG.getNode(PPCISD::STD_32, MVT::Other,
2180                                 DAG.getEntryNode(), Ext64, FIdx,
2181                                 DAG.getSrcValue(NULL));
2182   // Load the value as a double.
2183   SDOperand Ld = DAG.getLoad(MVT::f64, Store, FIdx, NULL, 0);
2184   
2185   // FCFID it and return it.
2186   SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Ld);
2187   if (Op.getValueType() == MVT::f32)
2188     FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
2189   return FP;
2190 }
2191
2192 static SDOperand LowerSHL_PARTS(SDOperand Op, SelectionDAG &DAG) {
2193   assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
2194          Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
2195   
2196   // Expand into a bunch of logical ops.  Note that these ops
2197   // depend on the PPC behavior for oversized shift amounts.
2198   SDOperand Lo = Op.getOperand(0);
2199   SDOperand Hi = Op.getOperand(1);
2200   SDOperand Amt = Op.getOperand(2);
2201   
2202   SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
2203                                DAG.getConstant(32, MVT::i32), Amt);
2204   SDOperand Tmp2 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Amt);
2205   SDOperand Tmp3 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Tmp1);
2206   SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
2207   SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
2208                                DAG.getConstant(-32U, MVT::i32));
2209   SDOperand Tmp6 = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Tmp5);
2210   SDOperand OutHi = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
2211   SDOperand OutLo = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Amt);
2212   SDOperand OutOps[] = { OutLo, OutHi };
2213   return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(MVT::i32, MVT::i32),
2214                      OutOps, 2);
2215 }
2216
2217 static SDOperand LowerSRL_PARTS(SDOperand Op, SelectionDAG &DAG) {
2218   assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
2219          Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRL!");
2220   
2221   // Otherwise, expand into a bunch of logical ops.  Note that these ops
2222   // depend on the PPC behavior for oversized shift amounts.
2223   SDOperand Lo = Op.getOperand(0);
2224   SDOperand Hi = Op.getOperand(1);
2225   SDOperand Amt = Op.getOperand(2);
2226   
2227   SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
2228                                DAG.getConstant(32, MVT::i32), Amt);
2229   SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
2230   SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
2231   SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
2232   SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
2233                                DAG.getConstant(-32U, MVT::i32));
2234   SDOperand Tmp6 = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Tmp5);
2235   SDOperand OutLo = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
2236   SDOperand OutHi = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Amt);
2237   SDOperand OutOps[] = { OutLo, OutHi };
2238   return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(MVT::i32, MVT::i32),
2239                      OutOps, 2);
2240 }
2241
2242 static SDOperand LowerSRA_PARTS(SDOperand Op, SelectionDAG &DAG) {
2243   assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
2244          Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRA!");
2245   
2246   // Otherwise, expand into a bunch of logical ops, followed by a select_cc.
2247   SDOperand Lo = Op.getOperand(0);
2248   SDOperand Hi = Op.getOperand(1);
2249   SDOperand Amt = Op.getOperand(2);
2250   
2251   SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
2252                                DAG.getConstant(32, MVT::i32), Amt);
2253   SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
2254   SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
2255   SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
2256   SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
2257                                DAG.getConstant(-32U, MVT::i32));
2258   SDOperand Tmp6 = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Tmp5);
2259   SDOperand OutHi = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Amt);
2260   SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, MVT::i32),
2261                                     Tmp4, Tmp6, ISD::SETLE);
2262   SDOperand OutOps[] = { OutLo, OutHi };
2263   return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(MVT::i32, MVT::i32),
2264                      OutOps, 2);
2265 }
2266
2267 //===----------------------------------------------------------------------===//
2268 // Vector related lowering.
2269 //
2270
2271 // If this is a vector of constants or undefs, get the bits.  A bit in
2272 // UndefBits is set if the corresponding element of the vector is an 
2273 // ISD::UNDEF value.  For undefs, the corresponding VectorBits values are
2274 // zero.   Return true if this is not an array of constants, false if it is.
2275 //
2276 static bool GetConstantBuildVectorBits(SDNode *BV, uint64_t VectorBits[2],
2277                                        uint64_t UndefBits[2]) {
2278   // Start with zero'd results.
2279   VectorBits[0] = VectorBits[1] = UndefBits[0] = UndefBits[1] = 0;
2280   
2281   unsigned EltBitSize = MVT::getSizeInBits(BV->getOperand(0).getValueType());
2282   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2283     SDOperand OpVal = BV->getOperand(i);
2284     
2285     unsigned PartNo = i >= e/2;     // In the upper 128 bits?
2286     unsigned SlotNo = e/2 - (i & (e/2-1))-1;  // Which subpiece of the uint64_t.
2287
2288     uint64_t EltBits = 0;
2289     if (OpVal.getOpcode() == ISD::UNDEF) {
2290       uint64_t EltUndefBits = ~0U >> (32-EltBitSize);
2291       UndefBits[PartNo] |= EltUndefBits << (SlotNo*EltBitSize);
2292       continue;
2293     } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2294       EltBits = CN->getValue() & (~0U >> (32-EltBitSize));
2295     } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2296       assert(CN->getValueType(0) == MVT::f32 &&
2297              "Only one legal FP vector type!");
2298       EltBits = FloatToBits(CN->getValueAPF().convertToFloat());
2299     } else {
2300       // Nonconstant element.
2301       return true;
2302     }
2303     
2304     VectorBits[PartNo] |= EltBits << (SlotNo*EltBitSize);
2305   }
2306   
2307   //printf("%llx %llx  %llx %llx\n", 
2308   //       VectorBits[0], VectorBits[1], UndefBits[0], UndefBits[1]);
2309   return false;
2310 }
2311
2312 // If this is a splat (repetition) of a value across the whole vector, return
2313 // the smallest size that splats it.  For example, "0x01010101010101..." is a
2314 // splat of 0x01, 0x0101, and 0x01010101.  We return SplatBits = 0x01 and 
2315 // SplatSize = 1 byte.
2316 static bool isConstantSplat(const uint64_t Bits128[2], 
2317                             const uint64_t Undef128[2],
2318                             unsigned &SplatBits, unsigned &SplatUndef,
2319                             unsigned &SplatSize) {
2320   
2321   // Don't let undefs prevent splats from matching.  See if the top 64-bits are
2322   // the same as the lower 64-bits, ignoring undefs.
2323   if ((Bits128[0] & ~Undef128[1]) != (Bits128[1] & ~Undef128[0]))
2324     return false;  // Can't be a splat if two pieces don't match.
2325   
2326   uint64_t Bits64  = Bits128[0] | Bits128[1];
2327   uint64_t Undef64 = Undef128[0] & Undef128[1];
2328   
2329   // Check that the top 32-bits are the same as the lower 32-bits, ignoring
2330   // undefs.
2331   if ((Bits64 & (~Undef64 >> 32)) != ((Bits64 >> 32) & ~Undef64))
2332     return false;  // Can't be a splat if two pieces don't match.
2333
2334   uint32_t Bits32  = uint32_t(Bits64) | uint32_t(Bits64 >> 32);
2335   uint32_t Undef32 = uint32_t(Undef64) & uint32_t(Undef64 >> 32);
2336
2337   // If the top 16-bits are different than the lower 16-bits, ignoring
2338   // undefs, we have an i32 splat.
2339   if ((Bits32 & (~Undef32 >> 16)) != ((Bits32 >> 16) & ~Undef32)) {
2340     SplatBits = Bits32;
2341     SplatUndef = Undef32;
2342     SplatSize = 4;
2343     return true;
2344   }
2345   
2346   uint16_t Bits16  = uint16_t(Bits32)  | uint16_t(Bits32 >> 16);
2347   uint16_t Undef16 = uint16_t(Undef32) & uint16_t(Undef32 >> 16);
2348
2349   // If the top 8-bits are different than the lower 8-bits, ignoring
2350   // undefs, we have an i16 splat.
2351   if ((Bits16 & (uint16_t(~Undef16) >> 8)) != ((Bits16 >> 8) & ~Undef16)) {
2352     SplatBits = Bits16;
2353     SplatUndef = Undef16;
2354     SplatSize = 2;
2355     return true;
2356   }
2357   
2358   // Otherwise, we have an 8-bit splat.
2359   SplatBits  = uint8_t(Bits16)  | uint8_t(Bits16 >> 8);
2360   SplatUndef = uint8_t(Undef16) & uint8_t(Undef16 >> 8);
2361   SplatSize = 1;
2362   return true;
2363 }
2364
2365 /// BuildSplatI - Build a canonical splati of Val with an element size of
2366 /// SplatSize.  Cast the result to VT.
2367 static SDOperand BuildSplatI(int Val, unsigned SplatSize, MVT::ValueType VT,
2368                              SelectionDAG &DAG) {
2369   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
2370
2371   static const MVT::ValueType VTys[] = { // canonical VT to use for each size.
2372     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
2373   };
2374
2375   MVT::ValueType ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
2376   
2377   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
2378   if (Val == -1)
2379     SplatSize = 1;
2380   
2381   MVT::ValueType CanonicalVT = VTys[SplatSize-1];
2382   
2383   // Build a canonical splat for this value.
2384   SDOperand Elt = DAG.getConstant(Val, MVT::getVectorElementType(CanonicalVT));
2385   SmallVector<SDOperand, 8> Ops;
2386   Ops.assign(MVT::getVectorNumElements(CanonicalVT), Elt);
2387   SDOperand Res = DAG.getNode(ISD::BUILD_VECTOR, CanonicalVT,
2388                               &Ops[0], Ops.size());
2389   return DAG.getNode(ISD::BIT_CONVERT, ReqVT, Res);
2390 }
2391
2392 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
2393 /// specified intrinsic ID.
2394 static SDOperand BuildIntrinsicOp(unsigned IID, SDOperand LHS, SDOperand RHS,
2395                                   SelectionDAG &DAG, 
2396                                   MVT::ValueType DestVT = MVT::Other) {
2397   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
2398   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DestVT,
2399                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
2400 }
2401
2402 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
2403 /// specified intrinsic ID.
2404 static SDOperand BuildIntrinsicOp(unsigned IID, SDOperand Op0, SDOperand Op1,
2405                                   SDOperand Op2, SelectionDAG &DAG, 
2406                                   MVT::ValueType DestVT = MVT::Other) {
2407   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
2408   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DestVT,
2409                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
2410 }
2411
2412
2413 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
2414 /// amount.  The result has the specified value type.
2415 static SDOperand BuildVSLDOI(SDOperand LHS, SDOperand RHS, unsigned Amt,
2416                              MVT::ValueType VT, SelectionDAG &DAG) {
2417   // Force LHS/RHS to be the right type.
2418   LHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, LHS);
2419   RHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, RHS);
2420   
2421   SDOperand Ops[16];
2422   for (unsigned i = 0; i != 16; ++i)
2423     Ops[i] = DAG.getConstant(i+Amt, MVT::i32);
2424   SDOperand T = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v16i8, LHS, RHS,
2425                             DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops,16));
2426   return DAG.getNode(ISD::BIT_CONVERT, VT, T);
2427 }
2428
2429 // If this is a case we can't handle, return null and let the default
2430 // expansion code take care of it.  If we CAN select this case, and if it
2431 // selects to a single instruction, return Op.  Otherwise, if we can codegen
2432 // this case more efficiently than a constant pool load, lower it to the
2433 // sequence of ops that should be used.
2434 static SDOperand LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2435   // If this is a vector of constants or undefs, get the bits.  A bit in
2436   // UndefBits is set if the corresponding element of the vector is an 
2437   // ISD::UNDEF value.  For undefs, the corresponding VectorBits values are
2438   // zero. 
2439   uint64_t VectorBits[2];
2440   uint64_t UndefBits[2];
2441   if (GetConstantBuildVectorBits(Op.Val, VectorBits, UndefBits))
2442     return SDOperand();   // Not a constant vector.
2443   
2444   // If this is a splat (repetition) of a value across the whole vector, return
2445   // the smallest size that splats it.  For example, "0x01010101010101..." is a
2446   // splat of 0x01, 0x0101, and 0x01010101.  We return SplatBits = 0x01 and 
2447   // SplatSize = 1 byte.
2448   unsigned SplatBits, SplatUndef, SplatSize;
2449   if (isConstantSplat(VectorBits, UndefBits, SplatBits, SplatUndef, SplatSize)){
2450     bool HasAnyUndefs = (UndefBits[0] | UndefBits[1]) != 0;
2451     
2452     // First, handle single instruction cases.
2453     
2454     // All zeros?
2455     if (SplatBits == 0) {
2456       // Canonicalize all zero vectors to be v4i32.
2457       if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
2458         SDOperand Z = DAG.getConstant(0, MVT::i32);
2459         Z = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Z, Z, Z, Z);
2460         Op = DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Z);
2461       }
2462       return Op;
2463     }
2464
2465     // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
2466     int32_t SextVal= int32_t(SplatBits << (32-8*SplatSize)) >> (32-8*SplatSize);
2467     if (SextVal >= -16 && SextVal <= 15)
2468       return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG);
2469     
2470     
2471     // Two instruction sequences.
2472     
2473     // If this value is in the range [-32,30] and is even, use:
2474     //    tmp = VSPLTI[bhw], result = add tmp, tmp
2475     if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
2476       Op = BuildSplatI(SextVal >> 1, SplatSize, Op.getValueType(), DAG);
2477       return DAG.getNode(ISD::ADD, Op.getValueType(), Op, Op);
2478     }
2479     
2480     // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is 
2481     // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
2482     // for fneg/fabs.
2483     if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
2484       // Make -1 and vspltisw -1:
2485       SDOperand OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG);
2486       
2487       // Make the VSLW intrinsic, computing 0x8000_0000.
2488       SDOperand Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 
2489                                        OnesV, DAG);
2490       
2491       // xor by OnesV to invert it.
2492       Res = DAG.getNode(ISD::XOR, MVT::v4i32, Res, OnesV);
2493       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
2494     }
2495
2496     // Check to see if this is a wide variety of vsplti*, binop self cases.
2497     unsigned SplatBitSize = SplatSize*8;
2498     static const signed char SplatCsts[] = {
2499       -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
2500       -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
2501     };
2502     
2503     for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
2504       // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
2505       // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
2506       int i = SplatCsts[idx];
2507       
2508       // Figure out what shift amount will be used by altivec if shifted by i in
2509       // this splat size.
2510       unsigned TypeShiftAmt = i & (SplatBitSize-1);
2511       
2512       // vsplti + shl self.
2513       if (SextVal == (i << (int)TypeShiftAmt)) {
2514         SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
2515         static const unsigned IIDs[] = { // Intrinsic to use for each size.
2516           Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
2517           Intrinsic::ppc_altivec_vslw
2518         };
2519         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
2520         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
2521       }
2522       
2523       // vsplti + srl self.
2524       if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
2525         SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
2526         static const unsigned IIDs[] = { // Intrinsic to use for each size.
2527           Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
2528           Intrinsic::ppc_altivec_vsrw
2529         };
2530         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
2531         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
2532       }
2533       
2534       // vsplti + sra self.
2535       if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
2536         SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
2537         static const unsigned IIDs[] = { // Intrinsic to use for each size.
2538           Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
2539           Intrinsic::ppc_altivec_vsraw
2540         };
2541         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
2542         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
2543       }
2544       
2545       // vsplti + rol self.
2546       if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
2547                            ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
2548         SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
2549         static const unsigned IIDs[] = { // Intrinsic to use for each size.
2550           Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
2551           Intrinsic::ppc_altivec_vrlw
2552         };
2553         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
2554         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
2555       }
2556
2557       // t = vsplti c, result = vsldoi t, t, 1
2558       if (SextVal == ((i << 8) | (i >> (TypeShiftAmt-8)))) {
2559         SDOperand T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
2560         return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG);
2561       }
2562       // t = vsplti c, result = vsldoi t, t, 2
2563       if (SextVal == ((i << 16) | (i >> (TypeShiftAmt-16)))) {
2564         SDOperand T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
2565         return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG);
2566       }
2567       // t = vsplti c, result = vsldoi t, t, 3
2568       if (SextVal == ((i << 24) | (i >> (TypeShiftAmt-24)))) {
2569         SDOperand T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
2570         return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG);
2571       }
2572     }
2573     
2574     // Three instruction sequences.
2575     
2576     // Odd, in range [17,31]:  (vsplti C)-(vsplti -16).
2577     if (SextVal >= 0 && SextVal <= 31) {
2578       SDOperand LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG);
2579       SDOperand RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG);
2580       LHS = DAG.getNode(ISD::SUB, LHS.getValueType(), LHS, RHS);
2581       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), LHS);
2582     }
2583     // Odd, in range [-31,-17]:  (vsplti C)+(vsplti -16).
2584     if (SextVal >= -31 && SextVal <= 0) {
2585       SDOperand LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG);
2586       SDOperand RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG);
2587       LHS = DAG.getNode(ISD::ADD, LHS.getValueType(), LHS, RHS);
2588       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), LHS);
2589     }
2590   }
2591     
2592   return SDOperand();
2593 }
2594
2595 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
2596 /// the specified operations to build the shuffle.
2597 static SDOperand GeneratePerfectShuffle(unsigned PFEntry, SDOperand LHS,
2598                                         SDOperand RHS, SelectionDAG &DAG) {
2599   unsigned OpNum = (PFEntry >> 26) & 0x0F;
2600   unsigned LHSID  = (PFEntry >> 13) & ((1 << 13)-1);
2601   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
2602   
2603   enum {
2604     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
2605     OP_VMRGHW,
2606     OP_VMRGLW,
2607     OP_VSPLTISW0,
2608     OP_VSPLTISW1,
2609     OP_VSPLTISW2,
2610     OP_VSPLTISW3,
2611     OP_VSLDOI4,
2612     OP_VSLDOI8,
2613     OP_VSLDOI12
2614   };
2615   
2616   if (OpNum == OP_COPY) {
2617     if (LHSID == (1*9+2)*9+3) return LHS;
2618     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
2619     return RHS;
2620   }
2621   
2622   SDOperand OpLHS, OpRHS;
2623   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG);
2624   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG);
2625   
2626   unsigned ShufIdxs[16];
2627   switch (OpNum) {
2628   default: assert(0 && "Unknown i32 permute!");
2629   case OP_VMRGHW:
2630     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
2631     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
2632     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
2633     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
2634     break;
2635   case OP_VMRGLW:
2636     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
2637     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
2638     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
2639     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
2640     break;
2641   case OP_VSPLTISW0:
2642     for (unsigned i = 0; i != 16; ++i)
2643       ShufIdxs[i] = (i&3)+0;
2644     break;
2645   case OP_VSPLTISW1:
2646     for (unsigned i = 0; i != 16; ++i)
2647       ShufIdxs[i] = (i&3)+4;
2648     break;
2649   case OP_VSPLTISW2:
2650     for (unsigned i = 0; i != 16; ++i)
2651       ShufIdxs[i] = (i&3)+8;
2652     break;
2653   case OP_VSPLTISW3:
2654     for (unsigned i = 0; i != 16; ++i)
2655       ShufIdxs[i] = (i&3)+12;
2656     break;
2657   case OP_VSLDOI4:
2658     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG);
2659   case OP_VSLDOI8:
2660     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG);
2661   case OP_VSLDOI12:
2662     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG);
2663   }
2664   SDOperand Ops[16];
2665   for (unsigned i = 0; i != 16; ++i)
2666     Ops[i] = DAG.getConstant(ShufIdxs[i], MVT::i32);
2667   
2668   return DAG.getNode(ISD::VECTOR_SHUFFLE, OpLHS.getValueType(), OpLHS, OpRHS,
2669                      DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops, 16));
2670 }
2671
2672 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
2673 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
2674 /// return the code it can be lowered into.  Worst case, it can always be
2675 /// lowered into a vperm.
2676 static SDOperand LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2677   SDOperand V1 = Op.getOperand(0);
2678   SDOperand V2 = Op.getOperand(1);
2679   SDOperand PermMask = Op.getOperand(2);
2680   
2681   // Cases that are handled by instructions that take permute immediates
2682   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
2683   // selected by the instruction selector.
2684   if (V2.getOpcode() == ISD::UNDEF) {
2685     if (PPC::isSplatShuffleMask(PermMask.Val, 1) ||
2686         PPC::isSplatShuffleMask(PermMask.Val, 2) ||
2687         PPC::isSplatShuffleMask(PermMask.Val, 4) ||
2688         PPC::isVPKUWUMShuffleMask(PermMask.Val, true) ||
2689         PPC::isVPKUHUMShuffleMask(PermMask.Val, true) ||
2690         PPC::isVSLDOIShuffleMask(PermMask.Val, true) != -1 ||
2691         PPC::isVMRGLShuffleMask(PermMask.Val, 1, true) ||
2692         PPC::isVMRGLShuffleMask(PermMask.Val, 2, true) ||
2693         PPC::isVMRGLShuffleMask(PermMask.Val, 4, true) ||
2694         PPC::isVMRGHShuffleMask(PermMask.Val, 1, true) ||
2695         PPC::isVMRGHShuffleMask(PermMask.Val, 2, true) ||
2696         PPC::isVMRGHShuffleMask(PermMask.Val, 4, true)) {
2697       return Op;
2698     }
2699   }
2700   
2701   // Altivec has a variety of "shuffle immediates" that take two vector inputs
2702   // and produce a fixed permutation.  If any of these match, do not lower to
2703   // VPERM.
2704   if (PPC::isVPKUWUMShuffleMask(PermMask.Val, false) ||
2705       PPC::isVPKUHUMShuffleMask(PermMask.Val, false) ||
2706       PPC::isVSLDOIShuffleMask(PermMask.Val, false) != -1 ||
2707       PPC::isVMRGLShuffleMask(PermMask.Val, 1, false) ||
2708       PPC::isVMRGLShuffleMask(PermMask.Val, 2, false) ||
2709       PPC::isVMRGLShuffleMask(PermMask.Val, 4, false) ||
2710       PPC::isVMRGHShuffleMask(PermMask.Val, 1, false) ||
2711       PPC::isVMRGHShuffleMask(PermMask.Val, 2, false) ||
2712       PPC::isVMRGHShuffleMask(PermMask.Val, 4, false))
2713     return Op;
2714   
2715   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
2716   // perfect shuffle table to emit an optimal matching sequence.
2717   unsigned PFIndexes[4];
2718   bool isFourElementShuffle = true;
2719   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
2720     unsigned EltNo = 8;   // Start out undef.
2721     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
2722       if (PermMask.getOperand(i*4+j).getOpcode() == ISD::UNDEF)
2723         continue;   // Undef, ignore it.
2724       
2725       unsigned ByteSource = 
2726         cast<ConstantSDNode>(PermMask.getOperand(i*4+j))->getValue();
2727       if ((ByteSource & 3) != j) {
2728         isFourElementShuffle = false;
2729         break;
2730       }
2731       
2732       if (EltNo == 8) {
2733         EltNo = ByteSource/4;
2734       } else if (EltNo != ByteSource/4) {
2735         isFourElementShuffle = false;
2736         break;
2737       }
2738     }
2739     PFIndexes[i] = EltNo;
2740   }
2741     
2742   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 
2743   // perfect shuffle vector to determine if it is cost effective to do this as
2744   // discrete instructions, or whether we should use a vperm.
2745   if (isFourElementShuffle) {
2746     // Compute the index in the perfect shuffle table.
2747     unsigned PFTableIndex = 
2748       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2749     
2750     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2751     unsigned Cost  = (PFEntry >> 30);
2752     
2753     // Determining when to avoid vperm is tricky.  Many things affect the cost
2754     // of vperm, particularly how many times the perm mask needs to be computed.
2755     // For example, if the perm mask can be hoisted out of a loop or is already
2756     // used (perhaps because there are multiple permutes with the same shuffle
2757     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
2758     // the loop requires an extra register.
2759     //
2760     // As a compromise, we only emit discrete instructions if the shuffle can be
2761     // generated in 3 or fewer operations.  When we have loop information 
2762     // available, if this block is within a loop, we should avoid using vperm
2763     // for 3-operation perms and use a constant pool load instead.
2764     if (Cost < 3) 
2765       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG);
2766   }
2767   
2768   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
2769   // vector that will get spilled to the constant pool.
2770   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
2771   
2772   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
2773   // that it is in input element units, not in bytes.  Convert now.
2774   MVT::ValueType EltVT = MVT::getVectorElementType(V1.getValueType());
2775   unsigned BytesPerElement = MVT::getSizeInBits(EltVT)/8;
2776   
2777   SmallVector<SDOperand, 16> ResultMask;
2778   for (unsigned i = 0, e = PermMask.getNumOperands(); i != e; ++i) {
2779     unsigned SrcElt;
2780     if (PermMask.getOperand(i).getOpcode() == ISD::UNDEF)
2781       SrcElt = 0;
2782     else 
2783       SrcElt = cast<ConstantSDNode>(PermMask.getOperand(i))->getValue();
2784     
2785     for (unsigned j = 0; j != BytesPerElement; ++j)
2786       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
2787                                            MVT::i8));
2788   }
2789   
2790   SDOperand VPermMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8,
2791                                     &ResultMask[0], ResultMask.size());
2792   return DAG.getNode(PPCISD::VPERM, V1.getValueType(), V1, V2, VPermMask);
2793 }
2794
2795 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
2796 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
2797 /// information about the intrinsic.
2798 static bool getAltivecCompareInfo(SDOperand Intrin, int &CompareOpc,
2799                                   bool &isDot) {
2800   unsigned IntrinsicID = cast<ConstantSDNode>(Intrin.getOperand(0))->getValue();
2801   CompareOpc = -1;
2802   isDot = false;
2803   switch (IntrinsicID) {
2804   default: return false;
2805     // Comparison predicates.
2806   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
2807   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
2808   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
2809   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
2810   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
2811   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
2812   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
2813   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
2814   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
2815   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
2816   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
2817   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
2818   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
2819     
2820     // Normal Comparisons.
2821   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
2822   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
2823   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
2824   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
2825   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
2826   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
2827   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
2828   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
2829   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
2830   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
2831   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
2832   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
2833   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
2834   }
2835   return true;
2836 }
2837
2838 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
2839 /// lower, do it, otherwise return null.
2840 static SDOperand LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
2841   // If this is a lowered altivec predicate compare, CompareOpc is set to the
2842   // opcode number of the comparison.
2843   int CompareOpc;
2844   bool isDot;
2845   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
2846     return SDOperand();    // Don't custom lower most intrinsics.
2847   
2848   // If this is a non-dot comparison, make the VCMP node and we are done.
2849   if (!isDot) {
2850     SDOperand Tmp = DAG.getNode(PPCISD::VCMP, Op.getOperand(2).getValueType(),
2851                                 Op.getOperand(1), Op.getOperand(2),
2852                                 DAG.getConstant(CompareOpc, MVT::i32));
2853     return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Tmp);
2854   }
2855   
2856   // Create the PPCISD altivec 'dot' comparison node.
2857   SDOperand Ops[] = {
2858     Op.getOperand(2),  // LHS
2859     Op.getOperand(3),  // RHS
2860     DAG.getConstant(CompareOpc, MVT::i32)
2861   };
2862   std::vector<MVT::ValueType> VTs;
2863   VTs.push_back(Op.getOperand(2).getValueType());
2864   VTs.push_back(MVT::Flag);
2865   SDOperand CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops, 3);
2866   
2867   // Now that we have the comparison, emit a copy from the CR to a GPR.
2868   // This is flagged to the above dot comparison.
2869   SDOperand Flags = DAG.getNode(PPCISD::MFCR, MVT::i32,
2870                                 DAG.getRegister(PPC::CR6, MVT::i32),
2871                                 CompNode.getValue(1)); 
2872   
2873   // Unpack the result based on how the target uses it.
2874   unsigned BitNo;   // Bit # of CR6.
2875   bool InvertBit;   // Invert result?
2876   switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
2877   default:  // Can't happen, don't crash on invalid number though.
2878   case 0:   // Return the value of the EQ bit of CR6.
2879     BitNo = 0; InvertBit = false;
2880     break;
2881   case 1:   // Return the inverted value of the EQ bit of CR6.
2882     BitNo = 0; InvertBit = true;
2883     break;
2884   case 2:   // Return the value of the LT bit of CR6.
2885     BitNo = 2; InvertBit = false;
2886     break;
2887   case 3:   // Return the inverted value of the LT bit of CR6.
2888     BitNo = 2; InvertBit = true;
2889     break;
2890   }
2891   
2892   // Shift the bit into the low position.
2893   Flags = DAG.getNode(ISD::SRL, MVT::i32, Flags,
2894                       DAG.getConstant(8-(3-BitNo), MVT::i32));
2895   // Isolate the bit.
2896   Flags = DAG.getNode(ISD::AND, MVT::i32, Flags,
2897                       DAG.getConstant(1, MVT::i32));
2898   
2899   // If we are supposed to, toggle the bit.
2900   if (InvertBit)
2901     Flags = DAG.getNode(ISD::XOR, MVT::i32, Flags,
2902                         DAG.getConstant(1, MVT::i32));
2903   return Flags;
2904 }
2905
2906 static SDOperand LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2907   // Create a stack slot that is 16-byte aligned.
2908   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2909   int FrameIdx = FrameInfo->CreateStackObject(16, 16);
2910   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2911   SDOperand FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
2912   
2913   // Store the input value into Value#0 of the stack slot.
2914   SDOperand Store = DAG.getStore(DAG.getEntryNode(),
2915                                  Op.getOperand(0), FIdx, NULL, 0);
2916   // Load it out.
2917   return DAG.getLoad(Op.getValueType(), Store, FIdx, NULL, 0);
2918 }
2919
2920 static SDOperand LowerMUL(SDOperand Op, SelectionDAG &DAG) {
2921   if (Op.getValueType() == MVT::v4i32) {
2922     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2923     
2924     SDOperand Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG);
2925     SDOperand Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG); // +16 as shift amt.
2926     
2927     SDOperand RHSSwap =   // = vrlw RHS, 16
2928       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG);
2929     
2930     // Shrinkify inputs to v8i16.
2931     LHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, LHS);
2932     RHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, RHS);
2933     RHSSwap = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, RHSSwap);
2934     
2935     // Low parts multiplied together, generating 32-bit results (we ignore the
2936     // top parts).
2937     SDOperand LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
2938                                         LHS, RHS, DAG, MVT::v4i32);
2939     
2940     SDOperand HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
2941                                         LHS, RHSSwap, Zero, DAG, MVT::v4i32);
2942     // Shift the high parts up 16 bits.
2943     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, Neg16, DAG);
2944     return DAG.getNode(ISD::ADD, MVT::v4i32, LoProd, HiProd);
2945   } else if (Op.getValueType() == MVT::v8i16) {
2946     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2947     
2948     SDOperand Zero = BuildSplatI(0, 1, MVT::v8i16, DAG);
2949
2950     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
2951                             LHS, RHS, Zero, DAG);
2952   } else if (Op.getValueType() == MVT::v16i8) {
2953     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2954     
2955     // Multiply the even 8-bit parts, producing 16-bit sums.
2956     SDOperand EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
2957                                            LHS, RHS, DAG, MVT::v8i16);
2958     EvenParts = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, EvenParts);
2959     
2960     // Multiply the odd 8-bit parts, producing 16-bit sums.
2961     SDOperand OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
2962                                           LHS, RHS, DAG, MVT::v8i16);
2963     OddParts = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, OddParts);
2964     
2965     // Merge the results together.
2966     SDOperand Ops[16];
2967     for (unsigned i = 0; i != 8; ++i) {
2968       Ops[i*2  ] = DAG.getConstant(2*i+1, MVT::i8);
2969       Ops[i*2+1] = DAG.getConstant(2*i+1+16, MVT::i8);
2970     }
2971     return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v16i8, EvenParts, OddParts,
2972                        DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops, 16));
2973   } else {
2974     assert(0 && "Unknown mul to lower!");
2975     abort();
2976   }
2977 }
2978
2979 /// LowerOperation - Provide custom lowering hooks for some operations.
2980 ///
2981 SDOperand PPCTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2982   switch (Op.getOpcode()) {
2983   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
2984   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
2985   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
2986   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2987   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
2988   case ISD::SETCC:              return LowerSETCC(Op, DAG);
2989   case ISD::VASTART:            
2990     return LowerVASTART(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
2991                         VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
2992   
2993   case ISD::VAARG:            
2994     return LowerVAARG(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
2995                       VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
2996
2997   case ISD::FORMAL_ARGUMENTS:
2998     return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex, 
2999                                  VarArgsStackOffset, VarArgsNumGPR,
3000                                  VarArgsNumFPR, PPCSubTarget);
3001
3002   case ISD::CALL:               return LowerCALL(Op, DAG, PPCSubTarget);
3003   case ISD::RET:                return LowerRET(Op, DAG, getTargetMachine());
3004   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
3005   case ISD::DYNAMIC_STACKALLOC:
3006     return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
3007     
3008   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
3009   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
3010   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
3011   case ISD::FP_ROUND_INREG:     return LowerFP_ROUND_INREG(Op, DAG);
3012
3013   // Lower 64-bit shifts.
3014   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
3015   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
3016   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
3017
3018   // Vector-related lowering.
3019   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
3020   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
3021   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3022   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
3023   case ISD::MUL:                return LowerMUL(Op, DAG);
3024   
3025   // Frame & Return address.  Currently unimplemented
3026   case ISD::RETURNADDR:         break;
3027   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
3028   }
3029   return SDOperand();
3030 }
3031
3032 //===----------------------------------------------------------------------===//
3033 //  Other Lowering Code
3034 //===----------------------------------------------------------------------===//
3035
3036 MachineBasicBlock *
3037 PPCTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3038                                            MachineBasicBlock *BB) {
3039   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3040   assert((MI->getOpcode() == PPC::SELECT_CC_I4 ||
3041           MI->getOpcode() == PPC::SELECT_CC_I8 ||
3042           MI->getOpcode() == PPC::SELECT_CC_F4 ||
3043           MI->getOpcode() == PPC::SELECT_CC_F8 ||
3044           MI->getOpcode() == PPC::SELECT_CC_VRRC) &&
3045          "Unexpected instr type to insert");
3046   
3047   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
3048   // control-flow pattern.  The incoming instruction knows the destination vreg
3049   // to set, the condition code register to branch on, the true/false values to
3050   // select between, and a branch opcode to use.
3051   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3052   ilist<MachineBasicBlock>::iterator It = BB;
3053   ++It;
3054   
3055   //  thisMBB:
3056   //  ...
3057   //   TrueVal = ...
3058   //   cmpTY ccX, r1, r2
3059   //   bCC copy1MBB
3060   //   fallthrough --> copy0MBB
3061   MachineBasicBlock *thisMBB = BB;
3062   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
3063   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
3064   unsigned SelectPred = MI->getOperand(4).getImm();
3065   BuildMI(BB, TII->get(PPC::BCC))
3066     .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
3067   MachineFunction *F = BB->getParent();
3068   F->getBasicBlockList().insert(It, copy0MBB);
3069   F->getBasicBlockList().insert(It, sinkMBB);
3070   // Update machine-CFG edges by first adding all successors of the current
3071   // block to the new block which will contain the Phi node for the select.
3072   for(MachineBasicBlock::succ_iterator i = BB->succ_begin(), 
3073       e = BB->succ_end(); i != e; ++i)
3074     sinkMBB->addSuccessor(*i);
3075   // Next, remove all successors of the current block, and add the true
3076   // and fallthrough blocks as its successors.
3077   while(!BB->succ_empty())
3078     BB->removeSuccessor(BB->succ_begin());
3079   BB->addSuccessor(copy0MBB);
3080   BB->addSuccessor(sinkMBB);
3081   
3082   //  copy0MBB:
3083   //   %FalseValue = ...
3084   //   # fallthrough to sinkMBB
3085   BB = copy0MBB;
3086   
3087   // Update machine-CFG edges
3088   BB->addSuccessor(sinkMBB);
3089   
3090   //  sinkMBB:
3091   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
3092   //  ...
3093   BB = sinkMBB;
3094   BuildMI(BB, TII->get(PPC::PHI), MI->getOperand(0).getReg())
3095     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
3096     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
3097
3098   delete MI;   // The pseudo instruction is gone now.
3099   return BB;
3100 }
3101
3102 //===----------------------------------------------------------------------===//
3103 // Target Optimization Hooks
3104 //===----------------------------------------------------------------------===//
3105
3106 SDOperand PPCTargetLowering::PerformDAGCombine(SDNode *N, 
3107                                                DAGCombinerInfo &DCI) const {
3108   TargetMachine &TM = getTargetMachine();
3109   SelectionDAG &DAG = DCI.DAG;
3110   switch (N->getOpcode()) {
3111   default: break;
3112   case PPCISD::SHL:
3113     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
3114       if (C->getValue() == 0)   // 0 << V -> 0.
3115         return N->getOperand(0);
3116     }
3117     break;
3118   case PPCISD::SRL:
3119     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
3120       if (C->getValue() == 0)   // 0 >>u V -> 0.
3121         return N->getOperand(0);
3122     }
3123     break;
3124   case PPCISD::SRA:
3125     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
3126       if (C->getValue() == 0 ||   //  0 >>s V -> 0.
3127           C->isAllOnesValue())    // -1 >>s V -> -1.
3128         return N->getOperand(0);
3129     }
3130     break;
3131     
3132   case ISD::SINT_TO_FP:
3133     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
3134       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
3135         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
3136         // We allow the src/dst to be either f32/f64, but the intermediate
3137         // type must be i64.
3138         if (N->getOperand(0).getValueType() == MVT::i64) {
3139           SDOperand Val = N->getOperand(0).getOperand(0);
3140           if (Val.getValueType() == MVT::f32) {
3141             Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
3142             DCI.AddToWorklist(Val.Val);
3143           }
3144             
3145           Val = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Val);
3146           DCI.AddToWorklist(Val.Val);
3147           Val = DAG.getNode(PPCISD::FCFID, MVT::f64, Val);
3148           DCI.AddToWorklist(Val.Val);
3149           if (N->getValueType(0) == MVT::f32) {
3150             Val = DAG.getNode(ISD::FP_ROUND, MVT::f32, Val);
3151             DCI.AddToWorklist(Val.Val);
3152           }
3153           return Val;
3154         } else if (N->getOperand(0).getValueType() == MVT::i32) {
3155           // If the intermediate type is i32, we can avoid the load/store here
3156           // too.
3157         }
3158       }
3159     }
3160     break;
3161   case ISD::STORE:
3162     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
3163     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
3164         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
3165         N->getOperand(1).getValueType() == MVT::i32) {
3166       SDOperand Val = N->getOperand(1).getOperand(0);
3167       if (Val.getValueType() == MVT::f32) {
3168         Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
3169         DCI.AddToWorklist(Val.Val);
3170       }
3171       Val = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Val);
3172       DCI.AddToWorklist(Val.Val);
3173
3174       Val = DAG.getNode(PPCISD::STFIWX, MVT::Other, N->getOperand(0), Val,
3175                         N->getOperand(2), N->getOperand(3));
3176       DCI.AddToWorklist(Val.Val);
3177       return Val;
3178     }
3179     
3180     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
3181     if (N->getOperand(1).getOpcode() == ISD::BSWAP &&
3182         N->getOperand(1).Val->hasOneUse() &&
3183         (N->getOperand(1).getValueType() == MVT::i32 ||
3184          N->getOperand(1).getValueType() == MVT::i16)) {
3185       SDOperand BSwapOp = N->getOperand(1).getOperand(0);
3186       // Do an any-extend to 32-bits if this is a half-word input.
3187       if (BSwapOp.getValueType() == MVT::i16)
3188         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, BSwapOp);
3189
3190       return DAG.getNode(PPCISD::STBRX, MVT::Other, N->getOperand(0), BSwapOp,
3191                          N->getOperand(2), N->getOperand(3),
3192                          DAG.getValueType(N->getOperand(1).getValueType()));
3193     }
3194     break;
3195   case ISD::BSWAP:
3196     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
3197     if (ISD::isNON_EXTLoad(N->getOperand(0).Val) &&
3198         N->getOperand(0).hasOneUse() &&
3199         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
3200       SDOperand Load = N->getOperand(0);
3201       LoadSDNode *LD = cast<LoadSDNode>(Load);
3202       // Create the byte-swapping load.
3203       std::vector<MVT::ValueType> VTs;
3204       VTs.push_back(MVT::i32);
3205       VTs.push_back(MVT::Other);
3206       SDOperand SV = DAG.getSrcValue(LD->getSrcValue(), LD->getSrcValueOffset());
3207       SDOperand Ops[] = {
3208         LD->getChain(),    // Chain
3209         LD->getBasePtr(),  // Ptr
3210         SV,                // SrcValue
3211         DAG.getValueType(N->getValueType(0)) // VT
3212       };
3213       SDOperand BSLoad = DAG.getNode(PPCISD::LBRX, VTs, Ops, 4);
3214
3215       // If this is an i16 load, insert the truncate.  
3216       SDOperand ResVal = BSLoad;
3217       if (N->getValueType(0) == MVT::i16)
3218         ResVal = DAG.getNode(ISD::TRUNCATE, MVT::i16, BSLoad);
3219       
3220       // First, combine the bswap away.  This makes the value produced by the
3221       // load dead.
3222       DCI.CombineTo(N, ResVal);
3223
3224       // Next, combine the load away, we give it a bogus result value but a real
3225       // chain result.  The result value is dead because the bswap is dead.
3226       DCI.CombineTo(Load.Val, ResVal, BSLoad.getValue(1));
3227       
3228       // Return N so it doesn't get rechecked!
3229       return SDOperand(N, 0);
3230     }
3231     
3232     break;
3233   case PPCISD::VCMP: {
3234     // If a VCMPo node already exists with exactly the same operands as this
3235     // node, use its result instead of this node (VCMPo computes both a CR6 and
3236     // a normal output).
3237     //
3238     if (!N->getOperand(0).hasOneUse() &&
3239         !N->getOperand(1).hasOneUse() &&
3240         !N->getOperand(2).hasOneUse()) {
3241       
3242       // Scan all of the users of the LHS, looking for VCMPo's that match.
3243       SDNode *VCMPoNode = 0;
3244       
3245       SDNode *LHSN = N->getOperand(0).Val;
3246       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
3247            UI != E; ++UI)
3248         if ((*UI)->getOpcode() == PPCISD::VCMPo &&
3249             (*UI)->getOperand(1) == N->getOperand(1) &&
3250             (*UI)->getOperand(2) == N->getOperand(2) &&
3251             (*UI)->getOperand(0) == N->getOperand(0)) {
3252           VCMPoNode = *UI;
3253           break;
3254         }
3255       
3256       // If there is no VCMPo node, or if the flag value has a single use, don't
3257       // transform this.
3258       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
3259         break;
3260         
3261       // Look at the (necessarily single) use of the flag value.  If it has a 
3262       // chain, this transformation is more complex.  Note that multiple things
3263       // could use the value result, which we should ignore.
3264       SDNode *FlagUser = 0;
3265       for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 
3266            FlagUser == 0; ++UI) {
3267         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
3268         SDNode *User = *UI;
3269         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
3270           if (User->getOperand(i) == SDOperand(VCMPoNode, 1)) {
3271             FlagUser = User;
3272             break;
3273           }
3274         }
3275       }
3276       
3277       // If the user is a MFCR instruction, we know this is safe.  Otherwise we
3278       // give up for right now.
3279       if (FlagUser->getOpcode() == PPCISD::MFCR)
3280         return SDOperand(VCMPoNode, 0);
3281     }
3282     break;
3283   }
3284   case ISD::BR_CC: {
3285     // If this is a branch on an altivec predicate comparison, lower this so
3286     // that we don't have to do a MFCR: instead, branch directly on CR6.  This
3287     // lowering is done pre-legalize, because the legalizer lowers the predicate
3288     // compare down to code that is difficult to reassemble.
3289     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
3290     SDOperand LHS = N->getOperand(2), RHS = N->getOperand(3);
3291     int CompareOpc;
3292     bool isDot;
3293     
3294     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3295         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
3296         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
3297       assert(isDot && "Can't compare against a vector result!");
3298       
3299       // If this is a comparison against something other than 0/1, then we know
3300       // that the condition is never/always true.
3301       unsigned Val = cast<ConstantSDNode>(RHS)->getValue();
3302       if (Val != 0 && Val != 1) {
3303         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
3304           return N->getOperand(0);
3305         // Always !=, turn it into an unconditional branch.
3306         return DAG.getNode(ISD::BR, MVT::Other, 
3307                            N->getOperand(0), N->getOperand(4));
3308       }
3309     
3310       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
3311       
3312       // Create the PPCISD altivec 'dot' comparison node.
3313       std::vector<MVT::ValueType> VTs;
3314       SDOperand Ops[] = {
3315         LHS.getOperand(2),  // LHS of compare
3316         LHS.getOperand(3),  // RHS of compare
3317         DAG.getConstant(CompareOpc, MVT::i32)
3318       };
3319       VTs.push_back(LHS.getOperand(2).getValueType());
3320       VTs.push_back(MVT::Flag);
3321       SDOperand CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops, 3);
3322       
3323       // Unpack the result based on how the target uses it.
3324       PPC::Predicate CompOpc;
3325       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getValue()) {
3326       default:  // Can't happen, don't crash on invalid number though.
3327       case 0:   // Branch on the value of the EQ bit of CR6.
3328         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
3329         break;
3330       case 1:   // Branch on the inverted value of the EQ bit of CR6.
3331         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
3332         break;
3333       case 2:   // Branch on the value of the LT bit of CR6.
3334         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
3335         break;
3336       case 3:   // Branch on the inverted value of the LT bit of CR6.
3337         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
3338         break;
3339       }
3340
3341       return DAG.getNode(PPCISD::COND_BRANCH, MVT::Other, N->getOperand(0),
3342                          DAG.getConstant(CompOpc, MVT::i32),
3343                          DAG.getRegister(PPC::CR6, MVT::i32),
3344                          N->getOperand(4), CompNode.getValue(1));
3345     }
3346     break;
3347   }
3348   }
3349   
3350   return SDOperand();
3351 }
3352
3353 //===----------------------------------------------------------------------===//
3354 // Inline Assembly Support
3355 //===----------------------------------------------------------------------===//
3356
3357 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
3358                                                        uint64_t Mask,
3359                                                        uint64_t &KnownZero, 
3360                                                        uint64_t &KnownOne,
3361                                                        const SelectionDAG &DAG,
3362                                                        unsigned Depth) const {
3363   KnownZero = 0;
3364   KnownOne = 0;
3365   switch (Op.getOpcode()) {
3366   default: break;
3367   case PPCISD::LBRX: {
3368     // lhbrx is known to have the top bits cleared out.
3369     if (cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::i16)
3370       KnownZero = 0xFFFF0000;
3371     break;
3372   }
3373   case ISD::INTRINSIC_WO_CHAIN: {
3374     switch (cast<ConstantSDNode>(Op.getOperand(0))->getValue()) {
3375     default: break;
3376     case Intrinsic::ppc_altivec_vcmpbfp_p:
3377     case Intrinsic::ppc_altivec_vcmpeqfp_p:
3378     case Intrinsic::ppc_altivec_vcmpequb_p:
3379     case Intrinsic::ppc_altivec_vcmpequh_p:
3380     case Intrinsic::ppc_altivec_vcmpequw_p:
3381     case Intrinsic::ppc_altivec_vcmpgefp_p:
3382     case Intrinsic::ppc_altivec_vcmpgtfp_p:
3383     case Intrinsic::ppc_altivec_vcmpgtsb_p:
3384     case Intrinsic::ppc_altivec_vcmpgtsh_p:
3385     case Intrinsic::ppc_altivec_vcmpgtsw_p:
3386     case Intrinsic::ppc_altivec_vcmpgtub_p:
3387     case Intrinsic::ppc_altivec_vcmpgtuh_p:
3388     case Intrinsic::ppc_altivec_vcmpgtuw_p:
3389       KnownZero = ~1U;  // All bits but the low one are known to be zero.
3390       break;
3391     }        
3392   }
3393   }
3394 }
3395
3396
3397 /// getConstraintType - Given a constraint, return the type of
3398 /// constraint it is for this target.
3399 PPCTargetLowering::ConstraintType 
3400 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
3401   if (Constraint.size() == 1) {
3402     switch (Constraint[0]) {
3403     default: break;
3404     case 'b':
3405     case 'r':
3406     case 'f':
3407     case 'v':
3408     case 'y':
3409       return C_RegisterClass;
3410     }
3411   }
3412   return TargetLowering::getConstraintType(Constraint);
3413 }
3414
3415 std::pair<unsigned, const TargetRegisterClass*> 
3416 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3417                                                 MVT::ValueType VT) const {
3418   if (Constraint.size() == 1) {
3419     // GCC RS6000 Constraint Letters
3420     switch (Constraint[0]) {
3421     case 'b':   // R1-R31
3422     case 'r':   // R0-R31
3423       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
3424         return std::make_pair(0U, PPC::G8RCRegisterClass);
3425       return std::make_pair(0U, PPC::GPRCRegisterClass);
3426     case 'f':
3427       if (VT == MVT::f32)
3428         return std::make_pair(0U, PPC::F4RCRegisterClass);
3429       else if (VT == MVT::f64)
3430         return std::make_pair(0U, PPC::F8RCRegisterClass);
3431       break;
3432     case 'v': 
3433       return std::make_pair(0U, PPC::VRRCRegisterClass);
3434     case 'y':   // crrc
3435       return std::make_pair(0U, PPC::CRRCRegisterClass);
3436     }
3437   }
3438   
3439   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3440 }
3441
3442
3443 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3444 /// vector.  If it is invalid, don't add anything to Ops.
3445 void PPCTargetLowering::LowerAsmOperandForConstraint(SDOperand Op, char Letter,
3446                                                      std::vector<SDOperand>&Ops,
3447                                                      SelectionDAG &DAG) {
3448   SDOperand Result(0,0);
3449   switch (Letter) {
3450   default: break;
3451   case 'I':
3452   case 'J':
3453   case 'K':
3454   case 'L':
3455   case 'M':
3456   case 'N':
3457   case 'O':
3458   case 'P': {
3459     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
3460     if (!CST) return; // Must be an immediate to match.
3461     unsigned Value = CST->getValue();
3462     switch (Letter) {
3463     default: assert(0 && "Unknown constraint letter!");
3464     case 'I':  // "I" is a signed 16-bit constant.
3465       if ((short)Value == (int)Value)
3466         Result = DAG.getTargetConstant(Value, Op.getValueType());
3467       break;
3468     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
3469     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
3470       if ((short)Value == 0)
3471         Result = DAG.getTargetConstant(Value, Op.getValueType());
3472       break;
3473     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
3474       if ((Value >> 16) == 0)
3475         Result = DAG.getTargetConstant(Value, Op.getValueType());
3476       break;
3477     case 'M':  // "M" is a constant that is greater than 31.
3478       if (Value > 31)
3479         Result = DAG.getTargetConstant(Value, Op.getValueType());
3480       break;
3481     case 'N':  // "N" is a positive constant that is an exact power of two.
3482       if ((int)Value > 0 && isPowerOf2_32(Value))
3483         Result = DAG.getTargetConstant(Value, Op.getValueType());
3484       break;
3485     case 'O':  // "O" is the constant zero. 
3486       if (Value == 0)
3487         Result = DAG.getTargetConstant(Value, Op.getValueType());
3488       break;
3489     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
3490       if ((short)-Value == (int)-Value)
3491         Result = DAG.getTargetConstant(Value, Op.getValueType());
3492       break;
3493     }
3494     break;
3495   }
3496   }
3497   
3498   if (Result.Val) {
3499     Ops.push_back(Result);
3500     return;
3501   }
3502   
3503   // Handle standard constraint letters.
3504   TargetLowering::LowerAsmOperandForConstraint(Op, Letter, Ops, DAG);
3505 }
3506
3507 // isLegalAddressingMode - Return true if the addressing mode represented
3508 // by AM is legal for this target, for a load/store of the specified type.
3509 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
3510                                               const Type *Ty) const {
3511   // FIXME: PPC does not allow r+i addressing modes for vectors!
3512   
3513   // PPC allows a sign-extended 16-bit immediate field.
3514   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
3515     return false;
3516   
3517   // No global is ever allowed as a base.
3518   if (AM.BaseGV)
3519     return false;
3520   
3521   // PPC only support r+r, 
3522   switch (AM.Scale) {
3523   case 0:  // "r+i" or just "i", depending on HasBaseReg.
3524     break;
3525   case 1:
3526     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
3527       return false;
3528     // Otherwise we have r+r or r+i.
3529     break;
3530   case 2:
3531     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
3532       return false;
3533     // Allow 2*r as r+r.
3534     break;
3535   default:
3536     // No other scales are supported.
3537     return false;
3538   }
3539   
3540   return true;
3541 }
3542
3543 /// isLegalAddressImmediate - Return true if the integer value can be used
3544 /// as the offset of the target addressing mode for load / store of the
3545 /// given type.
3546 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
3547   // PPC allows a sign-extended 16-bit immediate field.
3548   return (V > -(1 << 16) && V < (1 << 16)-1);
3549 }
3550
3551 bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) const {
3552   return false; 
3553 }
3554
3555 SDOperand PPCTargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG)
3556 {
3557   // Depths > 0 not supported yet! 
3558   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
3559     return SDOperand();
3560   
3561   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3562   bool isPPC64 = PtrVT == MVT::i64;
3563   
3564   MachineFunction &MF = DAG.getMachineFunction();
3565   MachineFrameInfo *MFI = MF.getFrameInfo();
3566   bool is31 = (NoFramePointerElim || MFI->hasVarSizedObjects()) 
3567                   && MFI->getStackSize();
3568
3569   if (isPPC64)
3570     return DAG.getCopyFromReg(DAG.getEntryNode(), is31 ? PPC::X31 : PPC::X1,
3571       MVT::i64);
3572   else
3573     return DAG.getCopyFromReg(DAG.getEntryNode(), is31 ? PPC::R31 : PPC::R1,
3574       MVT::i32);
3575 }