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