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