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