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