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