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