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