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