Don't #include DerivedTypes.h from TargetData.h.
[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 is distributed under the University of Illinois Open Source
6 // 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/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CallingConv.h"
29 #include "llvm/Constants.h"
30 #include "llvm/Function.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/DerivedTypes.h"
36 using namespace llvm;
37
38 static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc",
39 cl::desc("enable preincrement load/store generation on PPC (experimental)"),
40                                      cl::Hidden);
41
42 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
43   : TargetLowering(TM), PPCSubTarget(*TM.getSubtargetImpl()) {
44
45   setPow2DivIsCheap();
46
47   // Use _setjmp/_longjmp instead of setjmp/longjmp.
48   setUseUnderscoreSetJmp(true);
49   setUseUnderscoreLongJmp(true);
50
51   // Set up the register classes.
52   addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
53   addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
54   addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
55
56   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
57   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
58   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
59
60   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
61
62   // PowerPC has pre-inc load and store's.
63   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
64   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
65   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
66   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
67   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
68   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
69   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
70   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
71   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
72   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
73
74   // Shortening conversions involving ppcf128 get expanded (2 regs -> 1 reg)
75   setConvertAction(MVT::ppcf128, MVT::f64, Expand);
76   setConvertAction(MVT::ppcf128, MVT::f32, Expand);
77   // This is used in the ppcf128->int sequence.  Note it has different semantics
78   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
79   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
80
81   // PowerPC has no SREM/UREM instructions
82   setOperationAction(ISD::SREM, MVT::i32, Expand);
83   setOperationAction(ISD::UREM, MVT::i32, Expand);
84   setOperationAction(ISD::SREM, MVT::i64, Expand);
85   setOperationAction(ISD::UREM, MVT::i64, Expand);
86
87   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
88   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
89   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
90   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
91   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
92   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
93   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
94   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
95   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
96
97   // We don't support sin/cos/sqrt/fmod/pow
98   setOperationAction(ISD::FSIN , MVT::f64, Expand);
99   setOperationAction(ISD::FCOS , MVT::f64, Expand);
100   setOperationAction(ISD::FREM , MVT::f64, Expand);
101   setOperationAction(ISD::FPOW , MVT::f64, Expand);
102   setOperationAction(ISD::FSIN , MVT::f32, Expand);
103   setOperationAction(ISD::FCOS , MVT::f32, Expand);
104   setOperationAction(ISD::FREM , MVT::f32, Expand);
105   setOperationAction(ISD::FPOW , MVT::f32, Expand);
106
107   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
108
109   // If we're enabling GP optimizations, use hardware square root
110   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
111     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
112     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
113   }
114
115   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
116   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
117
118   // PowerPC does not have BSWAP, CTPOP or CTTZ
119   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
120   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
121   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
122   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
123   setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
124   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
125
126   // PowerPC does not have ROTR
127   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
128   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
129
130   // PowerPC does not have Select
131   setOperationAction(ISD::SELECT, MVT::i32, Expand);
132   setOperationAction(ISD::SELECT, MVT::i64, Expand);
133   setOperationAction(ISD::SELECT, MVT::f32, Expand);
134   setOperationAction(ISD::SELECT, MVT::f64, Expand);
135
136   // PowerPC wants to turn select_cc of FP into fsel when possible.
137   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
138   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
139
140   // PowerPC wants to optimize integer setcc a bit
141   setOperationAction(ISD::SETCC, MVT::i32, Custom);
142
143   // PowerPC does not have BRCOND which requires SetCC
144   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
145
146   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
147
148   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
149   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
150
151   // PowerPC does not have [U|S]INT_TO_FP
152   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
153   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
154
155   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
156   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
157   setOperationAction(ISD::BIT_CONVERT, MVT::i64, Expand);
158   setOperationAction(ISD::BIT_CONVERT, MVT::f64, Expand);
159
160   // We cannot sextinreg(i1).  Expand to shifts.
161   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
162
163   // Support label based line numbers.
164   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
165   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
166
167   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
168   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
169   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
170   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
171
172
173   // We want to legalize GlobalAddress and ConstantPool nodes into the
174   // appropriate instructions to materialize the address.
175   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
176   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
177   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
178   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
179   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
180   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
181   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
182   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
183
184   // RET must be custom lowered, to meet ABI requirements.
185   setOperationAction(ISD::RET               , MVT::Other, Custom);
186
187   // TRAP is legal.
188   setOperationAction(ISD::TRAP, MVT::Other, Legal);
189
190   // TRAMPOLINE is custom lowered.
191   setOperationAction(ISD::TRAMPOLINE, 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   // Comparisons that require checking two conditions.
214   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
215   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
216   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
217   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
218   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
219   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
220   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
221   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
222   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
223   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
224   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
225   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
226
227   if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
228     // They also have instructions for converting between i64 and fp.
229     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
230     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
231     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
232     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
233     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
234
235     // FIXME: disable this lowered code.  This generates 64-bit register values,
236     // and we don't model the fact that the top part is clobbered by calls.  We
237     // need to flag these together so that the value isn't live across a call.
238     //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
239
240     // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
241     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
242   } else {
243     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
244     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
245   }
246
247   if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
248     // 64-bit PowerPC implementations can support i64 types directly
249     addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
250     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
251     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
252     // 64-bit PowerPC wants to expand i128 shifts itself.
253     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
254     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
255     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
256   } else {
257     // 32-bit PowerPC wants to expand i64 shifts itself.
258     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
259     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
260     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
261   }
262
263   if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
264     // First set operation action for all vector types to expand. Then we
265     // will selectively turn on ones that can be effectively codegen'd.
266     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
267          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
268       MVT VT = (MVT::SimpleValueType)i;
269
270       // add/sub are legal for all supported vector VT's.
271       setOperationAction(ISD::ADD , VT, Legal);
272       setOperationAction(ISD::SUB , VT, Legal);
273
274       // We promote all shuffles to v16i8.
275       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
276       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
277
278       // We promote all non-typed operations to v4i32.
279       setOperationAction(ISD::AND   , VT, Promote);
280       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
281       setOperationAction(ISD::OR    , VT, Promote);
282       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
283       setOperationAction(ISD::XOR   , VT, Promote);
284       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
285       setOperationAction(ISD::LOAD  , VT, Promote);
286       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
287       setOperationAction(ISD::SELECT, VT, Promote);
288       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
289       setOperationAction(ISD::STORE, VT, Promote);
290       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
291
292       // No other operations are legal.
293       setOperationAction(ISD::MUL , VT, Expand);
294       setOperationAction(ISD::SDIV, VT, Expand);
295       setOperationAction(ISD::SREM, VT, Expand);
296       setOperationAction(ISD::UDIV, VT, Expand);
297       setOperationAction(ISD::UREM, VT, Expand);
298       setOperationAction(ISD::FDIV, VT, Expand);
299       setOperationAction(ISD::FNEG, VT, Expand);
300       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
301       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
302       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
303       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
304       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
305       setOperationAction(ISD::UDIVREM, VT, Expand);
306       setOperationAction(ISD::SDIVREM, VT, Expand);
307       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
308       setOperationAction(ISD::FPOW, VT, Expand);
309       setOperationAction(ISD::CTPOP, VT, Expand);
310       setOperationAction(ISD::CTLZ, VT, Expand);
311       setOperationAction(ISD::CTTZ, VT, Expand);
312     }
313
314     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
315     // with merges, splats, etc.
316     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
317
318     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
319     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
320     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
321     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
322     setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
323     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
324
325     addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
326     addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
327     addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
328     addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
329
330     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
331     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
332     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
333     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
334
335     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
336     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
337
338     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
339     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
340     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
341     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
342   }
343
344   setShiftAmountType(MVT::i32);
345   setBooleanContents(ZeroOrOneBooleanContent);
346
347   if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
348     setStackPointerRegisterToSaveRestore(PPC::X1);
349     setExceptionPointerRegister(PPC::X3);
350     setExceptionSelectorRegister(PPC::X4);
351   } else {
352     setStackPointerRegisterToSaveRestore(PPC::R1);
353     setExceptionPointerRegister(PPC::R3);
354     setExceptionSelectorRegister(PPC::R4);
355   }
356
357   // We have target-specific dag combine patterns for the following nodes:
358   setTargetDAGCombine(ISD::SINT_TO_FP);
359   setTargetDAGCombine(ISD::STORE);
360   setTargetDAGCombine(ISD::BR_CC);
361   setTargetDAGCombine(ISD::BSWAP);
362
363   // Darwin long double math library functions have $LDBL128 appended.
364   if (TM.getSubtarget<PPCSubtarget>().isDarwin()) {
365     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
366     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
367     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
368     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
369     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
370     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
371     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
372     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
373     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
374     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
375   }
376
377   computeRegisterProperties();
378 }
379
380 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
381 /// function arguments in the caller parameter area.
382 unsigned PPCTargetLowering::getByValTypeAlignment(const Type *Ty) const {
383   TargetMachine &TM = getTargetMachine();
384   // Darwin passes everything on 4 byte boundary.
385   if (TM.getSubtarget<PPCSubtarget>().isDarwin())
386     return 4;
387   // FIXME Elf TBD
388   return 4;
389 }
390
391 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
392   switch (Opcode) {
393   default: return 0;
394   case PPCISD::FSEL:            return "PPCISD::FSEL";
395   case PPCISD::FCFID:           return "PPCISD::FCFID";
396   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
397   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
398   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
399   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
400   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
401   case PPCISD::VPERM:           return "PPCISD::VPERM";
402   case PPCISD::Hi:              return "PPCISD::Hi";
403   case PPCISD::Lo:              return "PPCISD::Lo";
404   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
405   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
406   case PPCISD::SRL:             return "PPCISD::SRL";
407   case PPCISD::SRA:             return "PPCISD::SRA";
408   case PPCISD::SHL:             return "PPCISD::SHL";
409   case PPCISD::EXTSW_32:        return "PPCISD::EXTSW_32";
410   case PPCISD::STD_32:          return "PPCISD::STD_32";
411   case PPCISD::CALL_ELF:        return "PPCISD::CALL_ELF";
412   case PPCISD::CALL_Macho:      return "PPCISD::CALL_Macho";
413   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
414   case PPCISD::BCTRL_Macho:     return "PPCISD::BCTRL_Macho";
415   case PPCISD::BCTRL_ELF:       return "PPCISD::BCTRL_ELF";
416   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
417   case PPCISD::MFCR:            return "PPCISD::MFCR";
418   case PPCISD::VCMP:            return "PPCISD::VCMP";
419   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
420   case PPCISD::LBRX:            return "PPCISD::LBRX";
421   case PPCISD::STBRX:           return "PPCISD::STBRX";
422   case PPCISD::LARX:            return "PPCISD::LARX";
423   case PPCISD::STCX:            return "PPCISD::STCX";
424   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
425   case PPCISD::MFFS:            return "PPCISD::MFFS";
426   case PPCISD::MTFSB0:          return "PPCISD::MTFSB0";
427   case PPCISD::MTFSB1:          return "PPCISD::MTFSB1";
428   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
429   case PPCISD::MTFSF:           return "PPCISD::MTFSF";
430   case PPCISD::TAILCALL:        return "PPCISD::TAILCALL";
431   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
432   }
433 }
434
435
436 MVT PPCTargetLowering::getSetCCResultType(MVT VT) const {
437   return MVT::i32;
438 }
439
440
441 //===----------------------------------------------------------------------===//
442 // Node matching predicates, for use by the tblgen matching code.
443 //===----------------------------------------------------------------------===//
444
445 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
446 static bool isFloatingPointZero(SDValue Op) {
447   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
448     return CFP->getValueAPF().isZero();
449   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
450     // Maybe this has already been legalized into the constant pool?
451     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
452       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
453         return CFP->getValueAPF().isZero();
454   }
455   return false;
456 }
457
458 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
459 /// true if Op is undef or if it matches the specified value.
460 static bool isConstantOrUndef(int Op, int Val) {
461   return Op < 0 || Op == Val;
462 }
463
464 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
465 /// VPKUHUM instruction.
466 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
467   if (!isUnary) {
468     for (unsigned i = 0; i != 16; ++i)
469       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+1))
470         return false;
471   } else {
472     for (unsigned i = 0; i != 8; ++i)
473       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+1) ||
474           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+1))
475         return false;
476   }
477   return true;
478 }
479
480 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
481 /// VPKUWUM instruction.
482 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
483   if (!isUnary) {
484     for (unsigned i = 0; i != 16; i += 2)
485       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
486           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
487         return false;
488   } else {
489     for (unsigned i = 0; i != 8; i += 2)
490       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
491           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3) ||
492           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+2) ||
493           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+3))
494         return false;
495   }
496   return true;
497 }
498
499 /// isVMerge - Common function, used to match vmrg* shuffles.
500 ///
501 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
502                      unsigned LHSStart, unsigned RHSStart) {
503   assert(N->getValueType(0) == MVT::v16i8 &&
504          "PPC only supports shuffles by bytes!");
505   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
506          "Unsupported merge size!");
507
508   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
509     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
510       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
511                              LHSStart+j+i*UnitSize) ||
512           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
513                              RHSStart+j+i*UnitSize))
514         return false;
515     }
516   return true;
517 }
518
519 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
520 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
521 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 
522                              bool isUnary) {
523   if (!isUnary)
524     return isVMerge(N, UnitSize, 8, 24);
525   return isVMerge(N, UnitSize, 8, 8);
526 }
527
528 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
529 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
530 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 
531                              bool isUnary) {
532   if (!isUnary)
533     return isVMerge(N, UnitSize, 0, 16);
534   return isVMerge(N, UnitSize, 0, 0);
535 }
536
537
538 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
539 /// amount, otherwise return -1.
540 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
541   assert(N->getValueType(0) == MVT::v16i8 &&
542          "PPC only supports shuffles by bytes!");
543
544   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
545   
546   // Find the first non-undef value in the shuffle mask.
547   unsigned i;
548   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
549     /*search*/;
550
551   if (i == 16) return -1;  // all undef.
552
553   // Otherwise, check to see if the rest of the elements are consecutively
554   // numbered from this value.
555   unsigned ShiftAmt = SVOp->getMaskElt(i);
556   if (ShiftAmt < i) return -1;
557   ShiftAmt -= i;
558
559   if (!isUnary) {
560     // Check the rest of the elements to see if they are consecutive.
561     for (++i; i != 16; ++i)
562       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
563         return -1;
564   } else {
565     // Check the rest of the elements to see if they are consecutive.
566     for (++i; i != 16; ++i)
567       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
568         return -1;
569   }
570   return ShiftAmt;
571 }
572
573 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
574 /// specifies a splat of a single element that is suitable for input to
575 /// VSPLTB/VSPLTH/VSPLTW.
576 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
577   assert(N->getValueType(0) == MVT::v16i8 &&
578          (EltSize == 1 || EltSize == 2 || EltSize == 4));
579
580   // This is a splat operation if each element of the permute is the same, and
581   // if the value doesn't reference the second vector.
582   unsigned ElementBase = N->getMaskElt(0);
583   
584   // FIXME: Handle UNDEF elements too!
585   if (ElementBase >= 16)
586     return false;
587
588   // Check that the indices are consecutive, in the case of a multi-byte element
589   // splatted with a v16i8 mask.
590   for (unsigned i = 1; i != EltSize; ++i)
591     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
592       return false;
593
594   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
595     if (N->getMaskElt(i) < 0) continue;
596     for (unsigned j = 0; j != EltSize; ++j)
597       if (N->getMaskElt(i+j) != N->getMaskElt(j))
598         return false;
599   }
600   return true;
601 }
602
603 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
604 /// are -0.0.
605 bool PPC::isAllNegativeZeroVector(SDNode *N) {
606   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
607
608   APInt APVal, APUndef;
609   unsigned BitSize;
610   bool HasAnyUndefs;
611   
612   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32))
613     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
614       return CFP->getValueAPF().isNegZero();
615
616   return false;
617 }
618
619 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
620 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
621 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
622   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
623   assert(isSplatShuffleMask(SVOp, EltSize));
624   return SVOp->getMaskElt(0) / EltSize;
625 }
626
627 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
628 /// by using a vspltis[bhw] instruction of the specified element size, return
629 /// the constant being splatted.  The ByteSize field indicates the number of
630 /// bytes of each element [124] -> [bhw].
631 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
632   SDValue OpVal(0, 0);
633
634   // If ByteSize of the splat is bigger than the element size of the
635   // build_vector, then we have a case where we are checking for a splat where
636   // multiple elements of the buildvector are folded together into a single
637   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
638   unsigned EltSize = 16/N->getNumOperands();
639   if (EltSize < ByteSize) {
640     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
641     SDValue UniquedVals[4];
642     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
643
644     // See if all of the elements in the buildvector agree across.
645     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
646       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
647       // If the element isn't a constant, bail fully out.
648       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
649
650
651       if (UniquedVals[i&(Multiple-1)].getNode() == 0)
652         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
653       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
654         return SDValue();  // no match.
655     }
656
657     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
658     // either constant or undef values that are identical for each chunk.  See
659     // if these chunks can form into a larger vspltis*.
660
661     // Check to see if all of the leading entries are either 0 or -1.  If
662     // neither, then this won't fit into the immediate field.
663     bool LeadingZero = true;
664     bool LeadingOnes = true;
665     for (unsigned i = 0; i != Multiple-1; ++i) {
666       if (UniquedVals[i].getNode() == 0) continue;  // Must have been undefs.
667
668       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
669       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
670     }
671     // Finally, check the least significant entry.
672     if (LeadingZero) {
673       if (UniquedVals[Multiple-1].getNode() == 0)
674         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
675       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
676       if (Val < 16)
677         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
678     }
679     if (LeadingOnes) {
680       if (UniquedVals[Multiple-1].getNode() == 0)
681         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
682       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
683       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
684         return DAG.getTargetConstant(Val, MVT::i32);
685     }
686
687     return SDValue();
688   }
689
690   // Check to see if this buildvec has a single non-undef value in its elements.
691   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
692     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
693     if (OpVal.getNode() == 0)
694       OpVal = N->getOperand(i);
695     else if (OpVal != N->getOperand(i))
696       return SDValue();
697   }
698
699   if (OpVal.getNode() == 0) return SDValue();  // All UNDEF: use implicit def.
700
701   unsigned ValSizeInBytes = 0;
702   uint64_t Value = 0;
703   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
704     Value = CN->getZExtValue();
705     ValSizeInBytes = CN->getValueType(0).getSizeInBits()/8;
706   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
707     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
708     Value = FloatToBits(CN->getValueAPF().convertToFloat());
709     ValSizeInBytes = 4;
710   }
711
712   // If the splat value is larger than the element value, then we can never do
713   // this splat.  The only case that we could fit the replicated bits into our
714   // immediate field for would be zero, and we prefer to use vxor for it.
715   if (ValSizeInBytes < ByteSize) return SDValue();
716
717   // If the element value is larger than the splat value, cut it in half and
718   // check to see if the two halves are equal.  Continue doing this until we
719   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
720   while (ValSizeInBytes > ByteSize) {
721     ValSizeInBytes >>= 1;
722
723     // If the top half equals the bottom half, we're still ok.
724     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
725          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
726       return SDValue();
727   }
728
729   // Properly sign extend the value.
730   int ShAmt = (4-ByteSize)*8;
731   int MaskVal = ((int)Value << ShAmt) >> ShAmt;
732
733   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
734   if (MaskVal == 0) return SDValue();
735
736   // Finally, if this value fits in a 5 bit sext field, return it
737   if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
738     return DAG.getTargetConstant(MaskVal, MVT::i32);
739   return SDValue();
740 }
741
742 //===----------------------------------------------------------------------===//
743 //  Addressing Mode Selection
744 //===----------------------------------------------------------------------===//
745
746 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
747 /// or 64-bit immediate, and if the value can be accurately represented as a
748 /// sign extension from a 16-bit value.  If so, this returns true and the
749 /// immediate.
750 static bool isIntS16Immediate(SDNode *N, short &Imm) {
751   if (N->getOpcode() != ISD::Constant)
752     return false;
753
754   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
755   if (N->getValueType(0) == MVT::i32)
756     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
757   else
758     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
759 }
760 static bool isIntS16Immediate(SDValue Op, short &Imm) {
761   return isIntS16Immediate(Op.getNode(), Imm);
762 }
763
764
765 /// SelectAddressRegReg - Given the specified addressed, check to see if it
766 /// can be represented as an indexed [r+r] operation.  Returns false if it
767 /// can be more efficiently represented with [r+imm].
768 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
769                                             SDValue &Index,
770                                             SelectionDAG &DAG) const {
771   short imm = 0;
772   if (N.getOpcode() == ISD::ADD) {
773     if (isIntS16Immediate(N.getOperand(1), imm))
774       return false;    // r+i
775     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
776       return false;    // r+i
777
778     Base = N.getOperand(0);
779     Index = N.getOperand(1);
780     return true;
781   } else if (N.getOpcode() == ISD::OR) {
782     if (isIntS16Immediate(N.getOperand(1), imm))
783       return false;    // r+i can fold it if we can.
784
785     // If this is an or of disjoint bitfields, we can codegen this as an add
786     // (for better address arithmetic) if the LHS and RHS of the OR are provably
787     // disjoint.
788     APInt LHSKnownZero, LHSKnownOne;
789     APInt RHSKnownZero, RHSKnownOne;
790     DAG.ComputeMaskedBits(N.getOperand(0),
791                           APInt::getAllOnesValue(N.getOperand(0)
792                             .getValueSizeInBits()),
793                           LHSKnownZero, LHSKnownOne);
794
795     if (LHSKnownZero.getBoolValue()) {
796       DAG.ComputeMaskedBits(N.getOperand(1),
797                             APInt::getAllOnesValue(N.getOperand(1)
798                               .getValueSizeInBits()),
799                             RHSKnownZero, RHSKnownOne);
800       // If all of the bits are known zero on the LHS or RHS, the add won't
801       // carry.
802       if (~(LHSKnownZero | RHSKnownZero) == 0) {
803         Base = N.getOperand(0);
804         Index = N.getOperand(1);
805         return true;
806       }
807     }
808   }
809
810   return false;
811 }
812
813 /// Returns true if the address N can be represented by a base register plus
814 /// a signed 16-bit displacement [r+imm], and if it is not better
815 /// represented as reg+reg.
816 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
817                                             SDValue &Base,
818                                             SelectionDAG &DAG) const {
819   // FIXME dl should come from parent load or store, not from address
820   DebugLoc dl = N.getDebugLoc();
821   // If this can be more profitably realized as r+r, fail.
822   if (SelectAddressRegReg(N, Disp, Base, DAG))
823     return false;
824
825   if (N.getOpcode() == ISD::ADD) {
826     short imm = 0;
827     if (isIntS16Immediate(N.getOperand(1), imm)) {
828       Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
829       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
830         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
831       } else {
832         Base = N.getOperand(0);
833       }
834       return true; // [r+i]
835     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
836       // Match LOAD (ADD (X, Lo(G))).
837      assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
838              && "Cannot handle constant offsets yet!");
839       Disp = N.getOperand(1).getOperand(0);  // The global address.
840       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
841              Disp.getOpcode() == ISD::TargetConstantPool ||
842              Disp.getOpcode() == ISD::TargetJumpTable);
843       Base = N.getOperand(0);
844       return true;  // [&g+r]
845     }
846   } else if (N.getOpcode() == ISD::OR) {
847     short imm = 0;
848     if (isIntS16Immediate(N.getOperand(1), imm)) {
849       // If this is an or of disjoint bitfields, we can codegen this as an add
850       // (for better address arithmetic) if the LHS and RHS of the OR are
851       // provably disjoint.
852       APInt LHSKnownZero, LHSKnownOne;
853       DAG.ComputeMaskedBits(N.getOperand(0),
854                             APInt::getAllOnesValue(N.getOperand(0)
855                                                    .getValueSizeInBits()),
856                             LHSKnownZero, LHSKnownOne);
857
858       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
859         // If all of the bits are known zero on the LHS or RHS, the add won't
860         // carry.
861         Base = N.getOperand(0);
862         Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
863         return true;
864       }
865     }
866   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
867     // Loading from a constant address.
868
869     // If this address fits entirely in a 16-bit sext immediate field, codegen
870     // this as "d, 0"
871     short Imm;
872     if (isIntS16Immediate(CN, Imm)) {
873       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
874       Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
875       return true;
876     }
877
878     // Handle 32-bit sext immediates with LIS + addr mode.
879     if (CN->getValueType(0) == MVT::i32 ||
880         (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
881       int Addr = (int)CN->getZExtValue();
882
883       // Otherwise, break this down into an LIS + disp.
884       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
885
886       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
887       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
888       Base = SDValue(DAG.getTargetNode(Opc, dl, CN->getValueType(0), Base), 0);
889       return true;
890     }
891   }
892
893   Disp = DAG.getTargetConstant(0, getPointerTy());
894   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
895     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
896   else
897     Base = N;
898   return true;      // [r+0]
899 }
900
901 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
902 /// represented as an indexed [r+r] operation.
903 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
904                                                 SDValue &Index,
905                                                 SelectionDAG &DAG) const {
906   // Check to see if we can easily represent this as an [r+r] address.  This
907   // will fail if it thinks that the address is more profitably represented as
908   // reg+imm, e.g. where imm = 0.
909   if (SelectAddressRegReg(N, Base, Index, DAG))
910     return true;
911
912   // If the operand is an addition, always emit this as [r+r], since this is
913   // better (for code size, and execution, as the memop does the add for free)
914   // than emitting an explicit add.
915   if (N.getOpcode() == ISD::ADD) {
916     Base = N.getOperand(0);
917     Index = N.getOperand(1);
918     return true;
919   }
920
921   // Otherwise, do it the hard way, using R0 as the base register.
922   Base = DAG.getRegister(PPC::R0, N.getValueType());
923   Index = N;
924   return true;
925 }
926
927 /// SelectAddressRegImmShift - Returns true if the address N can be
928 /// represented by a base register plus a signed 14-bit displacement
929 /// [r+imm*4].  Suitable for use by STD and friends.
930 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
931                                                  SDValue &Base,
932                                                  SelectionDAG &DAG) const {
933   // FIXME dl should come from the parent load or store, not the address
934   DebugLoc dl = N.getDebugLoc();
935   // If this can be more profitably realized as r+r, fail.
936   if (SelectAddressRegReg(N, Disp, Base, DAG))
937     return false;
938
939   if (N.getOpcode() == ISD::ADD) {
940     short imm = 0;
941     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
942       Disp =  DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
943       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
944         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
945       } else {
946         Base = N.getOperand(0);
947       }
948       return true; // [r+i]
949     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
950       // Match LOAD (ADD (X, Lo(G))).
951      assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
952              && "Cannot handle constant offsets yet!");
953       Disp = N.getOperand(1).getOperand(0);  // The global address.
954       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
955              Disp.getOpcode() == ISD::TargetConstantPool ||
956              Disp.getOpcode() == ISD::TargetJumpTable);
957       Base = N.getOperand(0);
958       return true;  // [&g+r]
959     }
960   } else if (N.getOpcode() == ISD::OR) {
961     short imm = 0;
962     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
963       // If this is an or of disjoint bitfields, we can codegen this as an add
964       // (for better address arithmetic) if the LHS and RHS of the OR are
965       // provably disjoint.
966       APInt LHSKnownZero, LHSKnownOne;
967       DAG.ComputeMaskedBits(N.getOperand(0),
968                             APInt::getAllOnesValue(N.getOperand(0)
969                                                    .getValueSizeInBits()),
970                             LHSKnownZero, LHSKnownOne);
971       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
972         // If all of the bits are known zero on the LHS or RHS, the add won't
973         // carry.
974         Base = N.getOperand(0);
975         Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
976         return true;
977       }
978     }
979   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
980     // Loading from a constant address.  Verify low two bits are clear.
981     if ((CN->getZExtValue() & 3) == 0) {
982       // If this address fits entirely in a 14-bit sext immediate field, codegen
983       // this as "d, 0"
984       short Imm;
985       if (isIntS16Immediate(CN, Imm)) {
986         Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
987         Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
988         return true;
989       }
990
991       // Fold the low-part of 32-bit absolute addresses into addr mode.
992       if (CN->getValueType(0) == MVT::i32 ||
993           (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
994         int Addr = (int)CN->getZExtValue();
995
996         // Otherwise, break this down into an LIS + disp.
997         Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
998         Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
999         unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1000         Base = SDValue(DAG.getTargetNode(Opc, dl, CN->getValueType(0), Base),0);
1001         return true;
1002       }
1003     }
1004   }
1005
1006   Disp = DAG.getTargetConstant(0, getPointerTy());
1007   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1008     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1009   else
1010     Base = N;
1011   return true;      // [r+0]
1012 }
1013
1014
1015 /// getPreIndexedAddressParts - returns true by value, base pointer and
1016 /// offset pointer and addressing mode by reference if the node's address
1017 /// can be legally represented as pre-indexed load / store address.
1018 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1019                                                   SDValue &Offset,
1020                                                   ISD::MemIndexedMode &AM,
1021                                                   SelectionDAG &DAG) const {
1022   // Disabled by default for now.
1023   if (!EnablePPCPreinc) return false;
1024
1025   SDValue Ptr;
1026   MVT VT;
1027   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1028     Ptr = LD->getBasePtr();
1029     VT = LD->getMemoryVT();
1030
1031   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1032     ST = ST;
1033     Ptr = ST->getBasePtr();
1034     VT  = ST->getMemoryVT();
1035   } else
1036     return false;
1037
1038   // PowerPC doesn't have preinc load/store instructions for vectors.
1039   if (VT.isVector())
1040     return false;
1041
1042   // TODO: Check reg+reg first.
1043
1044   // LDU/STU use reg+imm*4, others use reg+imm.
1045   if (VT != MVT::i64) {
1046     // reg + imm
1047     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1048       return false;
1049   } else {
1050     // reg + imm * 4.
1051     if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1052       return false;
1053   }
1054
1055   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1056     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1057     // sext i32 to i64 when addr mode is r+i.
1058     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1059         LD->getExtensionType() == ISD::SEXTLOAD &&
1060         isa<ConstantSDNode>(Offset))
1061       return false;
1062   }
1063
1064   AM = ISD::PRE_INC;
1065   return true;
1066 }
1067
1068 //===----------------------------------------------------------------------===//
1069 //  LowerOperation implementation
1070 //===----------------------------------------------------------------------===//
1071
1072 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1073                                              SelectionDAG &DAG) {
1074   MVT PtrVT = Op.getValueType();
1075   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1076   Constant *C = CP->getConstVal();
1077   SDValue CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
1078   SDValue Zero = DAG.getConstant(0, PtrVT);
1079   // FIXME there isn't really any debug info here
1080   DebugLoc dl = Op.getDebugLoc();
1081
1082   const TargetMachine &TM = DAG.getTarget();
1083
1084   SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, CPI, Zero);
1085   SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, CPI, Zero);
1086
1087   // If this is a non-darwin platform, we don't support non-static relo models
1088   // yet.
1089   if (TM.getRelocationModel() == Reloc::Static ||
1090       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1091     // Generate non-pic code that has direct accesses to the constant pool.
1092     // The address of the global is just (hi(&g)+lo(&g)).
1093     return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1094   }
1095
1096   if (TM.getRelocationModel() == Reloc::PIC_) {
1097     // With PIC, the first instruction is actually "GR+hi(&G)".
1098     Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1099                      DAG.getNode(PPCISD::GlobalBaseReg,
1100                                  DebugLoc::getUnknownLoc(), PtrVT), Hi);
1101   }
1102
1103   Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1104   return Lo;
1105 }
1106
1107 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
1108   MVT PtrVT = Op.getValueType();
1109   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1110   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1111   SDValue Zero = DAG.getConstant(0, PtrVT);
1112   // FIXME there isn't really any debug loc here
1113   DebugLoc dl = Op.getDebugLoc();
1114
1115   const TargetMachine &TM = DAG.getTarget();
1116
1117   SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, JTI, Zero);
1118   SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, JTI, Zero);
1119
1120   // If this is a non-darwin platform, we don't support non-static relo models
1121   // yet.
1122   if (TM.getRelocationModel() == Reloc::Static ||
1123       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1124     // Generate non-pic code that has direct accesses to the constant pool.
1125     // The address of the global is just (hi(&g)+lo(&g)).
1126     return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1127   }
1128
1129   if (TM.getRelocationModel() == Reloc::PIC_) {
1130     // With PIC, the first instruction is actually "GR+hi(&G)".
1131     Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1132                      DAG.getNode(PPCISD::GlobalBaseReg,
1133                                  DebugLoc::getUnknownLoc(), PtrVT), Hi);
1134   }
1135
1136   Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1137   return Lo;
1138 }
1139
1140 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1141                                                    SelectionDAG &DAG) {
1142   assert(0 && "TLS not implemented for PPC.");
1143   return SDValue(); // Not reached
1144 }
1145
1146 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1147                                               SelectionDAG &DAG) {
1148   MVT PtrVT = Op.getValueType();
1149   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1150   GlobalValue *GV = GSDN->getGlobal();
1151   SDValue GA = DAG.getTargetGlobalAddress(GV, PtrVT, GSDN->getOffset());
1152   SDValue Zero = DAG.getConstant(0, PtrVT);
1153   // FIXME there isn't really any debug info here
1154   DebugLoc dl = GSDN->getDebugLoc();
1155
1156   const TargetMachine &TM = DAG.getTarget();
1157
1158   SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, GA, Zero);
1159   SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, GA, Zero);
1160
1161   // If this is a non-darwin platform, we don't support non-static relo models
1162   // yet.
1163   if (TM.getRelocationModel() == Reloc::Static ||
1164       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1165     // Generate non-pic code that has direct accesses to globals.
1166     // The address of the global is just (hi(&g)+lo(&g)).
1167     return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1168   }
1169
1170   if (TM.getRelocationModel() == Reloc::PIC_) {
1171     // With PIC, the first instruction is actually "GR+hi(&G)".
1172     Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1173                      DAG.getNode(PPCISD::GlobalBaseReg,
1174                                  DebugLoc::getUnknownLoc(), PtrVT), Hi);
1175   }
1176
1177   Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1178
1179   if (!TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV))
1180     return Lo;
1181
1182   // If the global is weak or external, we have to go through the lazy
1183   // resolution stub.
1184   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Lo, NULL, 0);
1185 }
1186
1187 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
1188   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1189   DebugLoc dl = Op.getDebugLoc();
1190
1191   // If we're comparing for equality to zero, expose the fact that this is
1192   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1193   // fold the new nodes.
1194   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1195     if (C->isNullValue() && CC == ISD::SETEQ) {
1196       MVT VT = Op.getOperand(0).getValueType();
1197       SDValue Zext = Op.getOperand(0);
1198       if (VT.bitsLT(MVT::i32)) {
1199         VT = MVT::i32;
1200         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1201       }
1202       unsigned Log2b = Log2_32(VT.getSizeInBits());
1203       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1204       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1205                                 DAG.getConstant(Log2b, MVT::i32));
1206       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1207     }
1208     // Leave comparisons against 0 and -1 alone for now, since they're usually
1209     // optimized.  FIXME: revisit this when we can custom lower all setcc
1210     // optimizations.
1211     if (C->isAllOnesValue() || C->isNullValue())
1212       return SDValue();
1213   }
1214
1215   // If we have an integer seteq/setne, turn it into a compare against zero
1216   // by xor'ing the rhs with the lhs, which is faster than setting a
1217   // condition register, reading it back out, and masking the correct bit.  The
1218   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1219   // the result to other bit-twiddling opportunities.
1220   MVT LHSVT = Op.getOperand(0).getValueType();
1221   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1222     MVT VT = Op.getValueType();
1223     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1224                                 Op.getOperand(1));
1225     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1226   }
1227   return SDValue();
1228 }
1229
1230 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1231                               int VarArgsFrameIndex,
1232                               int VarArgsStackOffset,
1233                               unsigned VarArgsNumGPR,
1234                               unsigned VarArgsNumFPR,
1235                               const PPCSubtarget &Subtarget) {
1236
1237   assert(0 && "VAARG in ELF32 ABI not implemented yet!");
1238   return SDValue(); // Not reached
1239 }
1240
1241 SDValue PPCTargetLowering::LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
1242   SDValue Chain = Op.getOperand(0);
1243   SDValue Trmp = Op.getOperand(1); // trampoline
1244   SDValue FPtr = Op.getOperand(2); // nested function
1245   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1246   DebugLoc dl = Op.getDebugLoc();
1247
1248   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1249   bool isPPC64 = (PtrVT == MVT::i64);
1250   const Type *IntPtrTy =
1251     DAG.getTargetLoweringInfo().getTargetData()->getIntPtrType();
1252
1253   TargetLowering::ArgListTy Args;
1254   TargetLowering::ArgListEntry Entry;
1255
1256   Entry.Ty = IntPtrTy;
1257   Entry.Node = Trmp; Args.push_back(Entry);
1258
1259   // TrampSize == (isPPC64 ? 48 : 40);
1260   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1261                                isPPC64 ? MVT::i64 : MVT::i32);
1262   Args.push_back(Entry);
1263
1264   Entry.Node = FPtr; Args.push_back(Entry);
1265   Entry.Node = Nest; Args.push_back(Entry);
1266
1267   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1268   std::pair<SDValue, SDValue> CallResult =
1269     LowerCallTo(Chain, Op.getValueType().getTypeForMVT(), false, false,
1270                 false, false, CallingConv::C, false,
1271                 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1272                 Args, DAG, dl);
1273
1274   SDValue Ops[] =
1275     { CallResult.first, CallResult.second };
1276
1277   return DAG.getMergeValues(Ops, 2, dl);
1278 }
1279
1280 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1281                                         int VarArgsFrameIndex,
1282                                         int VarArgsStackOffset,
1283                                         unsigned VarArgsNumGPR,
1284                                         unsigned VarArgsNumFPR,
1285                                         const PPCSubtarget &Subtarget) {
1286   DebugLoc dl = Op.getDebugLoc();
1287
1288   if (Subtarget.isMachoABI()) {
1289     // vastart just stores the address of the VarArgsFrameIndex slot into the
1290     // memory location argument.
1291     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1292     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1293     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1294     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1295   }
1296
1297   // For ELF 32 ABI we follow the layout of the va_list struct.
1298   // We suppose the given va_list is already allocated.
1299   //
1300   // typedef struct {
1301   //  char gpr;     /* index into the array of 8 GPRs
1302   //                 * stored in the register save area
1303   //                 * gpr=0 corresponds to r3,
1304   //                 * gpr=1 to r4, etc.
1305   //                 */
1306   //  char fpr;     /* index into the array of 8 FPRs
1307   //                 * stored in the register save area
1308   //                 * fpr=0 corresponds to f1,
1309   //                 * fpr=1 to f2, etc.
1310   //                 */
1311   //  char *overflow_arg_area;
1312   //                /* location on stack that holds
1313   //                 * the next overflow argument
1314   //                 */
1315   //  char *reg_save_area;
1316   //               /* where r3:r10 and f1:f8 (if saved)
1317   //                * are stored
1318   //                */
1319   // } va_list[1];
1320
1321
1322   SDValue ArgGPR = DAG.getConstant(VarArgsNumGPR, MVT::i8);
1323   SDValue ArgFPR = DAG.getConstant(VarArgsNumFPR, MVT::i8);
1324
1325
1326   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1327
1328   SDValue StackOffsetFI = DAG.getFrameIndex(VarArgsStackOffset, PtrVT);
1329   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1330
1331   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1332   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1333
1334   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1335   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1336
1337   uint64_t FPROffset = 1;
1338   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1339
1340   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1341
1342   // Store first byte : number of int regs
1343   SDValue firstStore = DAG.getStore(Op.getOperand(0), dl, ArgGPR,
1344                                       Op.getOperand(1), SV, 0);
1345   uint64_t nextOffset = FPROffset;
1346   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1347                                   ConstFPROffset);
1348
1349   // Store second byte : number of float regs
1350   SDValue secondStore =
1351     DAG.getStore(firstStore, dl, ArgFPR, nextPtr, SV, nextOffset);
1352   nextOffset += StackOffset;
1353   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1354
1355   // Store second word : arguments given on stack
1356   SDValue thirdStore =
1357     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, SV, nextOffset);
1358   nextOffset += FrameOffset;
1359   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1360
1361   // Store third word : arguments given in registers
1362   return DAG.getStore(thirdStore, dl, FR, nextPtr, SV, nextOffset);
1363
1364 }
1365
1366 #include "PPCGenCallingConv.inc"
1367
1368 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1369 /// depending on which subtarget is selected.
1370 static const unsigned *GetFPR(const PPCSubtarget &Subtarget) {
1371   if (Subtarget.isMachoABI()) {
1372     static const unsigned FPR[] = {
1373       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1374       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1375     };
1376     return FPR;
1377   }
1378
1379
1380   static const unsigned FPR[] = {
1381     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1382     PPC::F8
1383   };
1384   return FPR;
1385 }
1386
1387 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1388 /// the stack.
1389 static unsigned CalculateStackSlotSize(SDValue Arg, ISD::ArgFlagsTy Flags,
1390                                        bool isVarArg, unsigned PtrByteSize) {
1391   MVT ArgVT = Arg.getValueType();
1392   unsigned ArgSize =ArgVT.getSizeInBits()/8;
1393   if (Flags.isByVal())
1394     ArgSize = Flags.getByValSize();
1395   ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1396
1397   return ArgSize;
1398 }
1399
1400 SDValue
1401 PPCTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
1402                                          SelectionDAG &DAG,
1403                                          int &VarArgsFrameIndex,
1404                                          int &VarArgsStackOffset,
1405                                          unsigned &VarArgsNumGPR,
1406                                          unsigned &VarArgsNumFPR,
1407                                          const PPCSubtarget &Subtarget) {
1408   // TODO: add description of PPC stack frame format, or at least some docs.
1409   //
1410   MachineFunction &MF = DAG.getMachineFunction();
1411   MachineFrameInfo *MFI = MF.getFrameInfo();
1412   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1413   SmallVector<SDValue, 8> ArgValues;
1414   SDValue Root = Op.getOperand(0);
1415   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1416   DebugLoc dl = Op.getDebugLoc();
1417
1418   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1419   bool isPPC64 = PtrVT == MVT::i64;
1420   bool isMachoABI = Subtarget.isMachoABI();
1421   bool isELF32_ABI = Subtarget.isELF32_ABI();
1422   // Potential tail calls could cause overwriting of argument stack slots.
1423   unsigned CC = MF.getFunction()->getCallingConv();
1424   bool isImmutable = !(PerformTailCallOpt && (CC==CallingConv::Fast));
1425   unsigned PtrByteSize = isPPC64 ? 8 : 4;
1426
1427   unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1428   // Area that is at least reserved in caller of this function.
1429   unsigned MinReservedArea = ArgOffset;
1430
1431   static const unsigned GPR_32[] = {           // 32-bit registers.
1432     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1433     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1434   };
1435   static const unsigned GPR_64[] = {           // 64-bit registers.
1436     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1437     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1438   };
1439
1440   static const unsigned *FPR = GetFPR(Subtarget);
1441
1442   static const unsigned VR[] = {
1443     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1444     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1445   };
1446
1447   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
1448   const unsigned Num_FPR_Regs = isMachoABI ? 13 : 8;
1449   const unsigned Num_VR_Regs  = array_lengthof( VR);
1450
1451   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1452
1453   const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1454
1455   // In 32-bit non-varargs functions, the stack space for vectors is after the
1456   // stack space for non-vectors.  We do not use this space unless we have
1457   // too many vectors to fit in registers, something that only occurs in
1458   // constructed examples:), but we have to walk the arglist to figure
1459   // that out...for the pathological case, compute VecArgOffset as the
1460   // start of the vector parameter area.  Computing VecArgOffset is the
1461   // entire point of the following loop.
1462   // Altivec is not mentioned in the ppc32 Elf Supplement, so I'm not trying
1463   // to handle Elf here.
1464   unsigned VecArgOffset = ArgOffset;
1465   if (!isVarArg && !isPPC64) {
1466     for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues()-1; ArgNo != e;
1467          ++ArgNo) {
1468       MVT ObjectVT = Op.getValue(ArgNo).getValueType();
1469       unsigned ObjSize = ObjectVT.getSizeInBits()/8;
1470       ISD::ArgFlagsTy Flags =
1471         cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1472
1473       if (Flags.isByVal()) {
1474         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
1475         ObjSize = Flags.getByValSize();
1476         unsigned ArgSize =
1477                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1478         VecArgOffset += ArgSize;
1479         continue;
1480       }
1481
1482       switch(ObjectVT.getSimpleVT()) {
1483       default: assert(0 && "Unhandled argument type!");
1484       case MVT::i32:
1485       case MVT::f32:
1486         VecArgOffset += isPPC64 ? 8 : 4;
1487         break;
1488       case MVT::i64:  // PPC64
1489       case MVT::f64:
1490         VecArgOffset += 8;
1491         break;
1492       case MVT::v4f32:
1493       case MVT::v4i32:
1494       case MVT::v8i16:
1495       case MVT::v16i8:
1496         // Nothing to do, we're only looking at Nonvector args here.
1497         break;
1498       }
1499     }
1500   }
1501   // We've found where the vector parameter area in memory is.  Skip the
1502   // first 12 parameters; these don't use that memory.
1503   VecArgOffset = ((VecArgOffset+15)/16)*16;
1504   VecArgOffset += 12*16;
1505
1506   // Add DAG nodes to load the arguments or copy them out of registers.  On
1507   // entry to a function on PPC, the arguments start after the linkage area,
1508   // although the first ones are often in registers.
1509   //
1510   // In the ELF 32 ABI, GPRs and stack are double word align: an argument
1511   // represented with two words (long long or double) must be copied to an
1512   // even GPR_idx value or to an even ArgOffset value.
1513
1514   SmallVector<SDValue, 8> MemOps;
1515   unsigned nAltivecParamsAtEnd = 0;
1516   for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues() - 1;
1517        ArgNo != e; ++ArgNo) {
1518     SDValue ArgVal;
1519     bool needsLoad = false;
1520     MVT ObjectVT = Op.getValue(ArgNo).getValueType();
1521     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
1522     unsigned ArgSize = ObjSize;
1523     ISD::ArgFlagsTy Flags =
1524       cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1525     // See if next argument requires stack alignment in ELF
1526     bool Align = Flags.isSplit();
1527
1528     unsigned CurArgOffset = ArgOffset;
1529
1530     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
1531     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
1532         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
1533       if (isVarArg || isPPC64) {
1534         MinReservedArea = ((MinReservedArea+15)/16)*16;
1535         MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
1536                                                   Flags,
1537                                                   isVarArg,
1538                                                   PtrByteSize);
1539       } else  nAltivecParamsAtEnd++;
1540     } else
1541       // Calculate min reserved area.
1542       MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
1543                                                 Flags,
1544                                                 isVarArg,
1545                                                 PtrByteSize);
1546
1547     // FIXME alignment for ELF may not be right
1548     // FIXME the codegen can be much improved in some cases.
1549     // We do not have to keep everything in memory.
1550     if (Flags.isByVal()) {
1551       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
1552       ObjSize = Flags.getByValSize();
1553       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1554       // Double word align in ELF
1555       if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1556       // Objects of size 1 and 2 are right justified, everything else is
1557       // left justified.  This means the memory address is adjusted forwards.
1558       if (ObjSize==1 || ObjSize==2) {
1559         CurArgOffset = CurArgOffset + (4 - ObjSize);
1560       }
1561       // The value of the object is its address.
1562       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset);
1563       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1564       ArgValues.push_back(FIN);
1565       if (ObjSize==1 || ObjSize==2) {
1566         if (GPR_idx != Num_GPR_Regs) {
1567           unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1568           RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1569           SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1570           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
1571                                NULL, 0, ObjSize==1 ? MVT::i8 : MVT::i16 );
1572           MemOps.push_back(Store);
1573           ++GPR_idx;
1574           if (isMachoABI) ArgOffset += PtrByteSize;
1575         } else {
1576           ArgOffset += PtrByteSize;
1577         }
1578         continue;
1579       }
1580       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
1581         // Store whatever pieces of the object are in registers
1582         // to memory.  ArgVal will be address of the beginning of
1583         // the object.
1584         if (GPR_idx != Num_GPR_Regs) {
1585           unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1586           RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1587           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset);
1588           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1589           SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1590           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1591           MemOps.push_back(Store);
1592           ++GPR_idx;
1593           if (isMachoABI) ArgOffset += PtrByteSize;
1594         } else {
1595           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
1596           break;
1597         }
1598       }
1599       continue;
1600     }
1601
1602     switch (ObjectVT.getSimpleVT()) {
1603     default: assert(0 && "Unhandled argument type!");
1604     case MVT::i32:
1605       if (!isPPC64) {
1606         // Double word align in ELF
1607         if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1608
1609         if (GPR_idx != Num_GPR_Regs) {
1610           unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1611           RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1612           ArgVal = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
1613           ++GPR_idx;
1614         } else {
1615           needsLoad = true;
1616           ArgSize = PtrByteSize;
1617         }
1618         // Stack align in ELF
1619         if (needsLoad && Align && isELF32_ABI)
1620           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1621         // All int arguments reserve stack space in Macho ABI.
1622         if (isMachoABI || needsLoad) ArgOffset += PtrByteSize;
1623         break;
1624       }
1625       // FALLTHROUGH
1626     case MVT::i64:  // PPC64
1627       if (GPR_idx != Num_GPR_Regs) {
1628         unsigned VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
1629         RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1630         ArgVal = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1631
1632         if (ObjectVT == MVT::i32) {
1633           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
1634           // value to MVT::i64 and then truncate to the correct register size.
1635           if (Flags.isSExt())
1636             ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
1637                                  DAG.getValueType(ObjectVT));
1638           else if (Flags.isZExt())
1639             ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
1640                                  DAG.getValueType(ObjectVT));
1641
1642           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
1643         }
1644
1645         ++GPR_idx;
1646       } else {
1647         needsLoad = true;
1648         ArgSize = PtrByteSize;
1649       }
1650       // All int arguments reserve stack space in Macho ABI.
1651       if (isMachoABI || needsLoad) ArgOffset += 8;
1652       break;
1653
1654     case MVT::f32:
1655     case MVT::f64:
1656       // Every 4 bytes of argument space consumes one of the GPRs available for
1657       // argument passing.
1658       if (GPR_idx != Num_GPR_Regs && isMachoABI) {
1659         ++GPR_idx;
1660         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
1661           ++GPR_idx;
1662       }
1663       if (FPR_idx != Num_FPR_Regs) {
1664         unsigned VReg;
1665         if (ObjectVT == MVT::f32)
1666           VReg = RegInfo.createVirtualRegister(&PPC::F4RCRegClass);
1667         else
1668           VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
1669         RegInfo.addLiveIn(FPR[FPR_idx], VReg);
1670         ArgVal = DAG.getCopyFromReg(Root, dl, VReg, ObjectVT);
1671         ++FPR_idx;
1672       } else {
1673         needsLoad = true;
1674       }
1675
1676       // Stack align in ELF
1677       if (needsLoad && Align && isELF32_ABI)
1678         ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1679       // All FP arguments reserve stack space in Macho ABI.
1680       if (isMachoABI || needsLoad) ArgOffset += isPPC64 ? 8 : ObjSize;
1681       break;
1682     case MVT::v4f32:
1683     case MVT::v4i32:
1684     case MVT::v8i16:
1685     case MVT::v16i8:
1686       // Note that vector arguments in registers don't reserve stack space,
1687       // except in varargs functions.
1688       if (VR_idx != Num_VR_Regs) {
1689         unsigned VReg = RegInfo.createVirtualRegister(&PPC::VRRCRegClass);
1690         RegInfo.addLiveIn(VR[VR_idx], VReg);
1691         ArgVal = DAG.getCopyFromReg(Root, dl, VReg, ObjectVT);
1692         if (isVarArg) {
1693           while ((ArgOffset % 16) != 0) {
1694             ArgOffset += PtrByteSize;
1695             if (GPR_idx != Num_GPR_Regs)
1696               GPR_idx++;
1697           }
1698           ArgOffset += 16;
1699           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs);
1700         }
1701         ++VR_idx;
1702       } else {
1703         if (!isVarArg && !isPPC64) {
1704           // Vectors go after all the nonvectors.
1705           CurArgOffset = VecArgOffset;
1706           VecArgOffset += 16;
1707         } else {
1708           // Vectors are aligned.
1709           ArgOffset = ((ArgOffset+15)/16)*16;
1710           CurArgOffset = ArgOffset;
1711           ArgOffset += 16;
1712         }
1713         needsLoad = true;
1714       }
1715       break;
1716     }
1717
1718     // We need to load the argument to a virtual register if we determined above
1719     // that we ran out of physical registers of the appropriate type.
1720     if (needsLoad) {
1721       int FI = MFI->CreateFixedObject(ObjSize,
1722                                       CurArgOffset + (ArgSize - ObjSize),
1723                                       isImmutable);
1724       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1725       ArgVal = DAG.getLoad(ObjectVT, dl, Root, FIN, NULL, 0);
1726     }
1727
1728     ArgValues.push_back(ArgVal);
1729   }
1730
1731   // Set the size that is at least reserved in caller of this function.  Tail
1732   // call optimized function's reserved stack space needs to be aligned so that
1733   // taking the difference between two stack areas will result in an aligned
1734   // stack.
1735   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1736   // Add the Altivec parameters at the end, if needed.
1737   if (nAltivecParamsAtEnd) {
1738     MinReservedArea = ((MinReservedArea+15)/16)*16;
1739     MinReservedArea += 16*nAltivecParamsAtEnd;
1740   }
1741   MinReservedArea =
1742     std::max(MinReservedArea,
1743              PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
1744   unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
1745     getStackAlignment();
1746   unsigned AlignMask = TargetAlign-1;
1747   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1748   FI->setMinReservedArea(MinReservedArea);
1749
1750   // If the function takes variable number of arguments, make a frame index for
1751   // the start of the first vararg value... for expansion of llvm.va_start.
1752   if (isVarArg) {
1753
1754     int depth;
1755     if (isELF32_ABI) {
1756       VarArgsNumGPR = GPR_idx;
1757       VarArgsNumFPR = FPR_idx;
1758
1759       // Make room for Num_GPR_Regs, Num_FPR_Regs and for a possible frame
1760       // pointer.
1761       depth = -(Num_GPR_Regs * PtrVT.getSizeInBits()/8 +
1762                 Num_FPR_Regs * MVT(MVT::f64).getSizeInBits()/8 +
1763                 PtrVT.getSizeInBits()/8);
1764
1765       VarArgsStackOffset = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1766                                                   ArgOffset);
1767
1768     }
1769     else
1770       depth = ArgOffset;
1771
1772     VarArgsFrameIndex = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1773                                                depth);
1774     SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1775
1776     // In ELF 32 ABI, the fixed integer arguments of a variadic function are
1777     // stored to the VarArgsFrameIndex on the stack.
1778     if (isELF32_ABI) {
1779       for (GPR_idx = 0; GPR_idx != VarArgsNumGPR; ++GPR_idx) {
1780         SDValue Val = DAG.getRegister(GPR[GPR_idx], PtrVT);
1781         SDValue Store = DAG.getStore(Root, dl, Val, FIN, NULL, 0);
1782         MemOps.push_back(Store);
1783         // Increment the address by four for the next argument to store
1784         SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1785         FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1786       }
1787     }
1788
1789     // If this function is vararg, store any remaining integer argument regs
1790     // to their spots on the stack so that they may be loaded by deferencing the
1791     // result of va_next.
1792     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
1793       unsigned VReg;
1794       if (isPPC64)
1795         VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
1796       else
1797         VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1798
1799       RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1800       SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1801       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1802       MemOps.push_back(Store);
1803       // Increment the address by four for the next argument to store
1804       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1805       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1806     }
1807
1808     // In ELF 32 ABI, the double arguments are stored to the VarArgsFrameIndex
1809     // on the stack.
1810     if (isELF32_ABI) {
1811       for (FPR_idx = 0; FPR_idx != VarArgsNumFPR; ++FPR_idx) {
1812         SDValue Val = DAG.getRegister(FPR[FPR_idx], MVT::f64);
1813         SDValue Store = DAG.getStore(Root, dl, Val, FIN, NULL, 0);
1814         MemOps.push_back(Store);
1815         // Increment the address by eight for the next argument to store
1816         SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
1817                                            PtrVT);
1818         FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1819       }
1820
1821       for (; FPR_idx != Num_FPR_Regs; ++FPR_idx) {
1822         unsigned VReg;
1823         VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
1824
1825         RegInfo.addLiveIn(FPR[FPR_idx], VReg);
1826         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::f64);
1827         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1828         MemOps.push_back(Store);
1829         // Increment the address by eight for the next argument to store
1830         SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
1831                                            PtrVT);
1832         FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1833       }
1834     }
1835   }
1836
1837   if (!MemOps.empty())
1838     Root = DAG.getNode(ISD::TokenFactor, dl,
1839                        MVT::Other, &MemOps[0], MemOps.size());
1840
1841   ArgValues.push_back(Root);
1842
1843   // Return the new list of results.
1844   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1845                      &ArgValues[0], ArgValues.size());
1846 }
1847
1848 /// CalculateParameterAndLinkageAreaSize - Get the size of the paramter plus
1849 /// linkage area.
1850 static unsigned
1851 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
1852                                      bool isPPC64,
1853                                      bool isMachoABI,
1854                                      bool isVarArg,
1855                                      unsigned CC,
1856                                      CallSDNode *TheCall,
1857                                      unsigned &nAltivecParamsAtEnd) {
1858   // Count how many bytes are to be pushed on the stack, including the linkage
1859   // area, and parameter passing area.  We start with 24/48 bytes, which is
1860   // prereserved space for [SP][CR][LR][3 x unused].
1861   unsigned NumBytes = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1862   unsigned NumOps = TheCall->getNumArgs();
1863   unsigned PtrByteSize = isPPC64 ? 8 : 4;
1864
1865   // Add up all the space actually used.
1866   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
1867   // they all go in registers, but we must reserve stack space for them for
1868   // possible use by the caller.  In varargs or 64-bit calls, parameters are
1869   // assigned stack space in order, with padding so Altivec parameters are
1870   // 16-byte aligned.
1871   nAltivecParamsAtEnd = 0;
1872   for (unsigned i = 0; i != NumOps; ++i) {
1873     SDValue Arg = TheCall->getArg(i);
1874     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1875     MVT ArgVT = Arg.getValueType();
1876     // Varargs Altivec parameters are padded to a 16 byte boundary.
1877     if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
1878         ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
1879       if (!isVarArg && !isPPC64) {
1880         // Non-varargs Altivec parameters go after all the non-Altivec
1881         // parameters; handle those later so we know how much padding we need.
1882         nAltivecParamsAtEnd++;
1883         continue;
1884       }
1885       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
1886       NumBytes = ((NumBytes+15)/16)*16;
1887     }
1888     NumBytes += CalculateStackSlotSize(Arg, Flags, isVarArg, PtrByteSize);
1889   }
1890
1891    // Allow for Altivec parameters at the end, if needed.
1892   if (nAltivecParamsAtEnd) {
1893     NumBytes = ((NumBytes+15)/16)*16;
1894     NumBytes += 16*nAltivecParamsAtEnd;
1895   }
1896
1897   // The prolog code of the callee may store up to 8 GPR argument registers to
1898   // the stack, allowing va_start to index over them in memory if its varargs.
1899   // Because we cannot tell if this is needed on the caller side, we have to
1900   // conservatively assume that it is needed.  As such, make sure we have at
1901   // least enough stack space for the caller to store the 8 GPRs.
1902   NumBytes = std::max(NumBytes,
1903                       PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
1904
1905   // Tail call needs the stack to be aligned.
1906   if (CC==CallingConv::Fast && PerformTailCallOpt) {
1907     unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
1908       getStackAlignment();
1909     unsigned AlignMask = TargetAlign-1;
1910     NumBytes = (NumBytes + AlignMask) & ~AlignMask;
1911   }
1912
1913   return NumBytes;
1914 }
1915
1916 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
1917 /// adjusted to accomodate the arguments for the tailcall.
1918 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool IsTailCall,
1919                                    unsigned ParamSize) {
1920
1921   if (!IsTailCall) return 0;
1922
1923   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
1924   unsigned CallerMinReservedArea = FI->getMinReservedArea();
1925   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
1926   // Remember only if the new adjustement is bigger.
1927   if (SPDiff < FI->getTailCallSPDelta())
1928     FI->setTailCallSPDelta(SPDiff);
1929
1930   return SPDiff;
1931 }
1932
1933 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1934 /// following the call is a return. A function is eligible if caller/callee
1935 /// calling conventions match, currently only fastcc supports tail calls, and
1936 /// the function CALL is immediatly followed by a RET.
1937 bool
1938 PPCTargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1939                                                      SDValue Ret,
1940                                                      SelectionDAG& DAG) const {
1941   // Variable argument functions are not supported.
1942   if (!PerformTailCallOpt || TheCall->isVarArg())
1943     return false;
1944
1945   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1946     MachineFunction &MF = DAG.getMachineFunction();
1947     unsigned CallerCC = MF.getFunction()->getCallingConv();
1948     unsigned CalleeCC = TheCall->getCallingConv();
1949     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1950       // Functions containing by val parameters are not supported.
1951       for (unsigned i = 0; i != TheCall->getNumArgs(); i++) {
1952          ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1953          if (Flags.isByVal()) return false;
1954       }
1955
1956       SDValue Callee = TheCall->getCallee();
1957       // Non PIC/GOT  tail calls are supported.
1958       if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1959         return true;
1960
1961       // At the moment we can only do local tail calls (in same module, hidden
1962       // or protected) if we are generating PIC.
1963       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1964         return G->getGlobal()->hasHiddenVisibility()
1965             || G->getGlobal()->hasProtectedVisibility();
1966     }
1967   }
1968
1969   return false;
1970 }
1971
1972 /// isCallCompatibleAddress - Return the immediate to use if the specified
1973 /// 32-bit value is representable in the immediate field of a BxA instruction.
1974 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
1975   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1976   if (!C) return 0;
1977
1978   int Addr = C->getZExtValue();
1979   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
1980       (Addr << 6 >> 6) != Addr)
1981     return 0;  // Top 6 bits have to be sext of immediate.
1982
1983   return DAG.getConstant((int)C->getZExtValue() >> 2,
1984                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
1985 }
1986
1987 namespace {
1988
1989 struct TailCallArgumentInfo {
1990   SDValue Arg;
1991   SDValue FrameIdxOp;
1992   int       FrameIdx;
1993
1994   TailCallArgumentInfo() : FrameIdx(0) {}
1995 };
1996
1997 }
1998
1999 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2000 static void
2001 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2002                                            SDValue Chain,
2003                    const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2004                    SmallVector<SDValue, 8> &MemOpChains,
2005                    DebugLoc dl) {
2006   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2007     SDValue Arg = TailCallArgs[i].Arg;
2008     SDValue FIN = TailCallArgs[i].FrameIdxOp;
2009     int FI = TailCallArgs[i].FrameIdx;
2010     // Store relative to framepointer.
2011     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2012                                        PseudoSourceValue::getFixedStack(FI),
2013                                        0));
2014   }
2015 }
2016
2017 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2018 /// the appropriate stack slot for the tail call optimized function call.
2019 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2020                                                MachineFunction &MF,
2021                                                SDValue Chain,
2022                                                SDValue OldRetAddr,
2023                                                SDValue OldFP,
2024                                                int SPDiff,
2025                                                bool isPPC64,
2026                                                bool isMachoABI,
2027                                                DebugLoc dl) {
2028   if (SPDiff) {
2029     // Calculate the new stack slot for the return address.
2030     int SlotSize = isPPC64 ? 8 : 4;
2031     int NewRetAddrLoc = SPDiff + PPCFrameInfo::getReturnSaveOffset(isPPC64,
2032                                                                    isMachoABI);
2033     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2034                                                           NewRetAddrLoc);
2035     int NewFPLoc = SPDiff + PPCFrameInfo::getFramePointerSaveOffset(isPPC64,
2036                                                                     isMachoABI);
2037     int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc);
2038
2039     MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2040     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2041     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2042                          PseudoSourceValue::getFixedStack(NewRetAddr), 0);
2043     SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2044     Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2045                          PseudoSourceValue::getFixedStack(NewFPIdx), 0);
2046   }
2047   return Chain;
2048 }
2049
2050 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2051 /// the position of the argument.
2052 static void
2053 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2054                          SDValue Arg, int SPDiff, unsigned ArgOffset,
2055                       SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2056   int Offset = ArgOffset + SPDiff;
2057   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2058   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
2059   MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2060   SDValue FIN = DAG.getFrameIndex(FI, VT);
2061   TailCallArgumentInfo Info;
2062   Info.Arg = Arg;
2063   Info.FrameIdxOp = FIN;
2064   Info.FrameIdx = FI;
2065   TailCallArguments.push_back(Info);
2066 }
2067
2068 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2069 /// stack slot. Returns the chain as result and the loaded frame pointers in
2070 /// LROpOut/FPOpout. Used when tail calling.
2071 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2072                                                         int SPDiff,
2073                                                         SDValue Chain,
2074                                                         SDValue &LROpOut,
2075                                                         SDValue &FPOpOut,
2076                                                         DebugLoc dl) {
2077   if (SPDiff) {
2078     // Load the LR and FP stack slot for later adjusting.
2079     MVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2080     LROpOut = getReturnAddrFrameIndex(DAG);
2081     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, NULL, 0);
2082     Chain = SDValue(LROpOut.getNode(), 1);
2083     FPOpOut = getFramePointerFrameIndex(DAG);
2084     FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, NULL, 0);
2085     Chain = SDValue(FPOpOut.getNode(), 1);
2086   }
2087   return Chain;
2088 }
2089
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" of size "Size".  Alignment information is
2092 /// specified by the specific parameter attribute. The copy will be passed as
2093 /// a byval function parameter.
2094 /// Sometimes what we are copying is the end of a larger object, the part that
2095 /// does not fit in registers.
2096 static SDValue
2097 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2098                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2099                           unsigned Size, DebugLoc dl) {
2100   SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
2101   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2102                        false, NULL, 0, NULL, 0);
2103 }
2104
2105 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
2106 /// tail calls.
2107 static void
2108 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
2109                  SDValue Arg, SDValue PtrOff, int SPDiff,
2110                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
2111                  bool isVector, SmallVector<SDValue, 8> &MemOpChains,
2112                  SmallVector<TailCallArgumentInfo, 8>& TailCallArguments,
2113                  DebugLoc dl) {
2114   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2115   if (!isTailCall) {
2116     if (isVector) {
2117       SDValue StackPtr;
2118       if (isPPC64)
2119         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2120       else
2121         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2122       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2123                            DAG.getConstant(ArgOffset, PtrVT));
2124     }
2125     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
2126   // Calculate and remember argument location.
2127   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
2128                                   TailCallArguments);
2129 }
2130
2131 SDValue PPCTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG,
2132                                        const PPCSubtarget &Subtarget,
2133                                        TargetMachine &TM) {
2134   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
2135   SDValue Chain  = TheCall->getChain();
2136   bool isVarArg   = TheCall->isVarArg();
2137   unsigned CC     = TheCall->getCallingConv();
2138   bool isTailCall = TheCall->isTailCall()
2139                  && CC == CallingConv::Fast && PerformTailCallOpt;
2140   SDValue Callee = TheCall->getCallee();
2141   unsigned NumOps  = TheCall->getNumArgs();
2142   DebugLoc dl = TheCall->getDebugLoc();
2143
2144   bool isMachoABI = Subtarget.isMachoABI();
2145   bool isELF32_ABI  = Subtarget.isELF32_ABI();
2146
2147   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2148   bool isPPC64 = PtrVT == MVT::i64;
2149   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2150
2151   MachineFunction &MF = DAG.getMachineFunction();
2152
2153   // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
2154   // SelectExpr to use to put the arguments in the appropriate registers.
2155   std::vector<SDValue> args_to_use;
2156
2157   // Mark this function as potentially containing a function that contains a
2158   // tail call. As a consequence the frame pointer will be used for dynamicalloc
2159   // and restoring the callers stack pointer in this functions epilog. This is
2160   // done because by tail calling the called function might overwrite the value
2161   // in this function's (MF) stack pointer stack slot 0(SP).
2162   if (PerformTailCallOpt && CC==CallingConv::Fast)
2163     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
2164
2165   unsigned nAltivecParamsAtEnd = 0;
2166
2167   // Count how many bytes are to be pushed on the stack, including the linkage
2168   // area, and parameter passing area.  We start with 24/48 bytes, which is
2169   // prereserved space for [SP][CR][LR][3 x unused].
2170   unsigned NumBytes =
2171     CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isMachoABI, isVarArg, CC,
2172                                          TheCall, nAltivecParamsAtEnd);
2173
2174   // Calculate by how many bytes the stack has to be adjusted in case of tail
2175   // call optimization.
2176   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
2177
2178   // Adjust the stack pointer for the new arguments...
2179   // These operations are automatically eliminated by the prolog/epilog pass
2180   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2181   SDValue CallSeqStart = Chain;
2182
2183   // Load the return address and frame pointer so it can be move somewhere else
2184   // later.
2185   SDValue LROp, FPOp;
2186   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
2187
2188   // Set up a copy of the stack pointer for use loading and storing any
2189   // arguments that may not fit in the registers available for argument
2190   // passing.
2191   SDValue StackPtr;
2192   if (isPPC64)
2193     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2194   else
2195     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2196
2197   // Figure out which arguments are going to go in registers, and which in
2198   // memory.  Also, if this is a vararg function, floating point operations
2199   // must be stored to our stack, and loaded into integer regs as well, if
2200   // any integer regs are available for argument passing.
2201   unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
2202   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2203
2204   static const unsigned GPR_32[] = {           // 32-bit registers.
2205     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2206     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2207   };
2208   static const unsigned GPR_64[] = {           // 64-bit registers.
2209     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2210     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2211   };
2212   static const unsigned *FPR = GetFPR(Subtarget);
2213
2214   static const unsigned VR[] = {
2215     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2216     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2217   };
2218   const unsigned NumGPRs = array_lengthof(GPR_32);
2219   const unsigned NumFPRs = isMachoABI ? 13 : 8;
2220   const unsigned NumVRs  = array_lengthof( VR);
2221
2222   const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
2223
2224   std::vector<std::pair<unsigned, SDValue> > RegsToPass;
2225   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
2226
2227   SmallVector<SDValue, 8> MemOpChains;
2228   for (unsigned i = 0; i != NumOps; ++i) {
2229     bool inMem = false;
2230     SDValue Arg = TheCall->getArg(i);
2231     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
2232     // See if next argument requires stack alignment in ELF
2233     bool Align = Flags.isSplit();
2234
2235     // PtrOff will be used to store the current argument to the stack if a
2236     // register cannot be found for it.
2237     SDValue PtrOff;
2238
2239     // Stack align in ELF 32
2240     if (isELF32_ABI && Align)
2241       PtrOff = DAG.getConstant(ArgOffset + ((ArgOffset/4) % 2) * PtrByteSize,
2242                                StackPtr.getValueType());
2243     else
2244       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
2245
2246     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
2247
2248     // On PPC64, promote integers to 64-bit values.
2249     if (isPPC64 && Arg.getValueType() == MVT::i32) {
2250       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
2251       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2252       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
2253     }
2254
2255     // FIXME Elf untested, what are alignment rules?
2256     // FIXME memcpy is used way more than necessary.  Correctness first.
2257     if (Flags.isByVal()) {
2258       unsigned Size = Flags.getByValSize();
2259       if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
2260       if (Size==1 || Size==2) {
2261         // Very small objects are passed right-justified.
2262         // Everything else is passed left-justified.
2263         MVT VT = (Size==1) ? MVT::i8 : MVT::i16;
2264         if (GPR_idx != NumGPRs) {
2265           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
2266                                           NULL, 0, VT);
2267           MemOpChains.push_back(Load.getValue(1));
2268           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2269           if (isMachoABI)
2270             ArgOffset += PtrByteSize;
2271         } else {
2272           SDValue Const = DAG.getConstant(4 - Size, PtrOff.getValueType());
2273           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
2274           SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr,
2275                                 CallSeqStart.getNode()->getOperand(0),
2276                                 Flags, DAG, Size, dl);
2277           // This must go outside the CALLSEQ_START..END.
2278           SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2279                                CallSeqStart.getNode()->getOperand(1));
2280           DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
2281                                  NewCallSeqStart.getNode());
2282           Chain = CallSeqStart = NewCallSeqStart;
2283           ArgOffset += PtrByteSize;
2284         }
2285         continue;
2286       }
2287       // Copy entire object into memory.  There are cases where gcc-generated
2288       // code assumes it is there, even if it could be put entirely into
2289       // registers.  (This is not what the doc says.)
2290       SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
2291                             CallSeqStart.getNode()->getOperand(0),
2292                             Flags, DAG, Size, dl);
2293       // This must go outside the CALLSEQ_START..END.
2294       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2295                            CallSeqStart.getNode()->getOperand(1));
2296       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode());
2297       Chain = CallSeqStart = NewCallSeqStart;
2298       // And copy the pieces of it that fit into registers.
2299       for (unsigned j=0; j<Size; j+=PtrByteSize) {
2300         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
2301         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2302         if (GPR_idx != NumGPRs) {
2303           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, NULL, 0);
2304           MemOpChains.push_back(Load.getValue(1));
2305           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2306           if (isMachoABI)
2307             ArgOffset += PtrByteSize;
2308         } else {
2309           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
2310           break;
2311         }
2312       }
2313       continue;
2314     }
2315
2316     switch (Arg.getValueType().getSimpleVT()) {
2317     default: assert(0 && "Unexpected ValueType for argument!");
2318     case MVT::i32:
2319     case MVT::i64:
2320       // Double word align in ELF
2321       if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
2322       if (GPR_idx != NumGPRs) {
2323         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
2324       } else {
2325         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2326                          isPPC64, isTailCall, false, MemOpChains,
2327                          TailCallArguments, dl);
2328         inMem = true;
2329       }
2330       if (inMem || isMachoABI) {
2331         // Stack align in ELF
2332         if (isELF32_ABI && Align)
2333           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
2334
2335         ArgOffset += PtrByteSize;
2336       }
2337       break;
2338     case MVT::f32:
2339     case MVT::f64:
2340       if (FPR_idx != NumFPRs) {
2341         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
2342
2343         if (isVarArg) {
2344           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0);
2345           MemOpChains.push_back(Store);
2346
2347           // Float varargs are always shadowed in available integer registers
2348           if (GPR_idx != NumGPRs) {
2349             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, NULL, 0);
2350             MemOpChains.push_back(Load.getValue(1));
2351             if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
2352                                                                 Load));
2353           }
2354           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
2355             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
2356             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
2357             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, NULL, 0);
2358             MemOpChains.push_back(Load.getValue(1));
2359             if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
2360                                                                 Load));
2361           }
2362         } else {
2363           // If we have any FPRs remaining, we may also have GPRs remaining.
2364           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
2365           // GPRs.
2366           if (isMachoABI) {
2367             if (GPR_idx != NumGPRs)
2368               ++GPR_idx;
2369             if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
2370                 !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
2371               ++GPR_idx;
2372           }
2373         }
2374       } else {
2375         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2376                          isPPC64, isTailCall, false, MemOpChains,
2377                          TailCallArguments, dl);
2378         inMem = true;
2379       }
2380       if (inMem || isMachoABI) {
2381         // Stack align in ELF
2382         if (isELF32_ABI && Align)
2383           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
2384         if (isPPC64)
2385           ArgOffset += 8;
2386         else
2387           ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
2388       }
2389       break;
2390     case MVT::v4f32:
2391     case MVT::v4i32:
2392     case MVT::v8i16:
2393     case MVT::v16i8:
2394       if (isVarArg) {
2395         // These go aligned on the stack, or in the corresponding R registers
2396         // when within range.  The Darwin PPC ABI doc claims they also go in
2397         // V registers; in fact gcc does this only for arguments that are
2398         // prototyped, not for those that match the ...  We do it for all
2399         // arguments, seems to work.
2400         while (ArgOffset % 16 !=0) {
2401           ArgOffset += PtrByteSize;
2402           if (GPR_idx != NumGPRs)
2403             GPR_idx++;
2404         }
2405         // We could elide this store in the case where the object fits
2406         // entirely in R registers.  Maybe later.
2407         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2408                             DAG.getConstant(ArgOffset, PtrVT));
2409         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0);
2410         MemOpChains.push_back(Store);
2411         if (VR_idx != NumVRs) {
2412           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, NULL, 0);
2413           MemOpChains.push_back(Load.getValue(1));
2414           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
2415         }
2416         ArgOffset += 16;
2417         for (unsigned i=0; i<16; i+=PtrByteSize) {
2418           if (GPR_idx == NumGPRs)
2419             break;
2420           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
2421                                   DAG.getConstant(i, PtrVT));
2422           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, NULL, 0);
2423           MemOpChains.push_back(Load.getValue(1));
2424           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2425         }
2426         break;
2427       }
2428
2429       // Non-varargs Altivec params generally go in registers, but have
2430       // stack space allocated at the end.
2431       if (VR_idx != NumVRs) {
2432         // Doesn't have GPR space allocated.
2433         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
2434       } else if (nAltivecParamsAtEnd==0) {
2435         // We are emitting Altivec params in order.
2436         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2437                          isPPC64, isTailCall, true, MemOpChains,
2438                          TailCallArguments, dl);
2439         ArgOffset += 16;
2440       }
2441       break;
2442     }
2443   }
2444   // If all Altivec parameters fit in registers, as they usually do,
2445   // they get stack space following the non-Altivec parameters.  We
2446   // don't track this here because nobody below needs it.
2447   // If there are more Altivec parameters than fit in registers emit
2448   // the stores here.
2449   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
2450     unsigned j = 0;
2451     // Offset is aligned; skip 1st 12 params which go in V registers.
2452     ArgOffset = ((ArgOffset+15)/16)*16;
2453     ArgOffset += 12*16;
2454     for (unsigned i = 0; i != NumOps; ++i) {
2455       SDValue Arg = TheCall->getArg(i);
2456       MVT ArgType = Arg.getValueType();
2457       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
2458           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
2459         if (++j > NumVRs) {
2460           SDValue PtrOff;
2461           // We are emitting Altivec params in order.
2462           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2463                            isPPC64, isTailCall, true, MemOpChains,
2464                            TailCallArguments, dl);
2465           ArgOffset += 16;
2466         }
2467       }
2468     }
2469   }
2470
2471   if (!MemOpChains.empty())
2472     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2473                         &MemOpChains[0], MemOpChains.size());
2474
2475   // Build a sequence of copy-to-reg nodes chained together with token chain
2476   // and flag operands which copy the outgoing args into the appropriate regs.
2477   SDValue InFlag;
2478   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2479     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2480                              RegsToPass[i].second, InFlag);
2481     InFlag = Chain.getValue(1);
2482   }
2483
2484   // With the ELF 32 ABI, set CR6 to true if this is a vararg call.
2485   if (isVarArg && isELF32_ABI) {
2486     SDValue SetCR(DAG.getTargetNode(PPC::CRSET, dl, MVT::i32), 0);
2487     Chain = DAG.getCopyToReg(Chain, dl, PPC::CR1EQ, SetCR, InFlag);
2488     InFlag = Chain.getValue(1);
2489   }
2490
2491   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
2492   // might overwrite each other in case of tail call optimization.
2493   if (isTailCall) {
2494     SmallVector<SDValue, 8> MemOpChains2;
2495     // Do not flag preceeding copytoreg stuff together with the following stuff.
2496     InFlag = SDValue();
2497     StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
2498                                       MemOpChains2, dl);
2499     if (!MemOpChains2.empty())
2500       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2501                           &MemOpChains2[0], MemOpChains2.size());
2502
2503     // Store the return address to the appropriate stack slot.
2504     Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
2505                                           isPPC64, isMachoABI, dl);
2506   }
2507
2508   // Emit callseq_end just before tailcall node.
2509   if (isTailCall) {
2510     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2511                                DAG.getIntPtrConstant(0, true), InFlag);
2512     InFlag = Chain.getValue(1);
2513   }
2514
2515   std::vector<MVT> NodeTys;
2516   NodeTys.push_back(MVT::Other);   // Returns a chain
2517   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
2518
2519   SmallVector<SDValue, 8> Ops;
2520   unsigned CallOpc = isMachoABI? PPCISD::CALL_Macho : PPCISD::CALL_ELF;
2521
2522   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2523   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2524   // node so that legalize doesn't hack it.
2525   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2526     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
2527   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
2528     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
2529   else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
2530     // If this is an absolute destination address, use the munged value.
2531     Callee = SDValue(Dest, 0);
2532   else {
2533     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
2534     // to do the call, we can't use PPCISD::CALL.
2535     SDValue MTCTROps[] = {Chain, Callee, InFlag};
2536     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
2537                         2 + (InFlag.getNode() != 0));
2538     InFlag = Chain.getValue(1);
2539
2540     // Copy the callee address into R12/X12 on darwin.
2541     if (isMachoABI) {
2542       unsigned Reg = Callee.getValueType() == MVT::i32 ? PPC::R12 : PPC::X12;
2543       Chain = DAG.getCopyToReg(Chain, dl, Reg, Callee, InFlag);
2544       InFlag = Chain.getValue(1);
2545     }
2546
2547     NodeTys.clear();
2548     NodeTys.push_back(MVT::Other);
2549     NodeTys.push_back(MVT::Flag);
2550     Ops.push_back(Chain);
2551     CallOpc = isMachoABI ? PPCISD::BCTRL_Macho : PPCISD::BCTRL_ELF;
2552     Callee.setNode(0);
2553     // Add CTR register as callee so a bctr can be emitted later.
2554     if (isTailCall)
2555       Ops.push_back(DAG.getRegister(PPC::CTR, getPointerTy()));
2556   }
2557
2558   // If this is a direct call, pass the chain and the callee.
2559   if (Callee.getNode()) {
2560     Ops.push_back(Chain);
2561     Ops.push_back(Callee);
2562   }
2563   // If this is a tail call add stack pointer delta.
2564   if (isTailCall)
2565     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
2566
2567   // Add argument registers to the end of the list so that they are known live
2568   // into the call.
2569   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2570     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2571                                   RegsToPass[i].second.getValueType()));
2572
2573   // When performing tail call optimization the callee pops its arguments off
2574   // the stack. Account for this here so these bytes can be pushed back on in
2575   // PPCRegisterInfo::eliminateCallFramePseudoInstr.
2576   int BytesCalleePops =
2577     (CC==CallingConv::Fast && PerformTailCallOpt) ? NumBytes : 0;
2578
2579   if (InFlag.getNode())
2580     Ops.push_back(InFlag);
2581
2582   // Emit tail call.
2583   if (isTailCall) {
2584     assert(InFlag.getNode() &&
2585            "Flag must be set. Depend on flag being set in LowerRET");
2586     Chain = DAG.getNode(PPCISD::TAILCALL, dl,
2587                         TheCall->getVTList(), &Ops[0], Ops.size());
2588     return SDValue(Chain.getNode(), Op.getResNo());
2589   }
2590
2591   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
2592   InFlag = Chain.getValue(1);
2593
2594   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2595                              DAG.getIntPtrConstant(BytesCalleePops, true),
2596                              InFlag);
2597   if (TheCall->getValueType(0) != MVT::Other)
2598     InFlag = Chain.getValue(1);
2599
2600   SmallVector<SDValue, 16> ResultVals;
2601   SmallVector<CCValAssign, 16> RVLocs;
2602   unsigned CallerCC = DAG.getMachineFunction().getFunction()->getCallingConv();
2603   CCState CCInfo(CallerCC, isVarArg, TM, RVLocs);
2604   CCInfo.AnalyzeCallResult(TheCall, RetCC_PPC);
2605
2606   // Copy all of the result registers out of their specified physreg.
2607   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2608     CCValAssign &VA = RVLocs[i];
2609     MVT VT = VA.getValVT();
2610     assert(VA.isRegLoc() && "Can only return in registers!");
2611     Chain = DAG.getCopyFromReg(Chain, dl,
2612                                VA.getLocReg(), VT, InFlag).getValue(1);
2613     ResultVals.push_back(Chain.getValue(0));
2614     InFlag = Chain.getValue(2);
2615   }
2616
2617   // If the function returns void, just return the chain.
2618   if (RVLocs.empty())
2619     return Chain;
2620
2621   // Otherwise, merge everything together with a MERGE_VALUES node.
2622   ResultVals.push_back(Chain);
2623   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
2624                             &ResultVals[0], ResultVals.size());
2625   return Res.getValue(Op.getResNo());
2626 }
2627
2628 SDValue PPCTargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG,
2629                                       TargetMachine &TM) {
2630   SmallVector<CCValAssign, 16> RVLocs;
2631   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
2632   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
2633   DebugLoc dl = Op.getDebugLoc();
2634   CCState CCInfo(CC, isVarArg, TM, RVLocs);
2635   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_PPC);
2636
2637   // If this is the first return lowered for this function, add the regs to the
2638   // liveout set for the function.
2639   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2640     for (unsigned i = 0; i != RVLocs.size(); ++i)
2641       DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2642   }
2643
2644   SDValue Chain = Op.getOperand(0);
2645
2646   Chain = GetPossiblePreceedingTailCall(Chain, PPCISD::TAILCALL);
2647   if (Chain.getOpcode() == PPCISD::TAILCALL) {
2648     SDValue TailCall = Chain;
2649     SDValue TargetAddress = TailCall.getOperand(1);
2650     SDValue StackAdjustment = TailCall.getOperand(2);
2651
2652     assert(((TargetAddress.getOpcode() == ISD::Register &&
2653              cast<RegisterSDNode>(TargetAddress)->getReg() == PPC::CTR) ||
2654             TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
2655             TargetAddress.getOpcode() == ISD::TargetGlobalAddress ||
2656             isa<ConstantSDNode>(TargetAddress)) &&
2657     "Expecting an global address, external symbol, absolute value or register");
2658
2659     assert(StackAdjustment.getOpcode() == ISD::Constant &&
2660            "Expecting a const value");
2661
2662     SmallVector<SDValue,8> Operands;
2663     Operands.push_back(Chain.getOperand(0));
2664     Operands.push_back(TargetAddress);
2665     Operands.push_back(StackAdjustment);
2666     // Copy registers used by the call. Last operand is a flag so it is not
2667     // copied.
2668     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
2669       Operands.push_back(Chain.getOperand(i));
2670     }
2671     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Operands[0],
2672                        Operands.size());
2673   }
2674
2675   SDValue Flag;
2676
2677   // Copy the result values into the output registers.
2678   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2679     CCValAssign &VA = RVLocs[i];
2680     assert(VA.isRegLoc() && "Can only return in registers!");
2681     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2682                              Op.getOperand(i*2+1), Flag);
2683     Flag = Chain.getValue(1);
2684   }
2685
2686   if (Flag.getNode())
2687     return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
2688   else
2689     return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
2690 }
2691
2692 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
2693                                    const PPCSubtarget &Subtarget) {
2694   // When we pop the dynamic allocation we need to restore the SP link.
2695   DebugLoc dl = Op.getDebugLoc();
2696
2697   // Get the corect type for pointers.
2698   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2699
2700   // Construct the stack pointer operand.
2701   bool IsPPC64 = Subtarget.isPPC64();
2702   unsigned SP = IsPPC64 ? PPC::X1 : PPC::R1;
2703   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
2704
2705   // Get the operands for the STACKRESTORE.
2706   SDValue Chain = Op.getOperand(0);
2707   SDValue SaveSP = Op.getOperand(1);
2708
2709   // Load the old link SP.
2710   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, NULL, 0);
2711
2712   // Restore the stack pointer.
2713   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
2714
2715   // Store the old link SP.
2716   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, NULL, 0);
2717 }
2718
2719
2720
2721 SDValue
2722 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
2723   MachineFunction &MF = DAG.getMachineFunction();
2724   bool IsPPC64 = PPCSubTarget.isPPC64();
2725   bool isMachoABI = PPCSubTarget.isMachoABI();
2726   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2727
2728   // Get current frame pointer save index.  The users of this index will be
2729   // primarily DYNALLOC instructions.
2730   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2731   int RASI = FI->getReturnAddrSaveIndex();
2732
2733   // If the frame pointer save index hasn't been defined yet.
2734   if (!RASI) {
2735     // Find out what the fix offset of the frame pointer save area.
2736     int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, isMachoABI);
2737     // Allocate the frame index for frame pointer save area.
2738     RASI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, LROffset);
2739     // Save the result.
2740     FI->setReturnAddrSaveIndex(RASI);
2741   }
2742   return DAG.getFrameIndex(RASI, PtrVT);
2743 }
2744
2745 SDValue
2746 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
2747   MachineFunction &MF = DAG.getMachineFunction();
2748   bool IsPPC64 = PPCSubTarget.isPPC64();
2749   bool isMachoABI = PPCSubTarget.isMachoABI();
2750   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2751
2752   // Get current frame pointer save index.  The users of this index will be
2753   // primarily DYNALLOC instructions.
2754   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2755   int FPSI = FI->getFramePointerSaveIndex();
2756
2757   // If the frame pointer save index hasn't been defined yet.
2758   if (!FPSI) {
2759     // Find out what the fix offset of the frame pointer save area.
2760     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isMachoABI);
2761
2762     // Allocate the frame index for frame pointer save area.
2763     FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
2764     // Save the result.
2765     FI->setFramePointerSaveIndex(FPSI);
2766   }
2767   return DAG.getFrameIndex(FPSI, PtrVT);
2768 }
2769
2770 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
2771                                          SelectionDAG &DAG,
2772                                          const PPCSubtarget &Subtarget) {
2773   // Get the inputs.
2774   SDValue Chain = Op.getOperand(0);
2775   SDValue Size  = Op.getOperand(1);
2776   DebugLoc dl = Op.getDebugLoc();
2777
2778   // Get the corect type for pointers.
2779   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2780   // Negate the size.
2781   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
2782                                   DAG.getConstant(0, PtrVT), Size);
2783   // Construct a node for the frame pointer save index.
2784   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
2785   // Build a DYNALLOC node.
2786   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
2787   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
2788   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
2789 }
2790
2791 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
2792 /// possible.
2793 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
2794   // Not FP? Not a fsel.
2795   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
2796       !Op.getOperand(2).getValueType().isFloatingPoint())
2797     return SDValue();
2798
2799   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2800
2801   // Cannot handle SETEQ/SETNE.
2802   if (CC == ISD::SETEQ || CC == ISD::SETNE) return SDValue();
2803
2804   MVT ResVT = Op.getValueType();
2805   MVT CmpVT = Op.getOperand(0).getValueType();
2806   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2807   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
2808   DebugLoc dl = Op.getDebugLoc();
2809
2810   // If the RHS of the comparison is a 0.0, we don't need to do the
2811   // subtraction at all.
2812   if (isFloatingPointZero(RHS))
2813     switch (CC) {
2814     default: break;       // SETUO etc aren't handled by fsel.
2815     case ISD::SETULT:
2816     case ISD::SETLT:
2817       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2818     case ISD::SETOGE:
2819     case ISD::SETGE:
2820       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
2821         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
2822       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
2823     case ISD::SETUGT:
2824     case ISD::SETGT:
2825       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2826     case ISD::SETOLE:
2827     case ISD::SETLE:
2828       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
2829         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
2830       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
2831                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
2832     }
2833
2834   SDValue Cmp;
2835   switch (CC) {
2836   default: break;       // SETUO etc aren't handled by fsel.
2837   case ISD::SETULT:
2838   case ISD::SETLT:
2839     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
2840     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2841       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2842       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
2843   case ISD::SETOGE:
2844   case ISD::SETGE:
2845     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
2846     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2847       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2848       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
2849   case ISD::SETUGT:
2850   case ISD::SETGT:
2851     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
2852     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2853       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2854       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
2855   case ISD::SETOLE:
2856   case ISD::SETLE:
2857     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
2858     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2859       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2860       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
2861   }
2862   return SDValue();
2863 }
2864
2865 // FIXME: Split this code up when LegalizeDAGTypes lands.
2866 SDValue PPCTargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG,
2867                                            DebugLoc dl) {
2868   assert(Op.getOperand(0).getValueType().isFloatingPoint());
2869   SDValue Src = Op.getOperand(0);
2870   if (Src.getValueType() == MVT::f32)
2871     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
2872
2873   SDValue Tmp;
2874   switch (Op.getValueType().getSimpleVT()) {
2875   default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
2876   case MVT::i32:
2877     Tmp = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Src);
2878     break;
2879   case MVT::i64:
2880     Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
2881     break;
2882   }
2883
2884   // Convert the FP value to an int value through memory.
2885   SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
2886
2887   // Emit a store to the stack slot.
2888   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, NULL, 0);
2889
2890   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
2891   // add in a bias.
2892   if (Op.getValueType() == MVT::i32)
2893     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
2894                         DAG.getConstant(4, FIPtr.getValueType()));
2895   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, NULL, 0);
2896 }
2897
2898 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2899   DebugLoc dl = Op.getDebugLoc();
2900   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
2901   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
2902     return SDValue();
2903
2904   if (Op.getOperand(0).getValueType() == MVT::i64) {
2905     SDValue Bits = DAG.getNode(ISD::BIT_CONVERT, dl,
2906                                MVT::f64, Op.getOperand(0));
2907     SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
2908     if (Op.getValueType() == MVT::f32)
2909       FP = DAG.getNode(ISD::FP_ROUND, dl,
2910                        MVT::f32, FP, DAG.getIntPtrConstant(0));
2911     return FP;
2912   }
2913
2914   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2915          "Unhandled SINT_TO_FP type in custom expander!");
2916   // Since we only generate this in 64-bit mode, we can take advantage of
2917   // 64-bit registers.  In particular, sign extend the input value into the
2918   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
2919   // then lfd it and fcfid it.
2920   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2921   int FrameIdx = FrameInfo->CreateStackObject(8, 8);
2922   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2923   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
2924
2925   SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
2926                                 Op.getOperand(0));
2927
2928   // STD the extended value into the stack slot.
2929   MachineMemOperand MO(PseudoSourceValue::getFixedStack(FrameIdx),
2930                        MachineMemOperand::MOStore, 0, 8, 8);
2931   SDValue Store = DAG.getNode(PPCISD::STD_32, dl, MVT::Other,
2932                                 DAG.getEntryNode(), Ext64, FIdx,
2933                                 DAG.getMemOperand(MO));
2934   // Load the value as a double.
2935   SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, NULL, 0);
2936
2937   // FCFID it and return it.
2938   SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
2939   if (Op.getValueType() == MVT::f32)
2940     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
2941   return FP;
2942 }
2943
2944 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
2945   DebugLoc dl = Op.getDebugLoc();
2946   /*
2947    The rounding mode is in bits 30:31 of FPSR, and has the following
2948    settings:
2949      00 Round to nearest
2950      01 Round to 0
2951      10 Round to +inf
2952      11 Round to -inf
2953
2954   FLT_ROUNDS, on the other hand, expects the following:
2955     -1 Undefined
2956      0 Round to 0
2957      1 Round to nearest
2958      2 Round to +inf
2959      3 Round to -inf
2960
2961   To perform the conversion, we do:
2962     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
2963   */
2964
2965   MachineFunction &MF = DAG.getMachineFunction();
2966   MVT VT = Op.getValueType();
2967   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2968   std::vector<MVT> NodeTys;
2969   SDValue MFFSreg, InFlag;
2970
2971   // Save FP Control Word to register
2972   NodeTys.push_back(MVT::f64);    // return register
2973   NodeTys.push_back(MVT::Flag);   // unused in this context
2974   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
2975
2976   // Save FP register to stack slot
2977   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
2978   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
2979   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
2980                                  StackSlot, NULL, 0);
2981
2982   // Load FP Control Word from low 32 bits of stack slot.
2983   SDValue Four = DAG.getConstant(4, PtrVT);
2984   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
2985   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, NULL, 0);
2986
2987   // Transform as necessary
2988   SDValue CWD1 =
2989     DAG.getNode(ISD::AND, dl, MVT::i32,
2990                 CWD, DAG.getConstant(3, MVT::i32));
2991   SDValue CWD2 =
2992     DAG.getNode(ISD::SRL, dl, MVT::i32,
2993                 DAG.getNode(ISD::AND, dl, MVT::i32,
2994                             DAG.getNode(ISD::XOR, dl, MVT::i32,
2995                                         CWD, DAG.getConstant(3, MVT::i32)),
2996                             DAG.getConstant(3, MVT::i32)),
2997                 DAG.getConstant(1, MVT::i32));
2998
2999   SDValue RetVal =
3000     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
3001
3002   return DAG.getNode((VT.getSizeInBits() < 16 ?
3003                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
3004 }
3005
3006 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) {
3007   MVT VT = Op.getValueType();
3008   unsigned BitWidth = VT.getSizeInBits();
3009   DebugLoc dl = Op.getDebugLoc();
3010   assert(Op.getNumOperands() == 3 &&
3011          VT == Op.getOperand(1).getValueType() &&
3012          "Unexpected SHL!");
3013
3014   // Expand into a bunch of logical ops.  Note that these ops
3015   // depend on the PPC behavior for oversized shift amounts.
3016   SDValue Lo = Op.getOperand(0);
3017   SDValue Hi = Op.getOperand(1);
3018   SDValue Amt = Op.getOperand(2);
3019   MVT AmtVT = Amt.getValueType();
3020
3021   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3022                              DAG.getConstant(BitWidth, AmtVT), Amt);
3023   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
3024   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
3025   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
3026   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3027                              DAG.getConstant(-BitWidth, AmtVT));
3028   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
3029   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3030   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
3031   SDValue OutOps[] = { OutLo, OutHi };
3032   return DAG.getMergeValues(OutOps, 2, dl);
3033 }
3034
3035 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) {
3036   MVT VT = Op.getValueType();
3037   DebugLoc dl = Op.getDebugLoc();
3038   unsigned BitWidth = VT.getSizeInBits();
3039   assert(Op.getNumOperands() == 3 &&
3040          VT == Op.getOperand(1).getValueType() &&
3041          "Unexpected SRL!");
3042
3043   // Expand into a bunch of logical ops.  Note that these ops
3044   // depend on the PPC behavior for oversized shift amounts.
3045   SDValue Lo = Op.getOperand(0);
3046   SDValue Hi = Op.getOperand(1);
3047   SDValue Amt = Op.getOperand(2);
3048   MVT AmtVT = Amt.getValueType();
3049
3050   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3051                              DAG.getConstant(BitWidth, AmtVT), Amt);
3052   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3053   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3054   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3055   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3056                              DAG.getConstant(-BitWidth, AmtVT));
3057   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
3058   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3059   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
3060   SDValue OutOps[] = { OutLo, OutHi };
3061   return DAG.getMergeValues(OutOps, 2, dl);
3062 }
3063
3064 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) {
3065   DebugLoc dl = Op.getDebugLoc();
3066   MVT VT = Op.getValueType();
3067   unsigned BitWidth = VT.getSizeInBits();
3068   assert(Op.getNumOperands() == 3 &&
3069          VT == Op.getOperand(1).getValueType() &&
3070          "Unexpected SRA!");
3071
3072   // Expand into a bunch of logical ops, followed by a select_cc.
3073   SDValue Lo = Op.getOperand(0);
3074   SDValue Hi = Op.getOperand(1);
3075   SDValue Amt = Op.getOperand(2);
3076   MVT AmtVT = Amt.getValueType();
3077
3078   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3079                              DAG.getConstant(BitWidth, AmtVT), Amt);
3080   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3081   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3082   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3083   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3084                              DAG.getConstant(-BitWidth, AmtVT));
3085   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
3086   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
3087   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
3088                                   Tmp4, Tmp6, ISD::SETLE);
3089   SDValue OutOps[] = { OutLo, OutHi };
3090   return DAG.getMergeValues(OutOps, 2, dl);
3091 }
3092
3093 //===----------------------------------------------------------------------===//
3094 // Vector related lowering.
3095 //
3096
3097 /// BuildSplatI - Build a canonical splati of Val with an element size of
3098 /// SplatSize.  Cast the result to VT.
3099 static SDValue BuildSplatI(int Val, unsigned SplatSize, MVT VT,
3100                              SelectionDAG &DAG, DebugLoc dl) {
3101   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
3102
3103   static const MVT VTys[] = { // canonical VT to use for each size.
3104     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
3105   };
3106
3107   MVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
3108
3109   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
3110   if (Val == -1)
3111     SplatSize = 1;
3112
3113   MVT CanonicalVT = VTys[SplatSize-1];
3114
3115   // Build a canonical splat for this value.
3116   SDValue Elt = DAG.getConstant(Val, CanonicalVT.getVectorElementType());
3117   SmallVector<SDValue, 8> Ops;
3118   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
3119   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
3120                               &Ops[0], Ops.size());
3121   return DAG.getNode(ISD::BIT_CONVERT, dl, ReqVT, Res);
3122 }
3123
3124 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
3125 /// specified intrinsic ID.
3126 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
3127                                 SelectionDAG &DAG, DebugLoc dl,
3128                                 MVT DestVT = MVT::Other) {
3129   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
3130   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
3131                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
3132 }
3133
3134 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
3135 /// specified intrinsic ID.
3136 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
3137                                 SDValue Op2, SelectionDAG &DAG,
3138                                 DebugLoc dl, MVT DestVT = MVT::Other) {
3139   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
3140   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
3141                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
3142 }
3143
3144
3145 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
3146 /// amount.  The result has the specified value type.
3147 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
3148                              MVT VT, SelectionDAG &DAG, DebugLoc dl) {
3149   // Force LHS/RHS to be the right type.
3150   LHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, LHS);
3151   RHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, RHS);
3152
3153   int Ops[16];
3154   for (unsigned i = 0; i != 16; ++i)
3155     Ops[i] = i + Amt;
3156   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
3157   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, T);
3158 }
3159
3160 // If this is a case we can't handle, return null and let the default
3161 // expansion code take care of it.  If we CAN select this case, and if it
3162 // selects to a single instruction, return Op.  Otherwise, if we can codegen
3163 // this case more efficiently than a constant pool load, lower it to the
3164 // sequence of ops that should be used.
3165 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3166   DebugLoc dl = Op.getDebugLoc();
3167   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3168   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
3169
3170   // Check if this is a splat of a constant value.
3171   APInt APSplatBits, APSplatUndef;
3172   unsigned SplatBitSize;
3173   bool HasAnyUndefs;
3174   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
3175                              HasAnyUndefs) || SplatBitSize > 32)
3176     return SDValue();
3177
3178   unsigned SplatBits = APSplatBits.getZExtValue();
3179   unsigned SplatUndef = APSplatUndef.getZExtValue();
3180   unsigned SplatSize = SplatBitSize / 8;
3181
3182   // First, handle single instruction cases.
3183
3184   // All zeros?
3185   if (SplatBits == 0) {
3186     // Canonicalize all zero vectors to be v4i32.
3187     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
3188       SDValue Z = DAG.getConstant(0, MVT::i32);
3189       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
3190       Op = DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Z);
3191     }
3192     return Op;
3193   }
3194
3195   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
3196   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
3197                     (32-SplatBitSize));
3198   if (SextVal >= -16 && SextVal <= 15)
3199     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
3200
3201
3202   // Two instruction sequences.
3203
3204   // If this value is in the range [-32,30] and is even, use:
3205   //    tmp = VSPLTI[bhw], result = add tmp, tmp
3206   if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
3207     SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
3208     Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
3209     return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3210   }
3211
3212   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
3213   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
3214   // for fneg/fabs.
3215   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
3216     // Make -1 and vspltisw -1:
3217     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
3218
3219     // Make the VSLW intrinsic, computing 0x8000_0000.
3220     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
3221                                    OnesV, DAG, dl);
3222
3223     // xor by OnesV to invert it.
3224     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
3225     return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3226   }
3227
3228   // Check to see if this is a wide variety of vsplti*, binop self cases.
3229   static const signed char SplatCsts[] = {
3230     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
3231     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
3232   };
3233
3234   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
3235     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
3236     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
3237     int i = SplatCsts[idx];
3238
3239     // Figure out what shift amount will be used by altivec if shifted by i in
3240     // this splat size.
3241     unsigned TypeShiftAmt = i & (SplatBitSize-1);
3242
3243     // vsplti + shl self.
3244     if (SextVal == (i << (int)TypeShiftAmt)) {
3245       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3246       static const unsigned IIDs[] = { // Intrinsic to use for each size.
3247         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
3248         Intrinsic::ppc_altivec_vslw
3249       };
3250       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3251       return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3252     }
3253
3254     // vsplti + srl self.
3255     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3256       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3257       static const unsigned IIDs[] = { // Intrinsic to use for each size.
3258         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
3259         Intrinsic::ppc_altivec_vsrw
3260       };
3261       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3262       return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3263     }
3264
3265     // vsplti + sra self.
3266     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3267       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3268       static const unsigned IIDs[] = { // Intrinsic to use for each size.
3269         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
3270         Intrinsic::ppc_altivec_vsraw
3271       };
3272       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3273       return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3274     }
3275
3276     // vsplti + rol self.
3277     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
3278                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
3279       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3280       static const unsigned IIDs[] = { // Intrinsic to use for each size.
3281         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
3282         Intrinsic::ppc_altivec_vrlw
3283       };
3284       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3285       return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3286     }
3287
3288     // t = vsplti c, result = vsldoi t, t, 1
3289     if (SextVal == ((i << 8) | (i >> (TypeShiftAmt-8)))) {
3290       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3291       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
3292     }
3293     // t = vsplti c, result = vsldoi t, t, 2
3294     if (SextVal == ((i << 16) | (i >> (TypeShiftAmt-16)))) {
3295       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3296       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
3297     }
3298     // t = vsplti c, result = vsldoi t, t, 3
3299     if (SextVal == ((i << 24) | (i >> (TypeShiftAmt-24)))) {
3300       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3301       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
3302     }
3303   }
3304
3305   // Three instruction sequences.
3306
3307   // Odd, in range [17,31]:  (vsplti C)-(vsplti -16).
3308   if (SextVal >= 0 && SextVal <= 31) {
3309     SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
3310     SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
3311     LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
3312     return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), LHS);
3313   }
3314   // Odd, in range [-31,-17]:  (vsplti C)+(vsplti -16).
3315   if (SextVal >= -31 && SextVal <= 0) {
3316     SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
3317     SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
3318     LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
3319     return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), LHS);
3320   }
3321
3322   return SDValue();
3323 }
3324
3325 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
3326 /// the specified operations to build the shuffle.
3327 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
3328                                       SDValue RHS, SelectionDAG &DAG,
3329                                       DebugLoc dl) {
3330   unsigned OpNum = (PFEntry >> 26) & 0x0F;
3331   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
3332   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
3333
3334   enum {
3335     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
3336     OP_VMRGHW,
3337     OP_VMRGLW,
3338     OP_VSPLTISW0,
3339     OP_VSPLTISW1,
3340     OP_VSPLTISW2,
3341     OP_VSPLTISW3,
3342     OP_VSLDOI4,
3343     OP_VSLDOI8,
3344     OP_VSLDOI12
3345   };
3346
3347   if (OpNum == OP_COPY) {
3348     if (LHSID == (1*9+2)*9+3) return LHS;
3349     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
3350     return RHS;
3351   }
3352
3353   SDValue OpLHS, OpRHS;
3354   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
3355   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
3356
3357   int ShufIdxs[16];
3358   switch (OpNum) {
3359   default: assert(0 && "Unknown i32 permute!");
3360   case OP_VMRGHW:
3361     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
3362     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
3363     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
3364     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
3365     break;
3366   case OP_VMRGLW:
3367     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
3368     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
3369     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
3370     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
3371     break;
3372   case OP_VSPLTISW0:
3373     for (unsigned i = 0; i != 16; ++i)
3374       ShufIdxs[i] = (i&3)+0;
3375     break;
3376   case OP_VSPLTISW1:
3377     for (unsigned i = 0; i != 16; ++i)
3378       ShufIdxs[i] = (i&3)+4;
3379     break;
3380   case OP_VSPLTISW2:
3381     for (unsigned i = 0; i != 16; ++i)
3382       ShufIdxs[i] = (i&3)+8;
3383     break;
3384   case OP_VSPLTISW3:
3385     for (unsigned i = 0; i != 16; ++i)
3386       ShufIdxs[i] = (i&3)+12;
3387     break;
3388   case OP_VSLDOI4:
3389     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
3390   case OP_VSLDOI8:
3391     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
3392   case OP_VSLDOI12:
3393     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
3394   }
3395   MVT VT = OpLHS.getValueType();
3396   OpLHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OpLHS);
3397   OpRHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OpRHS);
3398   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
3399   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, T);
3400 }
3401
3402 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
3403 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
3404 /// return the code it can be lowered into.  Worst case, it can always be
3405 /// lowered into a vperm.
3406 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3407                                                SelectionDAG &DAG) {
3408   DebugLoc dl = Op.getDebugLoc();
3409   SDValue V1 = Op.getOperand(0);
3410   SDValue V2 = Op.getOperand(1);
3411   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3412   MVT VT = Op.getValueType();
3413
3414   // Cases that are handled by instructions that take permute immediates
3415   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
3416   // selected by the instruction selector.
3417   if (V2.getOpcode() == ISD::UNDEF) {
3418     if (PPC::isSplatShuffleMask(SVOp, 1) ||
3419         PPC::isSplatShuffleMask(SVOp, 2) ||
3420         PPC::isSplatShuffleMask(SVOp, 4) ||
3421         PPC::isVPKUWUMShuffleMask(SVOp, true) ||
3422         PPC::isVPKUHUMShuffleMask(SVOp, true) ||
3423         PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
3424         PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
3425         PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
3426         PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
3427         PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
3428         PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
3429         PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
3430       return Op;
3431     }
3432   }
3433
3434   // Altivec has a variety of "shuffle immediates" that take two vector inputs
3435   // and produce a fixed permutation.  If any of these match, do not lower to
3436   // VPERM.
3437   if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
3438       PPC::isVPKUHUMShuffleMask(SVOp, false) ||
3439       PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
3440       PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
3441       PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
3442       PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
3443       PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
3444       PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
3445       PPC::isVMRGHShuffleMask(SVOp, 4, false))
3446     return Op;
3447
3448   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
3449   // perfect shuffle table to emit an optimal matching sequence.
3450   SmallVector<int, 16> PermMask;
3451   SVOp->getMask(PermMask);
3452   
3453   unsigned PFIndexes[4];
3454   bool isFourElementShuffle = true;
3455   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
3456     unsigned EltNo = 8;   // Start out undef.
3457     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
3458       if (PermMask[i*4+j] < 0)
3459         continue;   // Undef, ignore it.
3460
3461       unsigned ByteSource = PermMask[i*4+j];
3462       if ((ByteSource & 3) != j) {
3463         isFourElementShuffle = false;
3464         break;
3465       }
3466
3467       if (EltNo == 8) {
3468         EltNo = ByteSource/4;
3469       } else if (EltNo != ByteSource/4) {
3470         isFourElementShuffle = false;
3471         break;
3472       }
3473     }
3474     PFIndexes[i] = EltNo;
3475   }
3476
3477   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
3478   // perfect shuffle vector to determine if it is cost effective to do this as
3479   // discrete instructions, or whether we should use a vperm.
3480   if (isFourElementShuffle) {
3481     // Compute the index in the perfect shuffle table.
3482     unsigned PFTableIndex =
3483       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3484
3485     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3486     unsigned Cost  = (PFEntry >> 30);
3487
3488     // Determining when to avoid vperm is tricky.  Many things affect the cost
3489     // of vperm, particularly how many times the perm mask needs to be computed.
3490     // For example, if the perm mask can be hoisted out of a loop or is already
3491     // used (perhaps because there are multiple permutes with the same shuffle
3492     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
3493     // the loop requires an extra register.
3494     //
3495     // As a compromise, we only emit discrete instructions if the shuffle can be
3496     // generated in 3 or fewer operations.  When we have loop information
3497     // available, if this block is within a loop, we should avoid using vperm
3498     // for 3-operation perms and use a constant pool load instead.
3499     if (Cost < 3)
3500       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
3501   }
3502
3503   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
3504   // vector that will get spilled to the constant pool.
3505   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
3506
3507   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
3508   // that it is in input element units, not in bytes.  Convert now.
3509   MVT EltVT = V1.getValueType().getVectorElementType();
3510   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
3511
3512   SmallVector<SDValue, 16> ResultMask;
3513   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
3514     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
3515
3516     for (unsigned j = 0; j != BytesPerElement; ++j)
3517       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
3518                                            MVT::i8));
3519   }
3520
3521   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
3522                                     &ResultMask[0], ResultMask.size());
3523   return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
3524 }
3525
3526 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
3527 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
3528 /// information about the intrinsic.
3529 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
3530                                   bool &isDot) {
3531   unsigned IntrinsicID =
3532     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
3533   CompareOpc = -1;
3534   isDot = false;
3535   switch (IntrinsicID) {
3536   default: return false;
3537     // Comparison predicates.
3538   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
3539   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
3540   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
3541   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
3542   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
3543   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
3544   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
3545   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
3546   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
3547   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
3548   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
3549   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
3550   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
3551
3552     // Normal Comparisons.
3553   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
3554   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
3555   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
3556   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
3557   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
3558   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
3559   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
3560   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
3561   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
3562   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
3563   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
3564   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
3565   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
3566   }
3567   return true;
3568 }
3569
3570 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
3571 /// lower, do it, otherwise return null.
3572 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3573                                                      SelectionDAG &DAG) {
3574   // If this is a lowered altivec predicate compare, CompareOpc is set to the
3575   // opcode number of the comparison.
3576   DebugLoc dl = Op.getDebugLoc();
3577   int CompareOpc;
3578   bool isDot;
3579   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
3580     return SDValue();    // Don't custom lower most intrinsics.
3581
3582   // If this is a non-dot comparison, make the VCMP node and we are done.
3583   if (!isDot) {
3584     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
3585                                 Op.getOperand(1), Op.getOperand(2),
3586                                 DAG.getConstant(CompareOpc, MVT::i32));
3587     return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Tmp);
3588   }
3589
3590   // Create the PPCISD altivec 'dot' comparison node.
3591   SDValue Ops[] = {
3592     Op.getOperand(2),  // LHS
3593     Op.getOperand(3),  // RHS
3594     DAG.getConstant(CompareOpc, MVT::i32)
3595   };
3596   std::vector<MVT> VTs;
3597   VTs.push_back(Op.getOperand(2).getValueType());
3598   VTs.push_back(MVT::Flag);
3599   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
3600
3601   // Now that we have the comparison, emit a copy from the CR to a GPR.
3602   // This is flagged to the above dot comparison.
3603   SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
3604                                 DAG.getRegister(PPC::CR6, MVT::i32),
3605                                 CompNode.getValue(1));
3606
3607   // Unpack the result based on how the target uses it.
3608   unsigned BitNo;   // Bit # of CR6.
3609   bool InvertBit;   // Invert result?
3610   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
3611   default:  // Can't happen, don't crash on invalid number though.
3612   case 0:   // Return the value of the EQ bit of CR6.
3613     BitNo = 0; InvertBit = false;
3614     break;
3615   case 1:   // Return the inverted value of the EQ bit of CR6.
3616     BitNo = 0; InvertBit = true;
3617     break;
3618   case 2:   // Return the value of the LT bit of CR6.
3619     BitNo = 2; InvertBit = false;
3620     break;
3621   case 3:   // Return the inverted value of the LT bit of CR6.
3622     BitNo = 2; InvertBit = true;
3623     break;
3624   }
3625
3626   // Shift the bit into the low position.
3627   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
3628                       DAG.getConstant(8-(3-BitNo), MVT::i32));
3629   // Isolate the bit.
3630   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
3631                       DAG.getConstant(1, MVT::i32));
3632
3633   // If we are supposed to, toggle the bit.
3634   if (InvertBit)
3635     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
3636                         DAG.getConstant(1, MVT::i32));
3637   return Flags;
3638 }
3639
3640 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
3641                                                    SelectionDAG &DAG) {
3642   DebugLoc dl = Op.getDebugLoc();
3643   // Create a stack slot that is 16-byte aligned.
3644   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3645   int FrameIdx = FrameInfo->CreateStackObject(16, 16);
3646   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3647   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
3648
3649   // Store the input value into Value#0 of the stack slot.
3650   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
3651                                  Op.getOperand(0), FIdx, NULL, 0);
3652   // Load it out.
3653   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, NULL, 0);
3654 }
3655
3656 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) {
3657   DebugLoc dl = Op.getDebugLoc();
3658   if (Op.getValueType() == MVT::v4i32) {
3659     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3660
3661     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
3662     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
3663
3664     SDValue RHSSwap =   // = vrlw RHS, 16
3665       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
3666
3667     // Shrinkify inputs to v8i16.
3668     LHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, LHS);
3669     RHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, RHS);
3670     RHSSwap = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, RHSSwap);
3671
3672     // Low parts multiplied together, generating 32-bit results (we ignore the
3673     // top parts).
3674     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
3675                                         LHS, RHS, DAG, dl, MVT::v4i32);
3676
3677     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
3678                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
3679     // Shift the high parts up 16 bits.
3680     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
3681                               Neg16, DAG, dl);
3682     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
3683   } else if (Op.getValueType() == MVT::v8i16) {
3684     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3685
3686     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
3687
3688     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
3689                             LHS, RHS, Zero, DAG, dl);
3690   } else if (Op.getValueType() == MVT::v16i8) {
3691     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3692
3693     // Multiply the even 8-bit parts, producing 16-bit sums.
3694     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
3695                                            LHS, RHS, DAG, dl, MVT::v8i16);
3696     EvenParts = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, EvenParts);
3697
3698     // Multiply the odd 8-bit parts, producing 16-bit sums.
3699     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
3700                                           LHS, RHS, DAG, dl, MVT::v8i16);
3701     OddParts = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OddParts);
3702
3703     // Merge the results together.
3704     int Ops[16];
3705     for (unsigned i = 0; i != 8; ++i) {
3706       Ops[i*2  ] = 2*i+1;
3707       Ops[i*2+1] = 2*i+1+16;
3708     }
3709     return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
3710   } else {
3711     assert(0 && "Unknown mul to lower!");
3712     abort();
3713   }
3714 }
3715
3716 /// LowerOperation - Provide custom lowering hooks for some operations.
3717 ///
3718 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
3719   switch (Op.getOpcode()) {
3720   default: assert(0 && "Wasn't expecting to be able to lower this!");
3721   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
3722   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
3723   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
3724   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
3725   case ISD::SETCC:              return LowerSETCC(Op, DAG);
3726   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
3727   case ISD::VASTART:
3728     return LowerVASTART(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
3729                         VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
3730
3731   case ISD::VAARG:
3732     return LowerVAARG(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
3733                       VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
3734
3735   case ISD::FORMAL_ARGUMENTS:
3736     return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex,
3737                                  VarArgsStackOffset, VarArgsNumGPR,
3738                                  VarArgsNumFPR, PPCSubTarget);
3739
3740   case ISD::CALL:               return LowerCALL(Op, DAG, PPCSubTarget,
3741                                                  getTargetMachine());
3742   case ISD::RET:                return LowerRET(Op, DAG, getTargetMachine());
3743   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
3744   case ISD::DYNAMIC_STACKALLOC:
3745     return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
3746
3747   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
3748   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG,
3749                                                        Op.getDebugLoc());
3750   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
3751   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
3752
3753   // Lower 64-bit shifts.
3754   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
3755   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
3756   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
3757
3758   // Vector-related lowering.
3759   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
3760   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
3761   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3762   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
3763   case ISD::MUL:                return LowerMUL(Op, DAG);
3764
3765   // Frame & Return address.
3766   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
3767   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
3768   }
3769   return SDValue();
3770 }
3771
3772 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
3773                                            SmallVectorImpl<SDValue>&Results,
3774                                            SelectionDAG &DAG) {
3775   DebugLoc dl = N->getDebugLoc();
3776   switch (N->getOpcode()) {
3777   default:
3778     assert(false && "Do not know how to custom type legalize this operation!");
3779     return;
3780   case ISD::FP_ROUND_INREG: {
3781     assert(N->getValueType(0) == MVT::ppcf128);
3782     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
3783     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
3784                              MVT::f64, N->getOperand(0),
3785                              DAG.getIntPtrConstant(0));
3786     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
3787                              MVT::f64, N->getOperand(0),
3788                              DAG.getIntPtrConstant(1));
3789
3790     // This sequence changes FPSCR to do round-to-zero, adds the two halves
3791     // of the long double, and puts FPSCR back the way it was.  We do not
3792     // actually model FPSCR.
3793     std::vector<MVT> NodeTys;
3794     SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
3795
3796     NodeTys.push_back(MVT::f64);   // Return register
3797     NodeTys.push_back(MVT::Flag);    // Returns a flag for later insns
3798     Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
3799     MFFSreg = Result.getValue(0);
3800     InFlag = Result.getValue(1);
3801
3802     NodeTys.clear();
3803     NodeTys.push_back(MVT::Flag);   // Returns a flag
3804     Ops[0] = DAG.getConstant(31, MVT::i32);
3805     Ops[1] = InFlag;
3806     Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
3807     InFlag = Result.getValue(0);
3808
3809     NodeTys.clear();
3810     NodeTys.push_back(MVT::Flag);   // Returns a flag
3811     Ops[0] = DAG.getConstant(30, MVT::i32);
3812     Ops[1] = InFlag;
3813     Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
3814     InFlag = Result.getValue(0);
3815
3816     NodeTys.clear();
3817     NodeTys.push_back(MVT::f64);    // result of add
3818     NodeTys.push_back(MVT::Flag);   // Returns a flag
3819     Ops[0] = Lo;
3820     Ops[1] = Hi;
3821     Ops[2] = InFlag;
3822     Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
3823     FPreg = Result.getValue(0);
3824     InFlag = Result.getValue(1);
3825
3826     NodeTys.clear();
3827     NodeTys.push_back(MVT::f64);
3828     Ops[0] = DAG.getConstant(1, MVT::i32);
3829     Ops[1] = MFFSreg;
3830     Ops[2] = FPreg;
3831     Ops[3] = InFlag;
3832     Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
3833     FPreg = Result.getValue(0);
3834
3835     // We know the low half is about to be thrown away, so just use something
3836     // convenient.
3837     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
3838                                 FPreg, FPreg));
3839     return;
3840   }
3841   case ISD::FP_TO_SINT:
3842     Results.push_back(LowerFP_TO_SINT(SDValue(N, 0), DAG, dl));
3843     return;
3844   }
3845 }
3846
3847
3848 //===----------------------------------------------------------------------===//
3849 //  Other Lowering Code
3850 //===----------------------------------------------------------------------===//
3851
3852 MachineBasicBlock *
3853 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
3854                                     bool is64bit, unsigned BinOpcode) const {
3855   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
3856   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3857
3858   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3859   MachineFunction *F = BB->getParent();
3860   MachineFunction::iterator It = BB;
3861   ++It;
3862
3863   unsigned dest = MI->getOperand(0).getReg();
3864   unsigned ptrA = MI->getOperand(1).getReg();
3865   unsigned ptrB = MI->getOperand(2).getReg();
3866   unsigned incr = MI->getOperand(3).getReg();
3867   DebugLoc dl = MI->getDebugLoc();
3868
3869   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
3870   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
3871   F->insert(It, loopMBB);
3872   F->insert(It, exitMBB);
3873   exitMBB->transferSuccessors(BB);
3874
3875   MachineRegisterInfo &RegInfo = F->getRegInfo();
3876   unsigned TmpReg = (!BinOpcode) ? incr :
3877     RegInfo.createVirtualRegister(
3878        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
3879                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
3880
3881   //  thisMBB:
3882   //   ...
3883   //   fallthrough --> loopMBB
3884   BB->addSuccessor(loopMBB);
3885
3886   //  loopMBB:
3887   //   l[wd]arx dest, ptr
3888   //   add r0, dest, incr
3889   //   st[wd]cx. r0, ptr
3890   //   bne- loopMBB
3891   //   fallthrough --> exitMBB
3892   BB = loopMBB;
3893   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
3894     .addReg(ptrA).addReg(ptrB);
3895   if (BinOpcode)
3896     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
3897   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
3898     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
3899   BuildMI(BB, dl, TII->get(PPC::BCC))
3900     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
3901   BB->addSuccessor(loopMBB);
3902   BB->addSuccessor(exitMBB);
3903
3904   //  exitMBB:
3905   //   ...
3906   BB = exitMBB;
3907   return BB;
3908 }
3909
3910 MachineBasicBlock *
3911 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
3912                                             MachineBasicBlock *BB,
3913                                             bool is8bit,    // operation
3914                                             unsigned BinOpcode) const {
3915   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
3916   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3917   // In 64 bit mode we have to use 64 bits for addresses, even though the
3918   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
3919   // registers without caring whether they're 32 or 64, but here we're
3920   // doing actual arithmetic on the addresses.
3921   bool is64bit = PPCSubTarget.isPPC64();
3922
3923   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3924   MachineFunction *F = BB->getParent();
3925   MachineFunction::iterator It = BB;
3926   ++It;
3927
3928   unsigned dest = MI->getOperand(0).getReg();
3929   unsigned ptrA = MI->getOperand(1).getReg();
3930   unsigned ptrB = MI->getOperand(2).getReg();
3931   unsigned incr = MI->getOperand(3).getReg();
3932   DebugLoc dl = MI->getDebugLoc();
3933
3934   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
3935   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
3936   F->insert(It, loopMBB);
3937   F->insert(It, exitMBB);
3938   exitMBB->transferSuccessors(BB);
3939
3940   MachineRegisterInfo &RegInfo = F->getRegInfo();
3941   const TargetRegisterClass *RC =
3942     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
3943               (const TargetRegisterClass *) &PPC::GPRCRegClass;
3944   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
3945   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
3946   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
3947   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
3948   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
3949   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
3950   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
3951   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
3952   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
3953   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
3954   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
3955   unsigned Ptr1Reg;
3956   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
3957
3958   //  thisMBB:
3959   //   ...
3960   //   fallthrough --> loopMBB
3961   BB->addSuccessor(loopMBB);
3962
3963   // The 4-byte load must be aligned, while a char or short may be
3964   // anywhere in the word.  Hence all this nasty bookkeeping code.
3965   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
3966   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
3967   //   xori shift, shift1, 24 [16]
3968   //   rlwinm ptr, ptr1, 0, 0, 29
3969   //   slw incr2, incr, shift
3970   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
3971   //   slw mask, mask2, shift
3972   //  loopMBB:
3973   //   lwarx tmpDest, ptr
3974   //   add tmp, tmpDest, incr2
3975   //   andc tmp2, tmpDest, mask
3976   //   and tmp3, tmp, mask
3977   //   or tmp4, tmp3, tmp2
3978   //   stwcx. tmp4, ptr
3979   //   bne- loopMBB
3980   //   fallthrough --> exitMBB
3981   //   srw dest, tmpDest, shift
3982
3983   if (ptrA!=PPC::R0) {
3984     Ptr1Reg = RegInfo.createVirtualRegister(RC);
3985     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
3986       .addReg(ptrA).addReg(ptrB);
3987   } else {
3988     Ptr1Reg = ptrB;
3989   }
3990   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
3991       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
3992   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
3993       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
3994   if (is64bit)
3995     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
3996       .addReg(Ptr1Reg).addImm(0).addImm(61);
3997   else
3998     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
3999       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
4000   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
4001       .addReg(incr).addReg(ShiftReg);
4002   if (is8bit)
4003     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
4004   else {
4005     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4006     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
4007   }
4008   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4009       .addReg(Mask2Reg).addReg(ShiftReg);
4010
4011   BB = loopMBB;
4012   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4013     .addReg(PPC::R0).addReg(PtrReg);
4014   if (BinOpcode)
4015     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
4016       .addReg(Incr2Reg).addReg(TmpDestReg);
4017   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
4018     .addReg(TmpDestReg).addReg(MaskReg);
4019   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
4020     .addReg(TmpReg).addReg(MaskReg);
4021   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
4022     .addReg(Tmp3Reg).addReg(Tmp2Reg);
4023   BuildMI(BB, dl, TII->get(PPC::STWCX))
4024     .addReg(Tmp4Reg).addReg(PPC::R0).addReg(PtrReg);
4025   BuildMI(BB, dl, TII->get(PPC::BCC))
4026     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
4027   BB->addSuccessor(loopMBB);
4028   BB->addSuccessor(exitMBB);
4029
4030   //  exitMBB:
4031   //   ...
4032   BB = exitMBB;
4033   BuildMI(BB, dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg).addReg(ShiftReg);
4034   return BB;
4035 }
4036
4037 MachineBasicBlock *
4038 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4039                                                MachineBasicBlock *BB) const {
4040   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4041
4042   // To "insert" these instructions we actually have to insert their
4043   // control-flow patterns.
4044   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4045   MachineFunction::iterator It = BB;
4046   ++It;
4047
4048   MachineFunction *F = BB->getParent();
4049
4050   if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
4051       MI->getOpcode() == PPC::SELECT_CC_I8 ||
4052       MI->getOpcode() == PPC::SELECT_CC_F4 ||
4053       MI->getOpcode() == PPC::SELECT_CC_F8 ||
4054       MI->getOpcode() == PPC::SELECT_CC_VRRC) {
4055
4056     // The incoming instruction knows the destination vreg to set, the
4057     // condition code register to branch on, the true/false values to
4058     // select between, and a branch opcode to use.
4059
4060     //  thisMBB:
4061     //  ...
4062     //   TrueVal = ...
4063     //   cmpTY ccX, r1, r2
4064     //   bCC copy1MBB
4065     //   fallthrough --> copy0MBB
4066     MachineBasicBlock *thisMBB = BB;
4067     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4068     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4069     unsigned SelectPred = MI->getOperand(4).getImm();
4070     DebugLoc dl = MI->getDebugLoc();
4071     BuildMI(BB, dl, TII->get(PPC::BCC))
4072       .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
4073     F->insert(It, copy0MBB);
4074     F->insert(It, sinkMBB);
4075     // Update machine-CFG edges by transferring all successors of the current
4076     // block to the new block which will contain the Phi node for the select.
4077     sinkMBB->transferSuccessors(BB);
4078     // Next, add the true and fallthrough blocks as its successors.
4079     BB->addSuccessor(copy0MBB);
4080     BB->addSuccessor(sinkMBB);
4081
4082     //  copy0MBB:
4083     //   %FalseValue = ...
4084     //   # fallthrough to sinkMBB
4085     BB = copy0MBB;
4086
4087     // Update machine-CFG edges
4088     BB->addSuccessor(sinkMBB);
4089
4090     //  sinkMBB:
4091     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4092     //  ...
4093     BB = sinkMBB;
4094     BuildMI(BB, dl, TII->get(PPC::PHI), MI->getOperand(0).getReg())
4095       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
4096       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4097   }
4098   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
4099     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
4100   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
4101     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
4102   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
4103     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
4104   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
4105     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
4106
4107   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
4108     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
4109   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
4110     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
4111   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
4112     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
4113   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
4114     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
4115
4116   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
4117     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
4118   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
4119     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
4120   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
4121     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
4122   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
4123     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
4124
4125   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
4126     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
4127   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
4128     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
4129   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
4130     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
4131   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
4132     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
4133
4134   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
4135     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
4136   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
4137     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
4138   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
4139     BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
4140   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
4141     BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
4142
4143   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
4144     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
4145   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
4146     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
4147   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
4148     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
4149   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
4150     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
4151
4152   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
4153     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
4154   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
4155     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
4156   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
4157     BB = EmitAtomicBinary(MI, BB, false, 0);
4158   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
4159     BB = EmitAtomicBinary(MI, BB, true, 0);
4160
4161   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
4162            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
4163     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
4164
4165     unsigned dest   = MI->getOperand(0).getReg();
4166     unsigned ptrA   = MI->getOperand(1).getReg();
4167     unsigned ptrB   = MI->getOperand(2).getReg();
4168     unsigned oldval = MI->getOperand(3).getReg();
4169     unsigned newval = MI->getOperand(4).getReg();
4170     DebugLoc dl     = MI->getDebugLoc();
4171
4172     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
4173     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
4174     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
4175     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4176     F->insert(It, loop1MBB);
4177     F->insert(It, loop2MBB);
4178     F->insert(It, midMBB);
4179     F->insert(It, exitMBB);
4180     exitMBB->transferSuccessors(BB);
4181
4182     //  thisMBB:
4183     //   ...
4184     //   fallthrough --> loopMBB
4185     BB->addSuccessor(loop1MBB);
4186
4187     // loop1MBB:
4188     //   l[wd]arx dest, ptr
4189     //   cmp[wd] dest, oldval
4190     //   bne- midMBB
4191     // loop2MBB:
4192     //   st[wd]cx. newval, ptr
4193     //   bne- loopMBB
4194     //   b exitBB
4195     // midMBB:
4196     //   st[wd]cx. dest, ptr
4197     // exitBB:
4198     BB = loop1MBB;
4199     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
4200       .addReg(ptrA).addReg(ptrB);
4201     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
4202       .addReg(oldval).addReg(dest);
4203     BuildMI(BB, dl, TII->get(PPC::BCC))
4204       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
4205     BB->addSuccessor(loop2MBB);
4206     BB->addSuccessor(midMBB);
4207
4208     BB = loop2MBB;
4209     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4210       .addReg(newval).addReg(ptrA).addReg(ptrB);
4211     BuildMI(BB, dl, TII->get(PPC::BCC))
4212       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
4213     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
4214     BB->addSuccessor(loop1MBB);
4215     BB->addSuccessor(exitMBB);
4216
4217     BB = midMBB;
4218     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4219       .addReg(dest).addReg(ptrA).addReg(ptrB);
4220     BB->addSuccessor(exitMBB);
4221
4222     //  exitMBB:
4223     //   ...
4224     BB = exitMBB;
4225   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
4226              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
4227     // We must use 64-bit registers for addresses when targeting 64-bit,
4228     // since we're actually doing arithmetic on them.  Other registers
4229     // can be 32-bit.
4230     bool is64bit = PPCSubTarget.isPPC64();
4231     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
4232
4233     unsigned dest   = MI->getOperand(0).getReg();
4234     unsigned ptrA   = MI->getOperand(1).getReg();
4235     unsigned ptrB   = MI->getOperand(2).getReg();
4236     unsigned oldval = MI->getOperand(3).getReg();
4237     unsigned newval = MI->getOperand(4).getReg();
4238     DebugLoc dl     = MI->getDebugLoc();
4239
4240     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
4241     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
4242     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
4243     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4244     F->insert(It, loop1MBB);
4245     F->insert(It, loop2MBB);
4246     F->insert(It, midMBB);
4247     F->insert(It, exitMBB);
4248     exitMBB->transferSuccessors(BB);
4249
4250     MachineRegisterInfo &RegInfo = F->getRegInfo();
4251     const TargetRegisterClass *RC =
4252       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4253                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
4254     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
4255     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
4256     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
4257     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
4258     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
4259     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
4260     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
4261     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
4262     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
4263     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
4264     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
4265     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
4266     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
4267     unsigned Ptr1Reg;
4268     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
4269     //  thisMBB:
4270     //   ...
4271     //   fallthrough --> loopMBB
4272     BB->addSuccessor(loop1MBB);
4273
4274     // The 4-byte load must be aligned, while a char or short may be
4275     // anywhere in the word.  Hence all this nasty bookkeeping code.
4276     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
4277     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
4278     //   xori shift, shift1, 24 [16]
4279     //   rlwinm ptr, ptr1, 0, 0, 29
4280     //   slw newval2, newval, shift
4281     //   slw oldval2, oldval,shift
4282     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
4283     //   slw mask, mask2, shift
4284     //   and newval3, newval2, mask
4285     //   and oldval3, oldval2, mask
4286     // loop1MBB:
4287     //   lwarx tmpDest, ptr
4288     //   and tmp, tmpDest, mask
4289     //   cmpw tmp, oldval3
4290     //   bne- midMBB
4291     // loop2MBB:
4292     //   andc tmp2, tmpDest, mask
4293     //   or tmp4, tmp2, newval3
4294     //   stwcx. tmp4, ptr
4295     //   bne- loop1MBB
4296     //   b exitBB
4297     // midMBB:
4298     //   stwcx. tmpDest, ptr
4299     // exitBB:
4300     //   srw dest, tmpDest, shift
4301     if (ptrA!=PPC::R0) {
4302       Ptr1Reg = RegInfo.createVirtualRegister(RC);
4303       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
4304         .addReg(ptrA).addReg(ptrB);
4305     } else {
4306       Ptr1Reg = ptrB;
4307     }
4308     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
4309         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
4310     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
4311         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
4312     if (is64bit)
4313       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
4314         .addReg(Ptr1Reg).addImm(0).addImm(61);
4315     else
4316       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
4317         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
4318     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
4319         .addReg(newval).addReg(ShiftReg);
4320     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
4321         .addReg(oldval).addReg(ShiftReg);
4322     if (is8bit)
4323       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
4324     else {
4325       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4326       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
4327         .addReg(Mask3Reg).addImm(65535);
4328     }
4329     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4330         .addReg(Mask2Reg).addReg(ShiftReg);
4331     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
4332         .addReg(NewVal2Reg).addReg(MaskReg);
4333     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
4334         .addReg(OldVal2Reg).addReg(MaskReg);
4335
4336     BB = loop1MBB;
4337     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4338         .addReg(PPC::R0).addReg(PtrReg);
4339     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
4340         .addReg(TmpDestReg).addReg(MaskReg);
4341     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
4342         .addReg(TmpReg).addReg(OldVal3Reg);
4343     BuildMI(BB, dl, TII->get(PPC::BCC))
4344         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
4345     BB->addSuccessor(loop2MBB);
4346     BB->addSuccessor(midMBB);
4347
4348     BB = loop2MBB;
4349     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
4350         .addReg(TmpDestReg).addReg(MaskReg);
4351     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
4352         .addReg(Tmp2Reg).addReg(NewVal3Reg);
4353     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
4354         .addReg(PPC::R0).addReg(PtrReg);
4355     BuildMI(BB, dl, TII->get(PPC::BCC))
4356       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
4357     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
4358     BB->addSuccessor(loop1MBB);
4359     BB->addSuccessor(exitMBB);
4360
4361     BB = midMBB;
4362     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
4363       .addReg(PPC::R0).addReg(PtrReg);
4364     BB->addSuccessor(exitMBB);
4365
4366     //  exitMBB:
4367     //   ...
4368     BB = exitMBB;
4369     BuildMI(BB, dl, TII->get(PPC::SRW),dest).addReg(TmpReg).addReg(ShiftReg);
4370   } else {
4371     assert(0 && "Unexpected instr type to insert");
4372   }
4373
4374   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
4375   return BB;
4376 }
4377
4378 //===----------------------------------------------------------------------===//
4379 // Target Optimization Hooks
4380 //===----------------------------------------------------------------------===//
4381
4382 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
4383                                              DAGCombinerInfo &DCI) const {
4384   TargetMachine &TM = getTargetMachine();
4385   SelectionDAG &DAG = DCI.DAG;
4386   DebugLoc dl = N->getDebugLoc();
4387   switch (N->getOpcode()) {
4388   default: break;
4389   case PPCISD::SHL:
4390     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4391       if (C->getZExtValue() == 0)   // 0 << V -> 0.
4392         return N->getOperand(0);
4393     }
4394     break;
4395   case PPCISD::SRL:
4396     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4397       if (C->getZExtValue() == 0)   // 0 >>u V -> 0.
4398         return N->getOperand(0);
4399     }
4400     break;
4401   case PPCISD::SRA:
4402     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4403       if (C->getZExtValue() == 0 ||   //  0 >>s V -> 0.
4404           C->isAllOnesValue())    // -1 >>s V -> -1.
4405         return N->getOperand(0);
4406     }
4407     break;
4408
4409   case ISD::SINT_TO_FP:
4410     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
4411       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
4412         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
4413         // We allow the src/dst to be either f32/f64, but the intermediate
4414         // type must be i64.
4415         if (N->getOperand(0).getValueType() == MVT::i64 &&
4416             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
4417           SDValue Val = N->getOperand(0).getOperand(0);
4418           if (Val.getValueType() == MVT::f32) {
4419             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
4420             DCI.AddToWorklist(Val.getNode());
4421           }
4422
4423           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
4424           DCI.AddToWorklist(Val.getNode());
4425           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
4426           DCI.AddToWorklist(Val.getNode());
4427           if (N->getValueType(0) == MVT::f32) {
4428             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
4429                               DAG.getIntPtrConstant(0));
4430             DCI.AddToWorklist(Val.getNode());
4431           }
4432           return Val;
4433         } else if (N->getOperand(0).getValueType() == MVT::i32) {
4434           // If the intermediate type is i32, we can avoid the load/store here
4435           // too.
4436         }
4437       }
4438     }
4439     break;
4440   case ISD::STORE:
4441     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
4442     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
4443         !cast<StoreSDNode>(N)->isTruncatingStore() &&
4444         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
4445         N->getOperand(1).getValueType() == MVT::i32 &&
4446         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
4447       SDValue Val = N->getOperand(1).getOperand(0);
4448       if (Val.getValueType() == MVT::f32) {
4449         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
4450         DCI.AddToWorklist(Val.getNode());
4451       }
4452       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
4453       DCI.AddToWorklist(Val.getNode());
4454
4455       Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
4456                         N->getOperand(2), N->getOperand(3));
4457       DCI.AddToWorklist(Val.getNode());
4458       return Val;
4459     }
4460
4461     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
4462     if (N->getOperand(1).getOpcode() == ISD::BSWAP &&
4463         N->getOperand(1).getNode()->hasOneUse() &&
4464         (N->getOperand(1).getValueType() == MVT::i32 ||
4465          N->getOperand(1).getValueType() == MVT::i16)) {
4466       SDValue BSwapOp = N->getOperand(1).getOperand(0);
4467       // Do an any-extend to 32-bits if this is a half-word input.
4468       if (BSwapOp.getValueType() == MVT::i16)
4469         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
4470
4471       return DAG.getNode(PPCISD::STBRX, dl, MVT::Other, N->getOperand(0),
4472                          BSwapOp, N->getOperand(2), N->getOperand(3),
4473                          DAG.getValueType(N->getOperand(1).getValueType()));
4474     }
4475     break;
4476   case ISD::BSWAP:
4477     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
4478     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
4479         N->getOperand(0).hasOneUse() &&
4480         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
4481       SDValue Load = N->getOperand(0);
4482       LoadSDNode *LD = cast<LoadSDNode>(Load);
4483       // Create the byte-swapping load.
4484       std::vector<MVT> VTs;
4485       VTs.push_back(MVT::i32);
4486       VTs.push_back(MVT::Other);
4487       SDValue MO = DAG.getMemOperand(LD->getMemOperand());
4488       SDValue Ops[] = {
4489         LD->getChain(),    // Chain
4490         LD->getBasePtr(),  // Ptr
4491         MO,                // MemOperand
4492         DAG.getValueType(N->getValueType(0)) // VT
4493       };
4494       SDValue BSLoad = DAG.getNode(PPCISD::LBRX, dl, VTs, Ops, 4);
4495
4496       // If this is an i16 load, insert the truncate.
4497       SDValue ResVal = BSLoad;
4498       if (N->getValueType(0) == MVT::i16)
4499         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
4500
4501       // First, combine the bswap away.  This makes the value produced by the
4502       // load dead.
4503       DCI.CombineTo(N, ResVal);
4504
4505       // Next, combine the load away, we give it a bogus result value but a real
4506       // chain result.  The result value is dead because the bswap is dead.
4507       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
4508
4509       // Return N so it doesn't get rechecked!
4510       return SDValue(N, 0);
4511     }
4512
4513     break;
4514   case PPCISD::VCMP: {
4515     // If a VCMPo node already exists with exactly the same operands as this
4516     // node, use its result instead of this node (VCMPo computes both a CR6 and
4517     // a normal output).
4518     //
4519     if (!N->getOperand(0).hasOneUse() &&
4520         !N->getOperand(1).hasOneUse() &&
4521         !N->getOperand(2).hasOneUse()) {
4522
4523       // Scan all of the users of the LHS, looking for VCMPo's that match.
4524       SDNode *VCMPoNode = 0;
4525
4526       SDNode *LHSN = N->getOperand(0).getNode();
4527       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
4528            UI != E; ++UI)
4529         if (UI->getOpcode() == PPCISD::VCMPo &&
4530             UI->getOperand(1) == N->getOperand(1) &&
4531             UI->getOperand(2) == N->getOperand(2) &&
4532             UI->getOperand(0) == N->getOperand(0)) {
4533           VCMPoNode = *UI;
4534           break;
4535         }
4536
4537       // If there is no VCMPo node, or if the flag value has a single use, don't
4538       // transform this.
4539       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
4540         break;
4541
4542       // Look at the (necessarily single) use of the flag value.  If it has a
4543       // chain, this transformation is more complex.  Note that multiple things
4544       // could use the value result, which we should ignore.
4545       SDNode *FlagUser = 0;
4546       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
4547            FlagUser == 0; ++UI) {
4548         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
4549         SDNode *User = *UI;
4550         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
4551           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
4552             FlagUser = User;
4553             break;
4554           }
4555         }
4556       }
4557
4558       // If the user is a MFCR instruction, we know this is safe.  Otherwise we
4559       // give up for right now.
4560       if (FlagUser->getOpcode() == PPCISD::MFCR)
4561         return SDValue(VCMPoNode, 0);
4562     }
4563     break;
4564   }
4565   case ISD::BR_CC: {
4566     // If this is a branch on an altivec predicate comparison, lower this so
4567     // that we don't have to do a MFCR: instead, branch directly on CR6.  This
4568     // lowering is done pre-legalize, because the legalizer lowers the predicate
4569     // compare down to code that is difficult to reassemble.
4570     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4571     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
4572     int CompareOpc;
4573     bool isDot;
4574
4575     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
4576         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
4577         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
4578       assert(isDot && "Can't compare against a vector result!");
4579
4580       // If this is a comparison against something other than 0/1, then we know
4581       // that the condition is never/always true.
4582       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
4583       if (Val != 0 && Val != 1) {
4584         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
4585           return N->getOperand(0);
4586         // Always !=, turn it into an unconditional branch.
4587         return DAG.getNode(ISD::BR, dl, MVT::Other,
4588                            N->getOperand(0), N->getOperand(4));
4589       }
4590
4591       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
4592
4593       // Create the PPCISD altivec 'dot' comparison node.
4594       std::vector<MVT> VTs;
4595       SDValue Ops[] = {
4596         LHS.getOperand(2),  // LHS of compare
4597         LHS.getOperand(3),  // RHS of compare
4598         DAG.getConstant(CompareOpc, MVT::i32)
4599       };
4600       VTs.push_back(LHS.getOperand(2).getValueType());
4601       VTs.push_back(MVT::Flag);
4602       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
4603
4604       // Unpack the result based on how the target uses it.
4605       PPC::Predicate CompOpc;
4606       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
4607       default:  // Can't happen, don't crash on invalid number though.
4608       case 0:   // Branch on the value of the EQ bit of CR6.
4609         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
4610         break;
4611       case 1:   // Branch on the inverted value of the EQ bit of CR6.
4612         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
4613         break;
4614       case 2:   // Branch on the value of the LT bit of CR6.
4615         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
4616         break;
4617       case 3:   // Branch on the inverted value of the LT bit of CR6.
4618         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
4619         break;
4620       }
4621
4622       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
4623                          DAG.getConstant(CompOpc, MVT::i32),
4624                          DAG.getRegister(PPC::CR6, MVT::i32),
4625                          N->getOperand(4), CompNode.getValue(1));
4626     }
4627     break;
4628   }
4629   }
4630
4631   return SDValue();
4632 }
4633
4634 //===----------------------------------------------------------------------===//
4635 // Inline Assembly Support
4636 //===----------------------------------------------------------------------===//
4637
4638 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
4639                                                        const APInt &Mask,
4640                                                        APInt &KnownZero,
4641                                                        APInt &KnownOne,
4642                                                        const SelectionDAG &DAG,
4643                                                        unsigned Depth) const {
4644   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
4645   switch (Op.getOpcode()) {
4646   default: break;
4647   case PPCISD::LBRX: {
4648     // lhbrx is known to have the top bits cleared out.
4649     if (cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::i16)
4650       KnownZero = 0xFFFF0000;
4651     break;
4652   }
4653   case ISD::INTRINSIC_WO_CHAIN: {
4654     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
4655     default: break;
4656     case Intrinsic::ppc_altivec_vcmpbfp_p:
4657     case Intrinsic::ppc_altivec_vcmpeqfp_p:
4658     case Intrinsic::ppc_altivec_vcmpequb_p:
4659     case Intrinsic::ppc_altivec_vcmpequh_p:
4660     case Intrinsic::ppc_altivec_vcmpequw_p:
4661     case Intrinsic::ppc_altivec_vcmpgefp_p:
4662     case Intrinsic::ppc_altivec_vcmpgtfp_p:
4663     case Intrinsic::ppc_altivec_vcmpgtsb_p:
4664     case Intrinsic::ppc_altivec_vcmpgtsh_p:
4665     case Intrinsic::ppc_altivec_vcmpgtsw_p:
4666     case Intrinsic::ppc_altivec_vcmpgtub_p:
4667     case Intrinsic::ppc_altivec_vcmpgtuh_p:
4668     case Intrinsic::ppc_altivec_vcmpgtuw_p:
4669       KnownZero = ~1U;  // All bits but the low one are known to be zero.
4670       break;
4671     }
4672   }
4673   }
4674 }
4675
4676
4677 /// getConstraintType - Given a constraint, return the type of
4678 /// constraint it is for this target.
4679 PPCTargetLowering::ConstraintType
4680 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
4681   if (Constraint.size() == 1) {
4682     switch (Constraint[0]) {
4683     default: break;
4684     case 'b':
4685     case 'r':
4686     case 'f':
4687     case 'v':
4688     case 'y':
4689       return C_RegisterClass;
4690     }
4691   }
4692   return TargetLowering::getConstraintType(Constraint);
4693 }
4694
4695 std::pair<unsigned, const TargetRegisterClass*>
4696 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4697                                                 MVT VT) const {
4698   if (Constraint.size() == 1) {
4699     // GCC RS6000 Constraint Letters
4700     switch (Constraint[0]) {
4701     case 'b':   // R1-R31
4702     case 'r':   // R0-R31
4703       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
4704         return std::make_pair(0U, PPC::G8RCRegisterClass);
4705       return std::make_pair(0U, PPC::GPRCRegisterClass);
4706     case 'f':
4707       if (VT == MVT::f32)
4708         return std::make_pair(0U, PPC::F4RCRegisterClass);
4709       else if (VT == MVT::f64)
4710         return std::make_pair(0U, PPC::F8RCRegisterClass);
4711       break;
4712     case 'v':
4713       return std::make_pair(0U, PPC::VRRCRegisterClass);
4714     case 'y':   // crrc
4715       return std::make_pair(0U, PPC::CRRCRegisterClass);
4716     }
4717   }
4718
4719   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4720 }
4721
4722
4723 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4724 /// vector.  If it is invalid, don't add anything to Ops. If hasMemory is true
4725 /// it means one of the asm constraint of the inline asm instruction being
4726 /// processed is 'm'.
4727 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, char Letter,
4728                                                      bool hasMemory,
4729                                                      std::vector<SDValue>&Ops,
4730                                                      SelectionDAG &DAG) const {
4731   SDValue Result(0,0);
4732   switch (Letter) {
4733   default: break;
4734   case 'I':
4735   case 'J':
4736   case 'K':
4737   case 'L':
4738   case 'M':
4739   case 'N':
4740   case 'O':
4741   case 'P': {
4742     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
4743     if (!CST) return; // Must be an immediate to match.
4744     unsigned Value = CST->getZExtValue();
4745     switch (Letter) {
4746     default: assert(0 && "Unknown constraint letter!");
4747     case 'I':  // "I" is a signed 16-bit constant.
4748       if ((short)Value == (int)Value)
4749         Result = DAG.getTargetConstant(Value, Op.getValueType());
4750       break;
4751     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
4752     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
4753       if ((short)Value == 0)
4754         Result = DAG.getTargetConstant(Value, Op.getValueType());
4755       break;
4756     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
4757       if ((Value >> 16) == 0)
4758         Result = DAG.getTargetConstant(Value, Op.getValueType());
4759       break;
4760     case 'M':  // "M" is a constant that is greater than 31.
4761       if (Value > 31)
4762         Result = DAG.getTargetConstant(Value, Op.getValueType());
4763       break;
4764     case 'N':  // "N" is a positive constant that is an exact power of two.
4765       if ((int)Value > 0 && isPowerOf2_32(Value))
4766         Result = DAG.getTargetConstant(Value, Op.getValueType());
4767       break;
4768     case 'O':  // "O" is the constant zero.
4769       if (Value == 0)
4770         Result = DAG.getTargetConstant(Value, Op.getValueType());
4771       break;
4772     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
4773       if ((short)-Value == (int)-Value)
4774         Result = DAG.getTargetConstant(Value, Op.getValueType());
4775       break;
4776     }
4777     break;
4778   }
4779   }
4780
4781   if (Result.getNode()) {
4782     Ops.push_back(Result);
4783     return;
4784   }
4785
4786   // Handle standard constraint letters.
4787   TargetLowering::LowerAsmOperandForConstraint(Op, Letter, hasMemory, Ops, DAG);
4788 }
4789
4790 // isLegalAddressingMode - Return true if the addressing mode represented
4791 // by AM is legal for this target, for a load/store of the specified type.
4792 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
4793                                               const Type *Ty) const {
4794   // FIXME: PPC does not allow r+i addressing modes for vectors!
4795
4796   // PPC allows a sign-extended 16-bit immediate field.
4797   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
4798     return false;
4799
4800   // No global is ever allowed as a base.
4801   if (AM.BaseGV)
4802     return false;
4803
4804   // PPC only support r+r,
4805   switch (AM.Scale) {
4806   case 0:  // "r+i" or just "i", depending on HasBaseReg.
4807     break;
4808   case 1:
4809     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
4810       return false;
4811     // Otherwise we have r+r or r+i.
4812     break;
4813   case 2:
4814     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
4815       return false;
4816     // Allow 2*r as r+r.
4817     break;
4818   default:
4819     // No other scales are supported.
4820     return false;
4821   }
4822
4823   return true;
4824 }
4825
4826 /// isLegalAddressImmediate - Return true if the integer value can be used
4827 /// as the offset of the target addressing mode for load / store of the
4828 /// given type.
4829 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
4830   // PPC allows a sign-extended 16-bit immediate field.
4831   return (V > -(1 << 16) && V < (1 << 16)-1);
4832 }
4833
4834 bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) const {
4835   return false;
4836 }
4837
4838 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
4839   DebugLoc dl = Op.getDebugLoc();
4840   // Depths > 0 not supported yet!
4841   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
4842     return SDValue();
4843
4844   MachineFunction &MF = DAG.getMachineFunction();
4845   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4846
4847   // Just load the return address off the stack.
4848   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
4849
4850   // Make sure the function really does not optimize away the store of the RA
4851   // to the stack.
4852   FuncInfo->setLRStoreRequired();
4853   return DAG.getLoad(getPointerTy(), dl,
4854                      DAG.getEntryNode(), RetAddrFI, NULL, 0);
4855 }
4856
4857 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
4858   DebugLoc dl = Op.getDebugLoc();
4859   // Depths > 0 not supported yet!
4860   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
4861     return SDValue();
4862
4863   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4864   bool isPPC64 = PtrVT == MVT::i64;
4865
4866   MachineFunction &MF = DAG.getMachineFunction();
4867   MachineFrameInfo *MFI = MF.getFrameInfo();
4868   bool is31 = (NoFramePointerElim || MFI->hasVarSizedObjects())
4869                   && MFI->getStackSize();
4870
4871   if (isPPC64)
4872     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, is31 ? PPC::X31 : PPC::X1,
4873       MVT::i64);
4874   else
4875     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, is31 ? PPC::R31 : PPC::R1,
4876       MVT::i32);
4877 }
4878
4879 bool
4880 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4881   // The PowerPC target isn't yet aware of offsets.
4882   return false;
4883 }