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