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