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