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