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