While reviewing the changes to Clang to add builtin support for the vsld, vsrd, and...
[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 "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
59
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61                                      const PPCSubtarget &STI)
62     : TargetLowering(TM), Subtarget(STI) {
63   // Use _setjmp/_longjmp instead of setjmp/longjmp.
64   setUseUnderscoreSetJmp(true);
65   setUseUnderscoreLongJmp(true);
66
67   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68   // arguments are at least 4/8 bytes aligned.
69   bool isPPC64 = Subtarget.isPPC64();
70   setMinStackArgumentAlignment(isPPC64 ? 8:4);
71
72   // Set up the register classes.
73   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76
77   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78   for (MVT VT : MVT::integer_valuetypes()) {
79     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
81   }
82
83   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84
85   // PowerPC has pre-inc load and store's.
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
100
101   if (Subtarget.useCRBits()) {
102     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103
104     if (isPPC64 || Subtarget.hasFPCVT()) {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107                          isPPC64 ? MVT::i64 : MVT::i32);
108       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
110                          isPPC64 ? MVT::i64 : MVT::i32);
111     } else {
112       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
114     }
115
116     // PowerPC does not support direct load / store of condition registers
117     setOperationAction(ISD::LOAD, MVT::i1, Custom);
118     setOperationAction(ISD::STORE, MVT::i1, Custom);
119
120     // FIXME: Remove this once the ANDI glue bug is fixed:
121     if (ANDIGlueBug)
122       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123
124     for (MVT VT : MVT::integer_valuetypes()) {
125       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127       setTruncStoreAction(VT, MVT::i1, Expand);
128     }
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 && Subtarget.hasFRSQRTE() &&
180         Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185         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 (Subtarget.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 (Subtarget.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 (MVT VT : MVT::vector_valuetypes()) {
404       // add/sub are legal for all supported vector VT's.
405       setOperationAction(ISD::ADD , VT, Legal);
406       setOperationAction(ISD::SUB , VT, Legal);
407
408       // Vector instructions introduced in P8
409       if (Subtarget.hasP8Altivec()) {
410         setOperationAction(ISD::CTPOP, VT, Legal);
411         setOperationAction(ISD::CTLZ, VT, Legal);
412       }
413       else {
414         setOperationAction(ISD::CTPOP, VT, Expand);
415         setOperationAction(ISD::CTLZ, VT, Expand);
416       }
417
418       // We promote all shuffles to v16i8.
419       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
421
422       // We promote all non-typed operations to v4i32.
423       setOperationAction(ISD::AND   , VT, Promote);
424       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
425       setOperationAction(ISD::OR    , VT, Promote);
426       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
427       setOperationAction(ISD::XOR   , VT, Promote);
428       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
429       setOperationAction(ISD::LOAD  , VT, Promote);
430       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
431       setOperationAction(ISD::SELECT, VT, Promote);
432       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433       setOperationAction(ISD::STORE, VT, Promote);
434       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
435
436       // No other operations are legal.
437       setOperationAction(ISD::MUL , VT, Expand);
438       setOperationAction(ISD::SDIV, VT, Expand);
439       setOperationAction(ISD::SREM, VT, Expand);
440       setOperationAction(ISD::UDIV, VT, Expand);
441       setOperationAction(ISD::UREM, VT, Expand);
442       setOperationAction(ISD::FDIV, VT, Expand);
443       setOperationAction(ISD::FREM, VT, Expand);
444       setOperationAction(ISD::FNEG, VT, Expand);
445       setOperationAction(ISD::FSQRT, VT, Expand);
446       setOperationAction(ISD::FLOG, VT, Expand);
447       setOperationAction(ISD::FLOG10, VT, Expand);
448       setOperationAction(ISD::FLOG2, VT, Expand);
449       setOperationAction(ISD::FEXP, VT, Expand);
450       setOperationAction(ISD::FEXP2, VT, Expand);
451       setOperationAction(ISD::FSIN, VT, Expand);
452       setOperationAction(ISD::FCOS, VT, Expand);
453       setOperationAction(ISD::FABS, VT, Expand);
454       setOperationAction(ISD::FPOWI, VT, Expand);
455       setOperationAction(ISD::FFLOOR, VT, Expand);
456       setOperationAction(ISD::FCEIL,  VT, Expand);
457       setOperationAction(ISD::FTRUNC, VT, Expand);
458       setOperationAction(ISD::FRINT,  VT, Expand);
459       setOperationAction(ISD::FNEARBYINT, VT, Expand);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463       setOperationAction(ISD::MULHU, VT, Expand);
464       setOperationAction(ISD::MULHS, VT, Expand);
465       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467       setOperationAction(ISD::UDIVREM, VT, Expand);
468       setOperationAction(ISD::SDIVREM, VT, Expand);
469       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470       setOperationAction(ISD::FPOW, VT, Expand);
471       setOperationAction(ISD::BSWAP, VT, Expand);
472       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473       setOperationAction(ISD::CTTZ, VT, Expand);
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475       setOperationAction(ISD::VSELECT, VT, Expand);
476       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
477
478       for (MVT InnerVT : MVT::vector_valuetypes()) {
479         setTruncStoreAction(VT, InnerVT, Expand);
480         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
483       }
484     }
485
486     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487     // with merges, splats, etc.
488     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
489
490     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
491     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
492     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
493     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
494     setOperationAction(ISD::SELECT, MVT::v4i32,
495                        Subtarget.useCRBits() ? Legal : Expand);
496     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
505
506     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
510
511     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
513
514     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
517     }
518
519     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
522
523     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
524     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
525
526     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
527     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
528     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
529     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
530
531     // Altivec does not contain unordered floating-point compare instructions
532     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
533     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
534     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
535     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536
537     if (Subtarget.hasVSX()) {
538       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
540
541       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548
549       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
551
552       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
554
555       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
560
561       // Share the Altivec comparison restrictions.
562       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
565       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
566
567       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
568       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
569
570       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
571
572       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
573
574       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
575       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
576
577       if (Subtarget.hasP8Altivec()) {
578         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
579         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
580         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
581
582         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
583       }
584       else {
585         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
586         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
587         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
588
589         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
590
591         // VSX v2i64 only supports non-arithmetic operations.
592         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
593         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
594       }
595
596       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
597       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
598       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
599       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
600
601       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
602
603       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
604       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
605       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
606       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
607
608       // Vector operation legalization checks the result type of
609       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
610       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
611       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
612       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
613       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
614
615       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
616     }
617
618     if (Subtarget.hasP8Altivec()) 
619       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
620   }
621
622   if (Subtarget.hasQPX()) {
623     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
624     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
625     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
626     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
627
628     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
629     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
630
631     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
632     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
633
634     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
635     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
636
637     if (!Subtarget.useCRBits())
638       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
639     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
640
641     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
642     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
643     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
644     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
645     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
646     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
647     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
648
649     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
650     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
651
652     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
653     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
654     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
655
656     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
657     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
658     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
659     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
660     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
661     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
662     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
663     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
664     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
665     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
666     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
667
668     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
669     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
670
671     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
672     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
673
674     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
675
676     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
677     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
678     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
679     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
680
681     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
682     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
683
684     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
685     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
686
687     if (!Subtarget.useCRBits())
688       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
689     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
690
691     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
692     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
693     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
694     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
695     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
696     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
697     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
698
699     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
700     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
701
702     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
703     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
704     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
705     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
706     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
707     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
708     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
709     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
710     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
711     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
712     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
713
714     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
715     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
716
717     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
718     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
719
720     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
721
722     setOperationAction(ISD::AND , MVT::v4i1, Legal);
723     setOperationAction(ISD::OR , MVT::v4i1, Legal);
724     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
725
726     if (!Subtarget.useCRBits())
727       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
728     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
729
730     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
731     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
732
733     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
734     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
735     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
736     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
737     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
738     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
739     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
740
741     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
742     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
743
744     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
745
746     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
747     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
748     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
749     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
750
751     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
752     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
753     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
754     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
755
756     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
757     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
758
759     // These need to set FE_INEXACT, and so cannot be vectorized here.
760     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
761     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
762
763     if (TM.Options.UnsafeFPMath) {
764       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
765       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
766
767       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
768       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
769     } else {
770       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
771       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
772
773       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
774       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
775     }
776   }
777
778   if (Subtarget.has64BitSupport())
779     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
780
781   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
782
783   if (!isPPC64) {
784     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
785     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
786   }
787
788   setBooleanContents(ZeroOrOneBooleanContent);
789
790   if (Subtarget.hasAltivec()) {
791     // Altivec instructions set fields to all zeros or all ones.
792     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
793   }
794
795   if (!isPPC64) {
796     // These libcalls are not available in 32-bit.
797     setLibcallName(RTLIB::SHL_I128, nullptr);
798     setLibcallName(RTLIB::SRL_I128, nullptr);
799     setLibcallName(RTLIB::SRA_I128, nullptr);
800   }
801
802   if (isPPC64) {
803     setStackPointerRegisterToSaveRestore(PPC::X1);
804     setExceptionPointerRegister(PPC::X3);
805     setExceptionSelectorRegister(PPC::X4);
806   } else {
807     setStackPointerRegisterToSaveRestore(PPC::R1);
808     setExceptionPointerRegister(PPC::R3);
809     setExceptionSelectorRegister(PPC::R4);
810   }
811
812   // We have target-specific dag combine patterns for the following nodes:
813   setTargetDAGCombine(ISD::SINT_TO_FP);
814   if (Subtarget.hasFPCVT())
815     setTargetDAGCombine(ISD::UINT_TO_FP);
816   setTargetDAGCombine(ISD::LOAD);
817   setTargetDAGCombine(ISD::STORE);
818   setTargetDAGCombine(ISD::BR_CC);
819   if (Subtarget.useCRBits())
820     setTargetDAGCombine(ISD::BRCOND);
821   setTargetDAGCombine(ISD::BSWAP);
822   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
823   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
824   setTargetDAGCombine(ISD::INTRINSIC_VOID);
825
826   setTargetDAGCombine(ISD::SIGN_EXTEND);
827   setTargetDAGCombine(ISD::ZERO_EXTEND);
828   setTargetDAGCombine(ISD::ANY_EXTEND);
829
830   if (Subtarget.useCRBits()) {
831     setTargetDAGCombine(ISD::TRUNCATE);
832     setTargetDAGCombine(ISD::SETCC);
833     setTargetDAGCombine(ISD::SELECT_CC);
834   }
835
836   // Use reciprocal estimates.
837   if (TM.Options.UnsafeFPMath) {
838     setTargetDAGCombine(ISD::FDIV);
839     setTargetDAGCombine(ISD::FSQRT);
840   }
841
842   // Darwin long double math library functions have $LDBL128 appended.
843   if (Subtarget.isDarwin()) {
844     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
845     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
846     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
847     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
848     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
849     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
850     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
851     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
852     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
853     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
854   }
855
856   // With 32 condition bits, we don't need to sink (and duplicate) compares
857   // aggressively in CodeGenPrep.
858   if (Subtarget.useCRBits()) {
859     setHasMultipleConditionRegisters();
860     setJumpIsExpensive();
861   }
862
863   setMinFunctionAlignment(2);
864   if (Subtarget.isDarwin())
865     setPrefFunctionAlignment(4);
866
867   switch (Subtarget.getDarwinDirective()) {
868   default: break;
869   case PPC::DIR_970:
870   case PPC::DIR_A2:
871   case PPC::DIR_E500mc:
872   case PPC::DIR_E5500:
873   case PPC::DIR_PWR4:
874   case PPC::DIR_PWR5:
875   case PPC::DIR_PWR5X:
876   case PPC::DIR_PWR6:
877   case PPC::DIR_PWR6X:
878   case PPC::DIR_PWR7:
879   case PPC::DIR_PWR8:
880     setPrefFunctionAlignment(4);
881     setPrefLoopAlignment(4);
882     break;
883   }
884
885   setInsertFencesForAtomic(true);
886
887   if (Subtarget.enableMachineScheduler())
888     setSchedulingPreference(Sched::Source);
889   else
890     setSchedulingPreference(Sched::Hybrid);
891
892   computeRegisterProperties(STI.getRegisterInfo());
893
894   // The Freescale cores do better with aggressive inlining of memcpy and
895   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
896   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
897       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
898     MaxStoresPerMemset = 32;
899     MaxStoresPerMemsetOptSize = 16;
900     MaxStoresPerMemcpy = 32;
901     MaxStoresPerMemcpyOptSize = 8;
902     MaxStoresPerMemmove = 32;
903     MaxStoresPerMemmoveOptSize = 8;
904   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
905     // The A2 also benefits from (very) aggressive inlining of memcpy and
906     // friends. The overhead of a the function call, even when warm, can be
907     // over one hundred cycles.
908     MaxStoresPerMemset = 128;
909     MaxStoresPerMemcpy = 128;
910     MaxStoresPerMemmove = 128;
911   }
912 }
913
914 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
915 /// the desired ByVal argument alignment.
916 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
917                              unsigned MaxMaxAlign) {
918   if (MaxAlign == MaxMaxAlign)
919     return;
920   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
921     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
922       MaxAlign = 32;
923     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
924       MaxAlign = 16;
925   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
926     unsigned EltAlign = 0;
927     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
928     if (EltAlign > MaxAlign)
929       MaxAlign = EltAlign;
930   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
931     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
932       unsigned EltAlign = 0;
933       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
934       if (EltAlign > MaxAlign)
935         MaxAlign = EltAlign;
936       if (MaxAlign == MaxMaxAlign)
937         break;
938     }
939   }
940 }
941
942 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
943 /// function arguments in the caller parameter area.
944 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
945   // Darwin passes everything on 4 byte boundary.
946   if (Subtarget.isDarwin())
947     return 4;
948
949   // 16byte and wider vectors are passed on 16byte boundary.
950   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
951   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
952   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
953     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
954   return Align;
955 }
956
957 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
958   switch (Opcode) {
959   default: return nullptr;
960   case PPCISD::FSEL:            return "PPCISD::FSEL";
961   case PPCISD::FCFID:           return "PPCISD::FCFID";
962   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
963   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
964   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
965   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
966   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
967   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
968   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
969   case PPCISD::FRE:             return "PPCISD::FRE";
970   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
971   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
972   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
973   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
974   case PPCISD::VPERM:           return "PPCISD::VPERM";
975   case PPCISD::CMPB:            return "PPCISD::CMPB";
976   case PPCISD::Hi:              return "PPCISD::Hi";
977   case PPCISD::Lo:              return "PPCISD::Lo";
978   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
979   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
980   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
981   case PPCISD::SRL:             return "PPCISD::SRL";
982   case PPCISD::SRA:             return "PPCISD::SRA";
983   case PPCISD::SHL:             return "PPCISD::SHL";
984   case PPCISD::CALL:            return "PPCISD::CALL";
985   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
986   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
987   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
988   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
989   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
990   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
991   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
992   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
993   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
994   case PPCISD::VCMP:            return "PPCISD::VCMP";
995   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
996   case PPCISD::LBRX:            return "PPCISD::LBRX";
997   case PPCISD::STBRX:           return "PPCISD::STBRX";
998   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
999   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1000   case PPCISD::LARX:            return "PPCISD::LARX";
1001   case PPCISD::STCX:            return "PPCISD::STCX";
1002   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1003   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1004   case PPCISD::BDZ:             return "PPCISD::BDZ";
1005   case PPCISD::MFFS:            return "PPCISD::MFFS";
1006   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1007   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1008   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1009   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1010   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1011   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1012   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1013   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1014   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1015   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1016   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1017   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1018   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1019   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1020   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1021   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1022   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1023   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1024   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1025   case PPCISD::SC:              return "PPCISD::SC";
1026   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1027   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1028   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1029   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1030   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1031   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1032   }
1033 }
1034
1035 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1036   if (!VT.isVector())
1037     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1038
1039   if (Subtarget.hasQPX())
1040     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1041
1042   return VT.changeVectorElementTypeToInteger();
1043 }
1044
1045 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1046   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1047   return true;
1048 }
1049
1050 //===----------------------------------------------------------------------===//
1051 // Node matching predicates, for use by the tblgen matching code.
1052 //===----------------------------------------------------------------------===//
1053
1054 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1055 static bool isFloatingPointZero(SDValue Op) {
1056   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1057     return CFP->getValueAPF().isZero();
1058   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1059     // Maybe this has already been legalized into the constant pool?
1060     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1061       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1062         return CFP->getValueAPF().isZero();
1063   }
1064   return false;
1065 }
1066
1067 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1068 /// true if Op is undef or if it matches the specified value.
1069 static bool isConstantOrUndef(int Op, int Val) {
1070   return Op < 0 || Op == Val;
1071 }
1072
1073 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1074 /// VPKUHUM instruction.
1075 /// The ShuffleKind distinguishes between big-endian operations with
1076 /// two different inputs (0), either-endian operations with two identical
1077 /// inputs (1), and little-endian operantion with two different inputs (2).
1078 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1079 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1080                                SelectionDAG &DAG) {
1081   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1082   if (ShuffleKind == 0) {
1083     if (IsLE)
1084       return false;
1085     for (unsigned i = 0; i != 16; ++i)
1086       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1087         return false;
1088   } else if (ShuffleKind == 2) {
1089     if (!IsLE)
1090       return false;
1091     for (unsigned i = 0; i != 16; ++i)
1092       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1093         return false;
1094   } else if (ShuffleKind == 1) {
1095     unsigned j = IsLE ? 0 : 1;
1096     for (unsigned i = 0; i != 8; ++i)
1097       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1098           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1099         return false;
1100   }
1101   return true;
1102 }
1103
1104 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1105 /// VPKUWUM instruction.
1106 /// The ShuffleKind distinguishes between big-endian operations with
1107 /// two different inputs (0), either-endian operations with two identical
1108 /// inputs (1), and little-endian operantion with two different inputs (2).
1109 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1110 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1111                                SelectionDAG &DAG) {
1112   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1113   if (ShuffleKind == 0) {
1114     if (IsLE)
1115       return false;
1116     for (unsigned i = 0; i != 16; i += 2)
1117       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1118           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1119         return false;
1120   } else if (ShuffleKind == 2) {
1121     if (!IsLE)
1122       return false;
1123     for (unsigned i = 0; i != 16; i += 2)
1124       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1125           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1126         return false;
1127   } else if (ShuffleKind == 1) {
1128     unsigned j = IsLE ? 0 : 2;
1129     for (unsigned i = 0; i != 8; i += 2)
1130       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1131           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1132           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1133           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1134         return false;
1135   }
1136   return true;
1137 }
1138
1139 /// isVMerge - Common function, used to match vmrg* shuffles.
1140 ///
1141 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1142                      unsigned LHSStart, unsigned RHSStart) {
1143   if (N->getValueType(0) != MVT::v16i8)
1144     return false;
1145   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1146          "Unsupported merge size!");
1147
1148   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1149     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1150       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1151                              LHSStart+j+i*UnitSize) ||
1152           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1153                              RHSStart+j+i*UnitSize))
1154         return false;
1155     }
1156   return true;
1157 }
1158
1159 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1160 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1161 /// The ShuffleKind distinguishes between big-endian merges with two 
1162 /// different inputs (0), either-endian merges with two identical inputs (1),
1163 /// and little-endian merges with two different inputs (2).  For the latter,
1164 /// the input operands are swapped (see PPCInstrAltivec.td).
1165 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1166                              unsigned ShuffleKind, SelectionDAG &DAG) {
1167   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1168     if (ShuffleKind == 1) // unary
1169       return isVMerge(N, UnitSize, 0, 0);
1170     else if (ShuffleKind == 2) // swapped
1171       return isVMerge(N, UnitSize, 0, 16);
1172     else
1173       return false;
1174   } else {
1175     if (ShuffleKind == 1) // unary
1176       return isVMerge(N, UnitSize, 8, 8);
1177     else if (ShuffleKind == 0) // normal
1178       return isVMerge(N, UnitSize, 8, 24);
1179     else
1180       return false;
1181   }
1182 }
1183
1184 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1185 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1186 /// The ShuffleKind distinguishes between big-endian merges with two 
1187 /// different inputs (0), either-endian merges with two identical inputs (1),
1188 /// and little-endian merges with two different inputs (2).  For the latter,
1189 /// the input operands are swapped (see PPCInstrAltivec.td).
1190 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1191                              unsigned ShuffleKind, SelectionDAG &DAG) {
1192   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1193     if (ShuffleKind == 1) // unary
1194       return isVMerge(N, UnitSize, 8, 8);
1195     else if (ShuffleKind == 2) // swapped
1196       return isVMerge(N, UnitSize, 8, 24);
1197     else
1198       return false;
1199   } else {
1200     if (ShuffleKind == 1) // unary
1201       return isVMerge(N, UnitSize, 0, 0);
1202     else if (ShuffleKind == 0) // normal
1203       return isVMerge(N, UnitSize, 0, 16);
1204     else
1205       return false;
1206   }
1207 }
1208
1209
1210 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1211 /// amount, otherwise return -1.
1212 /// The ShuffleKind distinguishes between big-endian operations with two 
1213 /// different inputs (0), either-endian operations with two identical inputs
1214 /// (1), and little-endian operations with two different inputs (2).  For the
1215 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1216 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1217                              SelectionDAG &DAG) {
1218   if (N->getValueType(0) != MVT::v16i8)
1219     return -1;
1220
1221   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1222
1223   // Find the first non-undef value in the shuffle mask.
1224   unsigned i;
1225   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1226     /*search*/;
1227
1228   if (i == 16) return -1;  // all undef.
1229
1230   // Otherwise, check to see if the rest of the elements are consecutively
1231   // numbered from this value.
1232   unsigned ShiftAmt = SVOp->getMaskElt(i);
1233   if (ShiftAmt < i) return -1;
1234
1235   ShiftAmt -= i;
1236   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1237
1238   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1239     // Check the rest of the elements to see if they are consecutive.
1240     for (++i; i != 16; ++i)
1241       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1242         return -1;
1243   } else if (ShuffleKind == 1) {
1244     // Check the rest of the elements to see if they are consecutive.
1245     for (++i; i != 16; ++i)
1246       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1247         return -1;
1248   } else
1249     return -1;
1250
1251   if (ShuffleKind == 2 && isLE)
1252     ShiftAmt = 16 - ShiftAmt;
1253
1254   return ShiftAmt;
1255 }
1256
1257 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1258 /// specifies a splat of a single element that is suitable for input to
1259 /// VSPLTB/VSPLTH/VSPLTW.
1260 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1261   assert(N->getValueType(0) == MVT::v16i8 &&
1262          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1263
1264   // This is a splat operation if each element of the permute is the same, and
1265   // if the value doesn't reference the second vector.
1266   unsigned ElementBase = N->getMaskElt(0);
1267
1268   // FIXME: Handle UNDEF elements too!
1269   if (ElementBase >= 16)
1270     return false;
1271
1272   // Check that the indices are consecutive, in the case of a multi-byte element
1273   // splatted with a v16i8 mask.
1274   for (unsigned i = 1; i != EltSize; ++i)
1275     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1276       return false;
1277
1278   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1279     if (N->getMaskElt(i) < 0) continue;
1280     for (unsigned j = 0; j != EltSize; ++j)
1281       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1282         return false;
1283   }
1284   return true;
1285 }
1286
1287 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1288 /// are -0.0.
1289 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1290   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1291
1292   APInt APVal, APUndef;
1293   unsigned BitSize;
1294   bool HasAnyUndefs;
1295
1296   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1297     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1298       return CFP->getValueAPF().isNegZero();
1299
1300   return false;
1301 }
1302
1303 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1304 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1305 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1306                                 SelectionDAG &DAG) {
1307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1308   assert(isSplatShuffleMask(SVOp, EltSize));
1309   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1310     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1311   else
1312     return SVOp->getMaskElt(0) / EltSize;
1313 }
1314
1315 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1316 /// by using a vspltis[bhw] instruction of the specified element size, return
1317 /// the constant being splatted.  The ByteSize field indicates the number of
1318 /// bytes of each element [124] -> [bhw].
1319 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1320   SDValue OpVal(nullptr, 0);
1321
1322   // If ByteSize of the splat is bigger than the element size of the
1323   // build_vector, then we have a case where we are checking for a splat where
1324   // multiple elements of the buildvector are folded together into a single
1325   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1326   unsigned EltSize = 16/N->getNumOperands();
1327   if (EltSize < ByteSize) {
1328     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1329     SDValue UniquedVals[4];
1330     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1331
1332     // See if all of the elements in the buildvector agree across.
1333     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1334       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1335       // If the element isn't a constant, bail fully out.
1336       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1337
1338
1339       if (!UniquedVals[i&(Multiple-1)].getNode())
1340         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1341       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1342         return SDValue();  // no match.
1343     }
1344
1345     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1346     // either constant or undef values that are identical for each chunk.  See
1347     // if these chunks can form into a larger vspltis*.
1348
1349     // Check to see if all of the leading entries are either 0 or -1.  If
1350     // neither, then this won't fit into the immediate field.
1351     bool LeadingZero = true;
1352     bool LeadingOnes = true;
1353     for (unsigned i = 0; i != Multiple-1; ++i) {
1354       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1355
1356       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1357       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1358     }
1359     // Finally, check the least significant entry.
1360     if (LeadingZero) {
1361       if (!UniquedVals[Multiple-1].getNode())
1362         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1363       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1364       if (Val < 16)
1365         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1366     }
1367     if (LeadingOnes) {
1368       if (!UniquedVals[Multiple-1].getNode())
1369         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1370       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1371       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1372         return DAG.getTargetConstant(Val, MVT::i32);
1373     }
1374
1375     return SDValue();
1376   }
1377
1378   // Check to see if this buildvec has a single non-undef value in its elements.
1379   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1380     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1381     if (!OpVal.getNode())
1382       OpVal = N->getOperand(i);
1383     else if (OpVal != N->getOperand(i))
1384       return SDValue();
1385   }
1386
1387   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1388
1389   unsigned ValSizeInBytes = EltSize;
1390   uint64_t Value = 0;
1391   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1392     Value = CN->getZExtValue();
1393   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1394     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1395     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1396   }
1397
1398   // If the splat value is larger than the element value, then we can never do
1399   // this splat.  The only case that we could fit the replicated bits into our
1400   // immediate field for would be zero, and we prefer to use vxor for it.
1401   if (ValSizeInBytes < ByteSize) return SDValue();
1402
1403   // If the element value is larger than the splat value, cut it in half and
1404   // check to see if the two halves are equal.  Continue doing this until we
1405   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1406   while (ValSizeInBytes > ByteSize) {
1407     ValSizeInBytes >>= 1;
1408
1409     // If the top half equals the bottom half, we're still ok.
1410     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1411          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1412       return SDValue();
1413   }
1414
1415   // Properly sign extend the value.
1416   int MaskVal = SignExtend32(Value, ByteSize * 8);
1417
1418   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1419   if (MaskVal == 0) return SDValue();
1420
1421   // Finally, if this value fits in a 5 bit sext field, return it
1422   if (SignExtend32<5>(MaskVal) == MaskVal)
1423     return DAG.getTargetConstant(MaskVal, MVT::i32);
1424   return SDValue();
1425 }
1426
1427 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1428 /// amount, otherwise return -1.
1429 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1430   EVT VT = N->getValueType(0);
1431   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1432     return -1;
1433
1434   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1435
1436   // Find the first non-undef value in the shuffle mask.
1437   unsigned i;
1438   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1439     /*search*/;
1440
1441   if (i == 4) return -1;  // all undef.
1442
1443   // Otherwise, check to see if the rest of the elements are consecutively
1444   // numbered from this value.
1445   unsigned ShiftAmt = SVOp->getMaskElt(i);
1446   if (ShiftAmt < i) return -1;
1447   ShiftAmt -= i;
1448
1449   // Check the rest of the elements to see if they are consecutive.
1450   for (++i; i != 4; ++i)
1451     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1452       return -1;
1453
1454   return ShiftAmt;
1455 }
1456
1457 //===----------------------------------------------------------------------===//
1458 //  Addressing Mode Selection
1459 //===----------------------------------------------------------------------===//
1460
1461 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1462 /// or 64-bit immediate, and if the value can be accurately represented as a
1463 /// sign extension from a 16-bit value.  If so, this returns true and the
1464 /// immediate.
1465 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1466   if (!isa<ConstantSDNode>(N))
1467     return false;
1468
1469   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1470   if (N->getValueType(0) == MVT::i32)
1471     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1472   else
1473     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1474 }
1475 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1476   return isIntS16Immediate(Op.getNode(), Imm);
1477 }
1478
1479
1480 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1481 /// can be represented as an indexed [r+r] operation.  Returns false if it
1482 /// can be more efficiently represented with [r+imm].
1483 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1484                                             SDValue &Index,
1485                                             SelectionDAG &DAG) const {
1486   short imm = 0;
1487   if (N.getOpcode() == ISD::ADD) {
1488     if (isIntS16Immediate(N.getOperand(1), imm))
1489       return false;    // r+i
1490     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1491       return false;    // r+i
1492
1493     Base = N.getOperand(0);
1494     Index = N.getOperand(1);
1495     return true;
1496   } else if (N.getOpcode() == ISD::OR) {
1497     if (isIntS16Immediate(N.getOperand(1), imm))
1498       return false;    // r+i can fold it if we can.
1499
1500     // If this is an or of disjoint bitfields, we can codegen this as an add
1501     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1502     // disjoint.
1503     APInt LHSKnownZero, LHSKnownOne;
1504     APInt RHSKnownZero, RHSKnownOne;
1505     DAG.computeKnownBits(N.getOperand(0),
1506                          LHSKnownZero, LHSKnownOne);
1507
1508     if (LHSKnownZero.getBoolValue()) {
1509       DAG.computeKnownBits(N.getOperand(1),
1510                            RHSKnownZero, RHSKnownOne);
1511       // If all of the bits are known zero on the LHS or RHS, the add won't
1512       // carry.
1513       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1514         Base = N.getOperand(0);
1515         Index = N.getOperand(1);
1516         return true;
1517       }
1518     }
1519   }
1520
1521   return false;
1522 }
1523
1524 // If we happen to be doing an i64 load or store into a stack slot that has
1525 // less than a 4-byte alignment, then the frame-index elimination may need to
1526 // use an indexed load or store instruction (because the offset may not be a
1527 // multiple of 4). The extra register needed to hold the offset comes from the
1528 // register scavenger, and it is possible that the scavenger will need to use
1529 // an emergency spill slot. As a result, we need to make sure that a spill slot
1530 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1531 // stack slot.
1532 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1533   // FIXME: This does not handle the LWA case.
1534   if (VT != MVT::i64)
1535     return;
1536
1537   // NOTE: We'll exclude negative FIs here, which come from argument
1538   // lowering, because there are no known test cases triggering this problem
1539   // using packed structures (or similar). We can remove this exclusion if
1540   // we find such a test case. The reason why this is so test-case driven is
1541   // because this entire 'fixup' is only to prevent crashes (from the
1542   // register scavenger) on not-really-valid inputs. For example, if we have:
1543   //   %a = alloca i1
1544   //   %b = bitcast i1* %a to i64*
1545   //   store i64* a, i64 b
1546   // then the store should really be marked as 'align 1', but is not. If it
1547   // were marked as 'align 1' then the indexed form would have been
1548   // instruction-selected initially, and the problem this 'fixup' is preventing
1549   // won't happen regardless.
1550   if (FrameIdx < 0)
1551     return;
1552
1553   MachineFunction &MF = DAG.getMachineFunction();
1554   MachineFrameInfo *MFI = MF.getFrameInfo();
1555
1556   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1557   if (Align >= 4)
1558     return;
1559
1560   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1561   FuncInfo->setHasNonRISpills();
1562 }
1563
1564 /// Returns true if the address N can be represented by a base register plus
1565 /// a signed 16-bit displacement [r+imm], and if it is not better
1566 /// represented as reg+reg.  If Aligned is true, only accept displacements
1567 /// suitable for STD and friends, i.e. multiples of 4.
1568 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1569                                             SDValue &Base,
1570                                             SelectionDAG &DAG,
1571                                             bool Aligned) const {
1572   // FIXME dl should come from parent load or store, not from address
1573   SDLoc dl(N);
1574   // If this can be more profitably realized as r+r, fail.
1575   if (SelectAddressRegReg(N, Disp, Base, DAG))
1576     return false;
1577
1578   if (N.getOpcode() == ISD::ADD) {
1579     short imm = 0;
1580     if (isIntS16Immediate(N.getOperand(1), imm) &&
1581         (!Aligned || (imm & 3) == 0)) {
1582       Disp = DAG.getTargetConstant(imm, N.getValueType());
1583       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1584         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1585         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1586       } else {
1587         Base = N.getOperand(0);
1588       }
1589       return true; // [r+i]
1590     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1591       // Match LOAD (ADD (X, Lo(G))).
1592       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1593              && "Cannot handle constant offsets yet!");
1594       Disp = N.getOperand(1).getOperand(0);  // The global address.
1595       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1596              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1597              Disp.getOpcode() == ISD::TargetConstantPool ||
1598              Disp.getOpcode() == ISD::TargetJumpTable);
1599       Base = N.getOperand(0);
1600       return true;  // [&g+r]
1601     }
1602   } else if (N.getOpcode() == ISD::OR) {
1603     short imm = 0;
1604     if (isIntS16Immediate(N.getOperand(1), imm) &&
1605         (!Aligned || (imm & 3) == 0)) {
1606       // If this is an or of disjoint bitfields, we can codegen this as an add
1607       // (for better address arithmetic) if the LHS and RHS of the OR are
1608       // provably disjoint.
1609       APInt LHSKnownZero, LHSKnownOne;
1610       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1611
1612       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1613         // If all of the bits are known zero on the LHS or RHS, the add won't
1614         // carry.
1615         if (FrameIndexSDNode *FI =
1616               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1617           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1618           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1619         } else {
1620           Base = N.getOperand(0);
1621         }
1622         Disp = DAG.getTargetConstant(imm, N.getValueType());
1623         return true;
1624       }
1625     }
1626   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1627     // Loading from a constant address.
1628
1629     // If this address fits entirely in a 16-bit sext immediate field, codegen
1630     // this as "d, 0"
1631     short Imm;
1632     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1633       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1634       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1635                              CN->getValueType(0));
1636       return true;
1637     }
1638
1639     // Handle 32-bit sext immediates with LIS + addr mode.
1640     if ((CN->getValueType(0) == MVT::i32 ||
1641          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1642         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1643       int Addr = (int)CN->getZExtValue();
1644
1645       // Otherwise, break this down into an LIS + disp.
1646       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1647
1648       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1649       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1650       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1651       return true;
1652     }
1653   }
1654
1655   Disp = DAG.getTargetConstant(0, getPointerTy());
1656   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1657     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1658     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1659   } else
1660     Base = N;
1661   return true;      // [r+0]
1662 }
1663
1664 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1665 /// represented as an indexed [r+r] operation.
1666 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1667                                                 SDValue &Index,
1668                                                 SelectionDAG &DAG) const {
1669   // Check to see if we can easily represent this as an [r+r] address.  This
1670   // will fail if it thinks that the address is more profitably represented as
1671   // reg+imm, e.g. where imm = 0.
1672   if (SelectAddressRegReg(N, Base, Index, DAG))
1673     return true;
1674
1675   // If the operand is an addition, always emit this as [r+r], since this is
1676   // better (for code size, and execution, as the memop does the add for free)
1677   // than emitting an explicit add.
1678   if (N.getOpcode() == ISD::ADD) {
1679     Base = N.getOperand(0);
1680     Index = N.getOperand(1);
1681     return true;
1682   }
1683
1684   // Otherwise, do it the hard way, using R0 as the base register.
1685   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1686                          N.getValueType());
1687   Index = N;
1688   return true;
1689 }
1690
1691 /// getPreIndexedAddressParts - returns true by value, base pointer and
1692 /// offset pointer and addressing mode by reference if the node's address
1693 /// can be legally represented as pre-indexed load / store address.
1694 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1695                                                   SDValue &Offset,
1696                                                   ISD::MemIndexedMode &AM,
1697                                                   SelectionDAG &DAG) const {
1698   if (DisablePPCPreinc) return false;
1699
1700   bool isLoad = true;
1701   SDValue Ptr;
1702   EVT VT;
1703   unsigned Alignment;
1704   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1705     Ptr = LD->getBasePtr();
1706     VT = LD->getMemoryVT();
1707     Alignment = LD->getAlignment();
1708   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1709     Ptr = ST->getBasePtr();
1710     VT  = ST->getMemoryVT();
1711     Alignment = ST->getAlignment();
1712     isLoad = false;
1713   } else
1714     return false;
1715
1716   // PowerPC doesn't have preinc load/store instructions for vectors (except
1717   // for QPX, which does have preinc r+r forms).
1718   if (VT.isVector()) {
1719     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1720       return false;
1721     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1722       AM = ISD::PRE_INC;
1723       return true;
1724     }
1725   }
1726
1727   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1728
1729     // Common code will reject creating a pre-inc form if the base pointer
1730     // is a frame index, or if N is a store and the base pointer is either
1731     // the same as or a predecessor of the value being stored.  Check for
1732     // those situations here, and try with swapped Base/Offset instead.
1733     bool Swap = false;
1734
1735     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1736       Swap = true;
1737     else if (!isLoad) {
1738       SDValue Val = cast<StoreSDNode>(N)->getValue();
1739       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1740         Swap = true;
1741     }
1742
1743     if (Swap)
1744       std::swap(Base, Offset);
1745
1746     AM = ISD::PRE_INC;
1747     return true;
1748   }
1749
1750   // LDU/STU can only handle immediates that are a multiple of 4.
1751   if (VT != MVT::i64) {
1752     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1753       return false;
1754   } else {
1755     // LDU/STU need an address with at least 4-byte alignment.
1756     if (Alignment < 4)
1757       return false;
1758
1759     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1760       return false;
1761   }
1762
1763   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1764     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1765     // sext i32 to i64 when addr mode is r+i.
1766     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1767         LD->getExtensionType() == ISD::SEXTLOAD &&
1768         isa<ConstantSDNode>(Offset))
1769       return false;
1770   }
1771
1772   AM = ISD::PRE_INC;
1773   return true;
1774 }
1775
1776 //===----------------------------------------------------------------------===//
1777 //  LowerOperation implementation
1778 //===----------------------------------------------------------------------===//
1779
1780 /// GetLabelAccessInfo - Return true if we should reference labels using a
1781 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1782 static bool GetLabelAccessInfo(const TargetMachine &TM,
1783                                const PPCSubtarget &Subtarget,
1784                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1785                                const GlobalValue *GV = nullptr) {
1786   HiOpFlags = PPCII::MO_HA;
1787   LoOpFlags = PPCII::MO_LO;
1788
1789   // Don't use the pic base if not in PIC relocation model.
1790   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1791
1792   if (isPIC) {
1793     HiOpFlags |= PPCII::MO_PIC_FLAG;
1794     LoOpFlags |= PPCII::MO_PIC_FLAG;
1795   }
1796
1797   // If this is a reference to a global value that requires a non-lazy-ptr, make
1798   // sure that instruction lowering adds it.
1799   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1800     HiOpFlags |= PPCII::MO_NLP_FLAG;
1801     LoOpFlags |= PPCII::MO_NLP_FLAG;
1802
1803     if (GV->hasHiddenVisibility()) {
1804       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1805       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1806     }
1807   }
1808
1809   return isPIC;
1810 }
1811
1812 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1813                              SelectionDAG &DAG) {
1814   EVT PtrVT = HiPart.getValueType();
1815   SDValue Zero = DAG.getConstant(0, PtrVT);
1816   SDLoc DL(HiPart);
1817
1818   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1819   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1820
1821   // With PIC, the first instruction is actually "GR+hi(&G)".
1822   if (isPIC)
1823     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1824                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1825
1826   // Generate non-pic code that has direct accesses to the constant pool.
1827   // The address of the global is just (hi(&g)+lo(&g)).
1828   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1829 }
1830
1831 static void setUsesTOCBasePtr(MachineFunction &MF) {
1832   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1833   FuncInfo->setUsesTOCBasePtr();
1834 }
1835
1836 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1837   setUsesTOCBasePtr(DAG.getMachineFunction());
1838 }
1839
1840 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1841                            SDValue GA) {
1842   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1843   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1844                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1845
1846   SDValue Ops[] = { GA, Reg };
1847   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1848                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1849                                  MachinePointerInfo::getGOT(), 0, false, true,
1850                                  false, 0);
1851 }
1852
1853 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1854                                              SelectionDAG &DAG) const {
1855   EVT PtrVT = Op.getValueType();
1856   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1857   const Constant *C = CP->getConstVal();
1858
1859   // 64-bit SVR4 ABI code is always position-independent.
1860   // The actual address of the GlobalValue is stored in the TOC.
1861   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1862     setUsesTOCBasePtr(DAG);
1863     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1864     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1865   }
1866
1867   unsigned MOHiFlag, MOLoFlag;
1868   bool isPIC =
1869       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1870
1871   if (isPIC && Subtarget.isSVR4ABI()) {
1872     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1873                                            PPCII::MO_PIC_FLAG);
1874     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1875   }
1876
1877   SDValue CPIHi =
1878     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1879   SDValue CPILo =
1880     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1881   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1882 }
1883
1884 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1885   EVT PtrVT = Op.getValueType();
1886   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1887
1888   // 64-bit SVR4 ABI code is always position-independent.
1889   // The actual address of the GlobalValue is stored in the TOC.
1890   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1891     setUsesTOCBasePtr(DAG);
1892     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1893     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1894   }
1895
1896   unsigned MOHiFlag, MOLoFlag;
1897   bool isPIC =
1898       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1899
1900   if (isPIC && Subtarget.isSVR4ABI()) {
1901     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1902                                         PPCII::MO_PIC_FLAG);
1903     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1904   }
1905
1906   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1907   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1908   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1909 }
1910
1911 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1912                                              SelectionDAG &DAG) const {
1913   EVT PtrVT = Op.getValueType();
1914   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1915   const BlockAddress *BA = BASDN->getBlockAddress();
1916
1917   // 64-bit SVR4 ABI code is always position-independent.
1918   // The actual BlockAddress is stored in the TOC.
1919   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1920     setUsesTOCBasePtr(DAG);
1921     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1922     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1923   }
1924
1925   unsigned MOHiFlag, MOLoFlag;
1926   bool isPIC =
1927       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1928   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1929   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1930   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1931 }
1932
1933 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1934                                               SelectionDAG &DAG) const {
1935
1936   // FIXME: TLS addresses currently use medium model code sequences,
1937   // which is the most useful form.  Eventually support for small and
1938   // large models could be added if users need it, at the cost of
1939   // additional complexity.
1940   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1941   SDLoc dl(GA);
1942   const GlobalValue *GV = GA->getGlobal();
1943   EVT PtrVT = getPointerTy();
1944   bool is64bit = Subtarget.isPPC64();
1945   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1946   PICLevel::Level picLevel = M->getPICLevel();
1947
1948   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1949
1950   if (Model == TLSModel::LocalExec) {
1951     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1952                                                PPCII::MO_TPREL_HA);
1953     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1954                                                PPCII::MO_TPREL_LO);
1955     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1956                                      is64bit ? MVT::i64 : MVT::i32);
1957     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1958     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1959   }
1960
1961   if (Model == TLSModel::InitialExec) {
1962     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1963     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1964                                                 PPCII::MO_TLS);
1965     SDValue GOTPtr;
1966     if (is64bit) {
1967       setUsesTOCBasePtr(DAG);
1968       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1969       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1970                            PtrVT, GOTReg, TGA);
1971     } else
1972       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1973     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1974                                    PtrVT, TGA, GOTPtr);
1975     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1976   }
1977
1978   if (Model == TLSModel::GeneralDynamic) {
1979     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1980     SDValue GOTPtr;
1981     if (is64bit) {
1982       setUsesTOCBasePtr(DAG);
1983       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1984       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1985                                    GOTReg, TGA);
1986     } else {
1987       if (picLevel == PICLevel::Small)
1988         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1989       else
1990         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1991     }
1992     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1993                        GOTPtr, TGA, TGA);
1994   }
1995
1996   if (Model == TLSModel::LocalDynamic) {
1997     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1998     SDValue GOTPtr;
1999     if (is64bit) {
2000       setUsesTOCBasePtr(DAG);
2001       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2002       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2003                            GOTReg, TGA);
2004     } else {
2005       if (picLevel == PICLevel::Small)
2006         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2007       else
2008         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2009     }
2010     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2011                                   PtrVT, GOTPtr, TGA, TGA);
2012     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2013                                       PtrVT, TLSAddr, TGA);
2014     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2015   }
2016
2017   llvm_unreachable("Unknown TLS model!");
2018 }
2019
2020 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2021                                               SelectionDAG &DAG) const {
2022   EVT PtrVT = Op.getValueType();
2023   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2024   SDLoc DL(GSDN);
2025   const GlobalValue *GV = GSDN->getGlobal();
2026
2027   // 64-bit SVR4 ABI code is always position-independent.
2028   // The actual address of the GlobalValue is stored in the TOC.
2029   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2030     setUsesTOCBasePtr(DAG);
2031     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2032     return getTOCEntry(DAG, DL, true, GA);
2033   }
2034
2035   unsigned MOHiFlag, MOLoFlag;
2036   bool isPIC =
2037       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2038
2039   if (isPIC && Subtarget.isSVR4ABI()) {
2040     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2041                                             GSDN->getOffset(),
2042                                             PPCII::MO_PIC_FLAG);
2043     return getTOCEntry(DAG, DL, false, GA);
2044   }
2045
2046   SDValue GAHi =
2047     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2048   SDValue GALo =
2049     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2050
2051   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2052
2053   // If the global reference is actually to a non-lazy-pointer, we have to do an
2054   // extra load to get the address of the global.
2055   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2056     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2057                       false, false, false, 0);
2058   return Ptr;
2059 }
2060
2061 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2062   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2063   SDLoc dl(Op);
2064
2065   if (Op.getValueType() == MVT::v2i64) {
2066     // When the operands themselves are v2i64 values, we need to do something
2067     // special because VSX has no underlying comparison operations for these.
2068     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2069       // Equality can be handled by casting to the legal type for Altivec
2070       // comparisons, everything else needs to be expanded.
2071       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2072         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2073                  DAG.getSetCC(dl, MVT::v4i32,
2074                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2075                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2076                    CC));
2077       }
2078
2079       return SDValue();
2080     }
2081
2082     // We handle most of these in the usual way.
2083     return Op;
2084   }
2085
2086   // If we're comparing for equality to zero, expose the fact that this is
2087   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2088   // fold the new nodes.
2089   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2090     if (C->isNullValue() && CC == ISD::SETEQ) {
2091       EVT VT = Op.getOperand(0).getValueType();
2092       SDValue Zext = Op.getOperand(0);
2093       if (VT.bitsLT(MVT::i32)) {
2094         VT = MVT::i32;
2095         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2096       }
2097       unsigned Log2b = Log2_32(VT.getSizeInBits());
2098       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2099       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2100                                 DAG.getConstant(Log2b, MVT::i32));
2101       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2102     }
2103     // Leave comparisons against 0 and -1 alone for now, since they're usually
2104     // optimized.  FIXME: revisit this when we can custom lower all setcc
2105     // optimizations.
2106     if (C->isAllOnesValue() || C->isNullValue())
2107       return SDValue();
2108   }
2109
2110   // If we have an integer seteq/setne, turn it into a compare against zero
2111   // by xor'ing the rhs with the lhs, which is faster than setting a
2112   // condition register, reading it back out, and masking the correct bit.  The
2113   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2114   // the result to other bit-twiddling opportunities.
2115   EVT LHSVT = Op.getOperand(0).getValueType();
2116   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2117     EVT VT = Op.getValueType();
2118     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2119                                 Op.getOperand(1));
2120     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2121   }
2122   return SDValue();
2123 }
2124
2125 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2126                                       const PPCSubtarget &Subtarget) const {
2127   SDNode *Node = Op.getNode();
2128   EVT VT = Node->getValueType(0);
2129   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2130   SDValue InChain = Node->getOperand(0);
2131   SDValue VAListPtr = Node->getOperand(1);
2132   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2133   SDLoc dl(Node);
2134
2135   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2136
2137   // gpr_index
2138   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2139                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2140                                     false, false, false, 0);
2141   InChain = GprIndex.getValue(1);
2142
2143   if (VT == MVT::i64) {
2144     // Check if GprIndex is even
2145     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2146                                  DAG.getConstant(1, MVT::i32));
2147     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2148                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2149     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2150                                           DAG.getConstant(1, MVT::i32));
2151     // Align GprIndex to be even if it isn't
2152     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2153                            GprIndex);
2154   }
2155
2156   // fpr index is 1 byte after gpr
2157   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2158                                DAG.getConstant(1, MVT::i32));
2159
2160   // fpr
2161   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2162                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2163                                     false, false, false, 0);
2164   InChain = FprIndex.getValue(1);
2165
2166   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2167                                        DAG.getConstant(8, MVT::i32));
2168
2169   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2170                                         DAG.getConstant(4, MVT::i32));
2171
2172   // areas
2173   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2174                                      MachinePointerInfo(), false, false,
2175                                      false, 0);
2176   InChain = OverflowArea.getValue(1);
2177
2178   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2179                                     MachinePointerInfo(), false, false,
2180                                     false, 0);
2181   InChain = RegSaveArea.getValue(1);
2182
2183   // select overflow_area if index > 8
2184   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2185                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2186
2187   // adjustment constant gpr_index * 4/8
2188   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2189                                     VT.isInteger() ? GprIndex : FprIndex,
2190                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2191                                                     MVT::i32));
2192
2193   // OurReg = RegSaveArea + RegConstant
2194   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2195                                RegConstant);
2196
2197   // Floating types are 32 bytes into RegSaveArea
2198   if (VT.isFloatingPoint())
2199     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2200                          DAG.getConstant(32, MVT::i32));
2201
2202   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2203   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2204                                    VT.isInteger() ? GprIndex : FprIndex,
2205                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2206                                                    MVT::i32));
2207
2208   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2209                               VT.isInteger() ? VAListPtr : FprPtr,
2210                               MachinePointerInfo(SV),
2211                               MVT::i8, false, false, 0);
2212
2213   // determine if we should load from reg_save_area or overflow_area
2214   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2215
2216   // increase overflow_area by 4/8 if gpr/fpr > 8
2217   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2218                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2219                                           MVT::i32));
2220
2221   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2222                              OverflowAreaPlusN);
2223
2224   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2225                               OverflowAreaPtr,
2226                               MachinePointerInfo(),
2227                               MVT::i32, false, false, 0);
2228
2229   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2230                      false, false, false, 0);
2231 }
2232
2233 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2234                                        const PPCSubtarget &Subtarget) const {
2235   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2236
2237   // We have to copy the entire va_list struct:
2238   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2239   return DAG.getMemcpy(Op.getOperand(0), Op,
2240                        Op.getOperand(1), Op.getOperand(2),
2241                        DAG.getConstant(12, MVT::i32), 8, false, true,
2242                        MachinePointerInfo(), MachinePointerInfo());
2243 }
2244
2245 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2246                                                   SelectionDAG &DAG) const {
2247   return Op.getOperand(0);
2248 }
2249
2250 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2251                                                 SelectionDAG &DAG) const {
2252   SDValue Chain = Op.getOperand(0);
2253   SDValue Trmp = Op.getOperand(1); // trampoline
2254   SDValue FPtr = Op.getOperand(2); // nested function
2255   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2256   SDLoc dl(Op);
2257
2258   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2259   bool isPPC64 = (PtrVT == MVT::i64);
2260   Type *IntPtrTy =
2261     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2262                                                              *DAG.getContext());
2263
2264   TargetLowering::ArgListTy Args;
2265   TargetLowering::ArgListEntry Entry;
2266
2267   Entry.Ty = IntPtrTy;
2268   Entry.Node = Trmp; Args.push_back(Entry);
2269
2270   // TrampSize == (isPPC64 ? 48 : 40);
2271   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2272                                isPPC64 ? MVT::i64 : MVT::i32);
2273   Args.push_back(Entry);
2274
2275   Entry.Node = FPtr; Args.push_back(Entry);
2276   Entry.Node = Nest; Args.push_back(Entry);
2277
2278   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2279   TargetLowering::CallLoweringInfo CLI(DAG);
2280   CLI.setDebugLoc(dl).setChain(Chain)
2281     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2282                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2283                std::move(Args), 0);
2284
2285   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2286   return CallResult.second;
2287 }
2288
2289 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2290                                         const PPCSubtarget &Subtarget) const {
2291   MachineFunction &MF = DAG.getMachineFunction();
2292   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2293
2294   SDLoc dl(Op);
2295
2296   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2297     // vastart just stores the address of the VarArgsFrameIndex slot into the
2298     // memory location argument.
2299     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2300     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2301     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2302     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2303                         MachinePointerInfo(SV),
2304                         false, false, 0);
2305   }
2306
2307   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2308   // We suppose the given va_list is already allocated.
2309   //
2310   // typedef struct {
2311   //  char gpr;     /* index into the array of 8 GPRs
2312   //                 * stored in the register save area
2313   //                 * gpr=0 corresponds to r3,
2314   //                 * gpr=1 to r4, etc.
2315   //                 */
2316   //  char fpr;     /* index into the array of 8 FPRs
2317   //                 * stored in the register save area
2318   //                 * fpr=0 corresponds to f1,
2319   //                 * fpr=1 to f2, etc.
2320   //                 */
2321   //  char *overflow_arg_area;
2322   //                /* location on stack that holds
2323   //                 * the next overflow argument
2324   //                 */
2325   //  char *reg_save_area;
2326   //               /* where r3:r10 and f1:f8 (if saved)
2327   //                * are stored
2328   //                */
2329   // } va_list[1];
2330
2331
2332   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2333   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2334
2335
2336   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2337
2338   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2339                                             PtrVT);
2340   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2341                                  PtrVT);
2342
2343   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2344   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2345
2346   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2347   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2348
2349   uint64_t FPROffset = 1;
2350   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2351
2352   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2353
2354   // Store first byte : number of int regs
2355   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2356                                          Op.getOperand(1),
2357                                          MachinePointerInfo(SV),
2358                                          MVT::i8, false, false, 0);
2359   uint64_t nextOffset = FPROffset;
2360   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2361                                   ConstFPROffset);
2362
2363   // Store second byte : number of float regs
2364   SDValue secondStore =
2365     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2366                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2367                       false, false, 0);
2368   nextOffset += StackOffset;
2369   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2370
2371   // Store second word : arguments given on stack
2372   SDValue thirdStore =
2373     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2374                  MachinePointerInfo(SV, nextOffset),
2375                  false, false, 0);
2376   nextOffset += FrameOffset;
2377   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2378
2379   // Store third word : arguments given in registers
2380   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2381                       MachinePointerInfo(SV, nextOffset),
2382                       false, false, 0);
2383
2384 }
2385
2386 #include "PPCGenCallingConv.inc"
2387
2388 // Function whose sole purpose is to kill compiler warnings 
2389 // stemming from unused functions included from PPCGenCallingConv.inc.
2390 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2391   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2392 }
2393
2394 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2395                                       CCValAssign::LocInfo &LocInfo,
2396                                       ISD::ArgFlagsTy &ArgFlags,
2397                                       CCState &State) {
2398   return true;
2399 }
2400
2401 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2402                                              MVT &LocVT,
2403                                              CCValAssign::LocInfo &LocInfo,
2404                                              ISD::ArgFlagsTy &ArgFlags,
2405                                              CCState &State) {
2406   static const MCPhysReg ArgRegs[] = {
2407     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2408     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2409   };
2410   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2411
2412   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2413
2414   // Skip one register if the first unallocated register has an even register
2415   // number and there are still argument registers available which have not been
2416   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2417   // need to skip a register if RegNum is odd.
2418   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2419     State.AllocateReg(ArgRegs[RegNum]);
2420   }
2421
2422   // Always return false here, as this function only makes sure that the first
2423   // unallocated register has an odd register number and does not actually
2424   // allocate a register for the current argument.
2425   return false;
2426 }
2427
2428 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2429                                                MVT &LocVT,
2430                                                CCValAssign::LocInfo &LocInfo,
2431                                                ISD::ArgFlagsTy &ArgFlags,
2432                                                CCState &State) {
2433   static const MCPhysReg ArgRegs[] = {
2434     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2435     PPC::F8
2436   };
2437
2438   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2439
2440   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2441
2442   // If there is only one Floating-point register left we need to put both f64
2443   // values of a split ppc_fp128 value on the stack.
2444   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2445     State.AllocateReg(ArgRegs[RegNum]);
2446   }
2447
2448   // Always return false here, as this function only makes sure that the two f64
2449   // values a ppc_fp128 value is split into are both passed in registers or both
2450   // passed on the stack and does not actually allocate a register for the
2451   // current argument.
2452   return false;
2453 }
2454
2455 /// FPR - The set of FP registers that should be allocated for arguments,
2456 /// on Darwin.
2457 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2458                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2459                                 PPC::F11, PPC::F12, PPC::F13};
2460
2461 /// QFPR - The set of QPX registers that should be allocated for arguments.
2462 static const MCPhysReg QFPR[] = {
2463     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2464     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2465
2466 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2467 /// the stack.
2468 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2469                                        unsigned PtrByteSize) {
2470   unsigned ArgSize = ArgVT.getStoreSize();
2471   if (Flags.isByVal())
2472     ArgSize = Flags.getByValSize();
2473
2474   // Round up to multiples of the pointer size, except for array members,
2475   // which are always packed.
2476   if (!Flags.isInConsecutiveRegs())
2477     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2478
2479   return ArgSize;
2480 }
2481
2482 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2483 /// on the stack.
2484 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2485                                             ISD::ArgFlagsTy Flags,
2486                                             unsigned PtrByteSize) {
2487   unsigned Align = PtrByteSize;
2488
2489   // Altivec parameters are padded to a 16 byte boundary.
2490   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2491       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2492       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2493     Align = 16;
2494   // QPX vector types stored in double-precision are padded to a 32 byte
2495   // boundary.
2496   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2497     Align = 32;
2498
2499   // ByVal parameters are aligned as requested.
2500   if (Flags.isByVal()) {
2501     unsigned BVAlign = Flags.getByValAlign();
2502     if (BVAlign > PtrByteSize) {
2503       if (BVAlign % PtrByteSize != 0)
2504           llvm_unreachable(
2505             "ByVal alignment is not a multiple of the pointer size");
2506
2507       Align = BVAlign;
2508     }
2509   }
2510
2511   // Array members are always packed to their original alignment.
2512   if (Flags.isInConsecutiveRegs()) {
2513     // If the array member was split into multiple registers, the first
2514     // needs to be aligned to the size of the full type.  (Except for
2515     // ppcf128, which is only aligned as its f64 components.)
2516     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2517       Align = OrigVT.getStoreSize();
2518     else
2519       Align = ArgVT.getStoreSize();
2520   }
2521
2522   return Align;
2523 }
2524
2525 /// CalculateStackSlotUsed - Return whether this argument will use its
2526 /// stack slot (instead of being passed in registers).  ArgOffset,
2527 /// AvailableFPRs, and AvailableVRs must hold the current argument
2528 /// position, and will be updated to account for this argument.
2529 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2530                                    ISD::ArgFlagsTy Flags,
2531                                    unsigned PtrByteSize,
2532                                    unsigned LinkageSize,
2533                                    unsigned ParamAreaSize,
2534                                    unsigned &ArgOffset,
2535                                    unsigned &AvailableFPRs,
2536                                    unsigned &AvailableVRs, bool HasQPX) {
2537   bool UseMemory = false;
2538
2539   // Respect alignment of argument on the stack.
2540   unsigned Align =
2541     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2542   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2543   // If there's no space left in the argument save area, we must
2544   // use memory (this check also catches zero-sized arguments).
2545   if (ArgOffset >= LinkageSize + ParamAreaSize)
2546     UseMemory = true;
2547
2548   // Allocate argument on the stack.
2549   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2550   if (Flags.isInConsecutiveRegsLast())
2551     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2552   // If we overran the argument save area, we must use memory
2553   // (this check catches arguments passed partially in memory)
2554   if (ArgOffset > LinkageSize + ParamAreaSize)
2555     UseMemory = true;
2556
2557   // However, if the argument is actually passed in an FPR or a VR,
2558   // we don't use memory after all.
2559   if (!Flags.isByVal()) {
2560     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2561         // QPX registers overlap with the scalar FP registers.
2562         (HasQPX && (ArgVT == MVT::v4f32 ||
2563                     ArgVT == MVT::v4f64 ||
2564                     ArgVT == MVT::v4i1)))
2565       if (AvailableFPRs > 0) {
2566         --AvailableFPRs;
2567         return false;
2568       }
2569     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2570         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2571         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2572       if (AvailableVRs > 0) {
2573         --AvailableVRs;
2574         return false;
2575       }
2576   }
2577
2578   return UseMemory;
2579 }
2580
2581 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2582 /// ensure minimum alignment required for target.
2583 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2584                                      unsigned NumBytes) {
2585   unsigned TargetAlign = Lowering->getStackAlignment();
2586   unsigned AlignMask = TargetAlign - 1;
2587   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2588   return NumBytes;
2589 }
2590
2591 SDValue
2592 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2593                                         CallingConv::ID CallConv, bool isVarArg,
2594                                         const SmallVectorImpl<ISD::InputArg>
2595                                           &Ins,
2596                                         SDLoc dl, SelectionDAG &DAG,
2597                                         SmallVectorImpl<SDValue> &InVals)
2598                                           const {
2599   if (Subtarget.isSVR4ABI()) {
2600     if (Subtarget.isPPC64())
2601       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2602                                          dl, DAG, InVals);
2603     else
2604       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2605                                          dl, DAG, InVals);
2606   } else {
2607     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2608                                        dl, DAG, InVals);
2609   }
2610 }
2611
2612 SDValue
2613 PPCTargetLowering::LowerFormalArguments_32SVR4(
2614                                       SDValue Chain,
2615                                       CallingConv::ID CallConv, bool isVarArg,
2616                                       const SmallVectorImpl<ISD::InputArg>
2617                                         &Ins,
2618                                       SDLoc dl, SelectionDAG &DAG,
2619                                       SmallVectorImpl<SDValue> &InVals) const {
2620
2621   // 32-bit SVR4 ABI Stack Frame Layout:
2622   //              +-----------------------------------+
2623   //        +-->  |            Back chain             |
2624   //        |     +-----------------------------------+
2625   //        |     | Floating-point register save area |
2626   //        |     +-----------------------------------+
2627   //        |     |    General register save area     |
2628   //        |     +-----------------------------------+
2629   //        |     |          CR save word             |
2630   //        |     +-----------------------------------+
2631   //        |     |         VRSAVE save word          |
2632   //        |     +-----------------------------------+
2633   //        |     |         Alignment padding         |
2634   //        |     +-----------------------------------+
2635   //        |     |     Vector register save area     |
2636   //        |     +-----------------------------------+
2637   //        |     |       Local variable space        |
2638   //        |     +-----------------------------------+
2639   //        |     |        Parameter list area        |
2640   //        |     +-----------------------------------+
2641   //        |     |           LR save word            |
2642   //        |     +-----------------------------------+
2643   // SP-->  +---  |            Back chain             |
2644   //              +-----------------------------------+
2645   //
2646   // Specifications:
2647   //   System V Application Binary Interface PowerPC Processor Supplement
2648   //   AltiVec Technology Programming Interface Manual
2649
2650   MachineFunction &MF = DAG.getMachineFunction();
2651   MachineFrameInfo *MFI = MF.getFrameInfo();
2652   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2653
2654   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2655   // Potential tail calls could cause overwriting of argument stack slots.
2656   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2657                        (CallConv == CallingConv::Fast));
2658   unsigned PtrByteSize = 4;
2659
2660   // Assign locations to all of the incoming arguments.
2661   SmallVector<CCValAssign, 16> ArgLocs;
2662   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2663                  *DAG.getContext());
2664
2665   // Reserve space for the linkage area on the stack.
2666   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2667   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2668
2669   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2670
2671   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2672     CCValAssign &VA = ArgLocs[i];
2673
2674     // Arguments stored in registers.
2675     if (VA.isRegLoc()) {
2676       const TargetRegisterClass *RC;
2677       EVT ValVT = VA.getValVT();
2678
2679       switch (ValVT.getSimpleVT().SimpleTy) {
2680         default:
2681           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2682         case MVT::i1:
2683         case MVT::i32:
2684           RC = &PPC::GPRCRegClass;
2685           break;
2686         case MVT::f32:
2687           RC = &PPC::F4RCRegClass;
2688           break;
2689         case MVT::f64:
2690           if (Subtarget.hasVSX())
2691             RC = &PPC::VSFRCRegClass;
2692           else
2693             RC = &PPC::F8RCRegClass;
2694           break;
2695         case MVT::v16i8:
2696         case MVT::v8i16:
2697         case MVT::v4i32:
2698           RC = &PPC::VRRCRegClass;
2699           break;
2700         case MVT::v4f32:
2701           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2702           break;
2703         case MVT::v2f64:
2704         case MVT::v2i64:
2705           RC = &PPC::VSHRCRegClass;
2706           break;
2707         case MVT::v4f64:
2708           RC = &PPC::QFRCRegClass;
2709           break;
2710         case MVT::v4i1:
2711           RC = &PPC::QBRCRegClass;
2712           break;
2713       }
2714
2715       // Transform the arguments stored in physical registers into virtual ones.
2716       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2717       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2718                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2719
2720       if (ValVT == MVT::i1)
2721         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2722
2723       InVals.push_back(ArgValue);
2724     } else {
2725       // Argument stored in memory.
2726       assert(VA.isMemLoc());
2727
2728       unsigned ArgSize = VA.getLocVT().getStoreSize();
2729       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2730                                       isImmutable);
2731
2732       // Create load nodes to retrieve arguments from the stack.
2733       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2734       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2735                                    MachinePointerInfo(),
2736                                    false, false, false, 0));
2737     }
2738   }
2739
2740   // Assign locations to all of the incoming aggregate by value arguments.
2741   // Aggregates passed by value are stored in the local variable space of the
2742   // caller's stack frame, right above the parameter list area.
2743   SmallVector<CCValAssign, 16> ByValArgLocs;
2744   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2745                       ByValArgLocs, *DAG.getContext());
2746
2747   // Reserve stack space for the allocations in CCInfo.
2748   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2749
2750   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2751
2752   // Area that is at least reserved in the caller of this function.
2753   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2754   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2755
2756   // Set the size that is at least reserved in caller of this function.  Tail
2757   // call optimized function's reserved stack space needs to be aligned so that
2758   // taking the difference between two stack areas will result in an aligned
2759   // stack.
2760   MinReservedArea =
2761       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2762   FuncInfo->setMinReservedArea(MinReservedArea);
2763
2764   SmallVector<SDValue, 8> MemOps;
2765
2766   // If the function takes variable number of arguments, make a frame index for
2767   // the start of the first vararg value... for expansion of llvm.va_start.
2768   if (isVarArg) {
2769     static const MCPhysReg GPArgRegs[] = {
2770       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2771       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2772     };
2773     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2774
2775     static const MCPhysReg FPArgRegs[] = {
2776       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2777       PPC::F8
2778     };
2779     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2780     if (DisablePPCFloatInVariadic)
2781       NumFPArgRegs = 0;
2782
2783     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2784     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2785
2786     // Make room for NumGPArgRegs and NumFPArgRegs.
2787     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2788                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2789
2790     FuncInfo->setVarArgsStackOffset(
2791       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2792                              CCInfo.getNextStackOffset(), true));
2793
2794     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2795     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2796
2797     // The fixed integer arguments of a variadic function are stored to the
2798     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2799     // the result of va_next.
2800     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2801       // Get an existing live-in vreg, or add a new one.
2802       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2803       if (!VReg)
2804         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2805
2806       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2807       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2808                                    MachinePointerInfo(), false, false, 0);
2809       MemOps.push_back(Store);
2810       // Increment the address by four for the next argument to store
2811       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2812       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2813     }
2814
2815     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2816     // is set.
2817     // The double arguments are stored to the VarArgsFrameIndex
2818     // on the stack.
2819     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2820       // Get an existing live-in vreg, or add a new one.
2821       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2822       if (!VReg)
2823         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2824
2825       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2826       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2827                                    MachinePointerInfo(), false, false, 0);
2828       MemOps.push_back(Store);
2829       // Increment the address by eight for the next argument to store
2830       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2831                                          PtrVT);
2832       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2833     }
2834   }
2835
2836   if (!MemOps.empty())
2837     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2838
2839   return Chain;
2840 }
2841
2842 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2843 // value to MVT::i64 and then truncate to the correct register size.
2844 SDValue
2845 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2846                                      SelectionDAG &DAG, SDValue ArgVal,
2847                                      SDLoc dl) const {
2848   if (Flags.isSExt())
2849     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2850                          DAG.getValueType(ObjectVT));
2851   else if (Flags.isZExt())
2852     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2853                          DAG.getValueType(ObjectVT));
2854
2855   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2856 }
2857
2858 SDValue
2859 PPCTargetLowering::LowerFormalArguments_64SVR4(
2860                                       SDValue Chain,
2861                                       CallingConv::ID CallConv, bool isVarArg,
2862                                       const SmallVectorImpl<ISD::InputArg>
2863                                         &Ins,
2864                                       SDLoc dl, SelectionDAG &DAG,
2865                                       SmallVectorImpl<SDValue> &InVals) const {
2866   // TODO: add description of PPC stack frame format, or at least some docs.
2867   //
2868   bool isELFv2ABI = Subtarget.isELFv2ABI();
2869   bool isLittleEndian = Subtarget.isLittleEndian();
2870   MachineFunction &MF = DAG.getMachineFunction();
2871   MachineFrameInfo *MFI = MF.getFrameInfo();
2872   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2873
2874   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2875          "fastcc not supported on varargs functions");
2876
2877   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2878   // Potential tail calls could cause overwriting of argument stack slots.
2879   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2880                        (CallConv == CallingConv::Fast));
2881   unsigned PtrByteSize = 8;
2882   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2883
2884   static const MCPhysReg GPR[] = {
2885     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2886     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2887   };
2888   static const MCPhysReg VR[] = {
2889     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2890     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2891   };
2892   static const MCPhysReg VSRH[] = {
2893     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2894     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2895   };
2896
2897   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2898   const unsigned Num_FPR_Regs = 13;
2899   const unsigned Num_VR_Regs  = array_lengthof(VR);
2900   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2901
2902   // Do a first pass over the arguments to determine whether the ABI
2903   // guarantees that our caller has allocated the parameter save area
2904   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2905   // in the ELFv2 ABI, it is true if this is a vararg function or if
2906   // any parameter is located in a stack slot.
2907
2908   bool HasParameterArea = !isELFv2ABI || isVarArg;
2909   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2910   unsigned NumBytes = LinkageSize;
2911   unsigned AvailableFPRs = Num_FPR_Regs;
2912   unsigned AvailableVRs = Num_VR_Regs;
2913   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2914     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2915                                PtrByteSize, LinkageSize, ParamAreaSize,
2916                                NumBytes, AvailableFPRs, AvailableVRs,
2917                                Subtarget.hasQPX()))
2918       HasParameterArea = true;
2919
2920   // Add DAG nodes to load the arguments or copy them out of registers.  On
2921   // entry to a function on PPC, the arguments start after the linkage area,
2922   // although the first ones are often in registers.
2923
2924   unsigned ArgOffset = LinkageSize;
2925   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2926   unsigned &QFPR_idx = FPR_idx;
2927   SmallVector<SDValue, 8> MemOps;
2928   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2929   unsigned CurArgIdx = 0;
2930   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2931     SDValue ArgVal;
2932     bool needsLoad = false;
2933     EVT ObjectVT = Ins[ArgNo].VT;
2934     EVT OrigVT = Ins[ArgNo].ArgVT;
2935     unsigned ObjSize = ObjectVT.getStoreSize();
2936     unsigned ArgSize = ObjSize;
2937     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2938     if (Ins[ArgNo].isOrigArg()) {
2939       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2940       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2941     }
2942     // We re-align the argument offset for each argument, except when using the
2943     // fast calling convention, when we need to make sure we do that only when
2944     // we'll actually use a stack slot.
2945     unsigned CurArgOffset, Align;
2946     auto ComputeArgOffset = [&]() {
2947       /* Respect alignment of argument on the stack.  */
2948       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2949       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2950       CurArgOffset = ArgOffset;
2951     };
2952
2953     if (CallConv != CallingConv::Fast) {
2954       ComputeArgOffset();
2955
2956       /* Compute GPR index associated with argument offset.  */
2957       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2958       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2959     }
2960
2961     // FIXME the codegen can be much improved in some cases.
2962     // We do not have to keep everything in memory.
2963     if (Flags.isByVal()) {
2964       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2965
2966       if (CallConv == CallingConv::Fast)
2967         ComputeArgOffset();
2968
2969       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2970       ObjSize = Flags.getByValSize();
2971       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2972       // Empty aggregate parameters do not take up registers.  Examples:
2973       //   struct { } a;
2974       //   union  { } b;
2975       //   int c[0];
2976       // etc.  However, we have to provide a place-holder in InVals, so
2977       // pretend we have an 8-byte item at the current address for that
2978       // purpose.
2979       if (!ObjSize) {
2980         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2981         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2982         InVals.push_back(FIN);
2983         continue;
2984       }
2985
2986       // Create a stack object covering all stack doublewords occupied
2987       // by the argument.  If the argument is (fully or partially) on
2988       // the stack, or if the argument is fully in registers but the
2989       // caller has allocated the parameter save anyway, we can refer
2990       // directly to the caller's stack frame.  Otherwise, create a
2991       // local copy in our own frame.
2992       int FI;
2993       if (HasParameterArea ||
2994           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2995         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2996       else
2997         FI = MFI->CreateStackObject(ArgSize, Align, false);
2998       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2999
3000       // Handle aggregates smaller than 8 bytes.
3001       if (ObjSize < PtrByteSize) {
3002         // The value of the object is its address, which differs from the
3003         // address of the enclosing doubleword on big-endian systems.
3004         SDValue Arg = FIN;
3005         if (!isLittleEndian) {
3006           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3007           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3008         }
3009         InVals.push_back(Arg);
3010
3011         if (GPR_idx != Num_GPR_Regs) {
3012           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3013           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3014           SDValue Store;
3015
3016           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3017             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3018                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3019             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3020                                       MachinePointerInfo(FuncArg),
3021                                       ObjType, false, false, 0);
3022           } else {
3023             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3024             // store the whole register as-is to the parameter save area
3025             // slot.
3026             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3027                                  MachinePointerInfo(FuncArg),
3028                                  false, false, 0);
3029           }
3030
3031           MemOps.push_back(Store);
3032         }
3033         // Whether we copied from a register or not, advance the offset
3034         // into the parameter save area by a full doubleword.
3035         ArgOffset += PtrByteSize;
3036         continue;
3037       }
3038
3039       // The value of the object is its address, which is the address of
3040       // its first stack doubleword.
3041       InVals.push_back(FIN);
3042
3043       // Store whatever pieces of the object are in registers to memory.
3044       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3045         if (GPR_idx == Num_GPR_Regs)
3046           break;
3047
3048         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3049         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3050         SDValue Addr = FIN;
3051         if (j) {
3052           SDValue Off = DAG.getConstant(j, PtrVT);
3053           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3054         }
3055         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3056                                      MachinePointerInfo(FuncArg, j),
3057                                      false, false, 0);
3058         MemOps.push_back(Store);
3059         ++GPR_idx;
3060       }
3061       ArgOffset += ArgSize;
3062       continue;
3063     }
3064
3065     switch (ObjectVT.getSimpleVT().SimpleTy) {
3066     default: llvm_unreachable("Unhandled argument type!");
3067     case MVT::i1:
3068     case MVT::i32:
3069     case MVT::i64:
3070       // These can be scalar arguments or elements of an integer array type
3071       // passed directly.  Clang may use those instead of "byval" aggregate
3072       // types to avoid forcing arguments to memory unnecessarily.
3073       if (GPR_idx != Num_GPR_Regs) {
3074         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3075         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3076
3077         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3078           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3079           // value to MVT::i64 and then truncate to the correct register size.
3080           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3081       } else {
3082         if (CallConv == CallingConv::Fast)
3083           ComputeArgOffset();
3084
3085         needsLoad = true;
3086         ArgSize = PtrByteSize;
3087       }
3088       if (CallConv != CallingConv::Fast || needsLoad)
3089         ArgOffset += 8;
3090       break;
3091
3092     case MVT::f32:
3093     case MVT::f64:
3094       // These can be scalar arguments or elements of a float array type
3095       // passed directly.  The latter are used to implement ELFv2 homogenous
3096       // float aggregates.
3097       if (FPR_idx != Num_FPR_Regs) {
3098         unsigned VReg;
3099
3100         if (ObjectVT == MVT::f32)
3101           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3102         else
3103           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3104                                                 ? &PPC::VSFRCRegClass
3105                                                 : &PPC::F8RCRegClass);
3106
3107         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3108         ++FPR_idx;
3109       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3110         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3111         // once we support fp <-> gpr moves.
3112
3113         // This can only ever happen in the presence of f32 array types,
3114         // since otherwise we never run out of FPRs before running out
3115         // of GPRs.
3116         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3117         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3118
3119         if (ObjectVT == MVT::f32) {
3120           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3121             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3122                                  DAG.getConstant(32, MVT::i32));
3123           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3124         }
3125
3126         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3127       } else {
3128         if (CallConv == CallingConv::Fast)
3129           ComputeArgOffset();
3130
3131         needsLoad = true;
3132       }
3133
3134       // When passing an array of floats, the array occupies consecutive
3135       // space in the argument area; only round up to the next doubleword
3136       // at the end of the array.  Otherwise, each float takes 8 bytes.
3137       if (CallConv != CallingConv::Fast || needsLoad) {
3138         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3139         ArgOffset += ArgSize;
3140         if (Flags.isInConsecutiveRegsLast())
3141           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3142       }
3143       break;
3144     case MVT::v4f32:
3145     case MVT::v4i32:
3146     case MVT::v8i16:
3147     case MVT::v16i8:
3148     case MVT::v2f64:
3149     case MVT::v2i64:
3150       if (!Subtarget.hasQPX()) {
3151       // These can be scalar arguments or elements of a vector array type
3152       // passed directly.  The latter are used to implement ELFv2 homogenous
3153       // vector aggregates.
3154       if (VR_idx != Num_VR_Regs) {
3155         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3156                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3157                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3158         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3159         ++VR_idx;
3160       } else {
3161         if (CallConv == CallingConv::Fast)
3162           ComputeArgOffset();
3163
3164         needsLoad = true;
3165       }
3166       if (CallConv != CallingConv::Fast || needsLoad)
3167         ArgOffset += 16;
3168       break;
3169       } // not QPX
3170
3171       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3172              "Invalid QPX parameter type");
3173       /* fall through */
3174
3175     case MVT::v4f64:
3176     case MVT::v4i1:
3177       // QPX vectors are treated like their scalar floating-point subregisters
3178       // (except that they're larger).
3179       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3180       if (QFPR_idx != Num_QFPR_Regs) {
3181         const TargetRegisterClass *RC;
3182         switch (ObjectVT.getSimpleVT().SimpleTy) {
3183         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3184         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3185         default:         RC = &PPC::QBRCRegClass; break;
3186         }
3187
3188         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3189         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3190         ++QFPR_idx;
3191       } else {
3192         if (CallConv == CallingConv::Fast)
3193           ComputeArgOffset();
3194         needsLoad = true;
3195       }
3196       if (CallConv != CallingConv::Fast || needsLoad)
3197         ArgOffset += Sz;
3198       break;
3199     }
3200
3201     // We need to load the argument to a virtual register if we determined
3202     // above that we ran out of physical registers of the appropriate type.
3203     if (needsLoad) {
3204       if (ObjSize < ArgSize && !isLittleEndian)
3205         CurArgOffset += ArgSize - ObjSize;
3206       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3207       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3208       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3209                            false, false, false, 0);
3210     }
3211
3212     InVals.push_back(ArgVal);
3213   }
3214
3215   // Area that is at least reserved in the caller of this function.
3216   unsigned MinReservedArea;
3217   if (HasParameterArea)
3218     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3219   else
3220     MinReservedArea = LinkageSize;
3221
3222   // Set the size that is at least reserved in caller of this function.  Tail
3223   // call optimized functions' reserved stack space needs to be aligned so that
3224   // taking the difference between two stack areas will result in an aligned
3225   // stack.
3226   MinReservedArea =
3227       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3228   FuncInfo->setMinReservedArea(MinReservedArea);
3229
3230   // If the function takes variable number of arguments, make a frame index for
3231   // the start of the first vararg value... for expansion of llvm.va_start.
3232   if (isVarArg) {
3233     int Depth = ArgOffset;
3234
3235     FuncInfo->setVarArgsFrameIndex(
3236       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3237     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3238
3239     // If this function is vararg, store any remaining integer argument regs
3240     // to their spots on the stack so that they may be loaded by deferencing the
3241     // result of va_next.
3242     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3243          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3244       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3245       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3246       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3247                                    MachinePointerInfo(), false, false, 0);
3248       MemOps.push_back(Store);
3249       // Increment the address by four for the next argument to store
3250       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3251       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3252     }
3253   }
3254
3255   if (!MemOps.empty())
3256     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3257
3258   return Chain;
3259 }
3260
3261 SDValue
3262 PPCTargetLowering::LowerFormalArguments_Darwin(
3263                                       SDValue Chain,
3264                                       CallingConv::ID CallConv, bool isVarArg,
3265                                       const SmallVectorImpl<ISD::InputArg>
3266                                         &Ins,
3267                                       SDLoc dl, SelectionDAG &DAG,
3268                                       SmallVectorImpl<SDValue> &InVals) const {
3269   // TODO: add description of PPC stack frame format, or at least some docs.
3270   //
3271   MachineFunction &MF = DAG.getMachineFunction();
3272   MachineFrameInfo *MFI = MF.getFrameInfo();
3273   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3274
3275   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3276   bool isPPC64 = PtrVT == MVT::i64;
3277   // Potential tail calls could cause overwriting of argument stack slots.
3278   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3279                        (CallConv == CallingConv::Fast));
3280   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3281   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3282   unsigned ArgOffset = LinkageSize;
3283   // Area that is at least reserved in caller of this function.
3284   unsigned MinReservedArea = ArgOffset;
3285
3286   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3287     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3288     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3289   };
3290   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3291     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3292     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3293   };
3294   static const MCPhysReg VR[] = {
3295     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3296     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3297   };
3298
3299   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3300   const unsigned Num_FPR_Regs = 13;
3301   const unsigned Num_VR_Regs  = array_lengthof( VR);
3302
3303   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3304
3305   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3306
3307   // In 32-bit non-varargs functions, the stack space for vectors is after the
3308   // stack space for non-vectors.  We do not use this space unless we have
3309   // too many vectors to fit in registers, something that only occurs in
3310   // constructed examples:), but we have to walk the arglist to figure
3311   // that out...for the pathological case, compute VecArgOffset as the
3312   // start of the vector parameter area.  Computing VecArgOffset is the
3313   // entire point of the following loop.
3314   unsigned VecArgOffset = ArgOffset;
3315   if (!isVarArg && !isPPC64) {
3316     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3317          ++ArgNo) {
3318       EVT ObjectVT = Ins[ArgNo].VT;
3319       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3320
3321       if (Flags.isByVal()) {
3322         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3323         unsigned ObjSize = Flags.getByValSize();
3324         unsigned ArgSize =
3325                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3326         VecArgOffset += ArgSize;
3327         continue;
3328       }
3329
3330       switch(ObjectVT.getSimpleVT().SimpleTy) {
3331       default: llvm_unreachable("Unhandled argument type!");
3332       case MVT::i1:
3333       case MVT::i32:
3334       case MVT::f32:
3335         VecArgOffset += 4;
3336         break;
3337       case MVT::i64:  // PPC64
3338       case MVT::f64:
3339         // FIXME: We are guaranteed to be !isPPC64 at this point.
3340         // Does MVT::i64 apply?
3341         VecArgOffset += 8;
3342         break;
3343       case MVT::v4f32:
3344       case MVT::v4i32:
3345       case MVT::v8i16:
3346       case MVT::v16i8:
3347         // Nothing to do, we're only looking at Nonvector args here.
3348         break;
3349       }
3350     }
3351   }
3352   // We've found where the vector parameter area in memory is.  Skip the
3353   // first 12 parameters; these don't use that memory.
3354   VecArgOffset = ((VecArgOffset+15)/16)*16;
3355   VecArgOffset += 12*16;
3356
3357   // Add DAG nodes to load the arguments or copy them out of registers.  On
3358   // entry to a function on PPC, the arguments start after the linkage area,
3359   // although the first ones are often in registers.
3360
3361   SmallVector<SDValue, 8> MemOps;
3362   unsigned nAltivecParamsAtEnd = 0;
3363   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3364   unsigned CurArgIdx = 0;
3365   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3366     SDValue ArgVal;
3367     bool needsLoad = false;
3368     EVT ObjectVT = Ins[ArgNo].VT;
3369     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3370     unsigned ArgSize = ObjSize;
3371     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3372     if (Ins[ArgNo].isOrigArg()) {
3373       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3374       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3375     }
3376     unsigned CurArgOffset = ArgOffset;
3377
3378     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3379     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3380         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3381       if (isVarArg || isPPC64) {
3382         MinReservedArea = ((MinReservedArea+15)/16)*16;
3383         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3384                                                   Flags,
3385                                                   PtrByteSize);
3386       } else  nAltivecParamsAtEnd++;
3387     } else
3388       // Calculate min reserved area.
3389       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3390                                                 Flags,
3391                                                 PtrByteSize);
3392
3393     // FIXME the codegen can be much improved in some cases.
3394     // We do not have to keep everything in memory.
3395     if (Flags.isByVal()) {
3396       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3397
3398       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3399       ObjSize = Flags.getByValSize();
3400       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3401       // Objects of size 1 and 2 are right justified, everything else is
3402       // left justified.  This means the memory address is adjusted forwards.
3403       if (ObjSize==1 || ObjSize==2) {
3404         CurArgOffset = CurArgOffset + (4 - ObjSize);
3405       }
3406       // The value of the object is its address.
3407       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3408       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3409       InVals.push_back(FIN);
3410       if (ObjSize==1 || ObjSize==2) {
3411         if (GPR_idx != Num_GPR_Regs) {
3412           unsigned VReg;
3413           if (isPPC64)
3414             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3415           else
3416             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3417           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3418           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3419           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3420                                             MachinePointerInfo(FuncArg),
3421                                             ObjType, false, false, 0);
3422           MemOps.push_back(Store);
3423           ++GPR_idx;
3424         }
3425
3426         ArgOffset += PtrByteSize;
3427
3428         continue;
3429       }
3430       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3431         // Store whatever pieces of the object are in registers
3432         // to memory.  ArgOffset will be the address of the beginning
3433         // of the object.
3434         if (GPR_idx != Num_GPR_Regs) {
3435           unsigned VReg;
3436           if (isPPC64)
3437             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3438           else
3439             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3440           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3441           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3442           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3443           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3444                                        MachinePointerInfo(FuncArg, j),
3445                                        false, false, 0);
3446           MemOps.push_back(Store);
3447           ++GPR_idx;
3448           ArgOffset += PtrByteSize;
3449         } else {
3450           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3451           break;
3452         }
3453       }
3454       continue;
3455     }
3456
3457     switch (ObjectVT.getSimpleVT().SimpleTy) {
3458     default: llvm_unreachable("Unhandled argument type!");
3459     case MVT::i1:
3460     case MVT::i32:
3461       if (!isPPC64) {
3462         if (GPR_idx != Num_GPR_Regs) {
3463           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3464           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3465
3466           if (ObjectVT == MVT::i1)
3467             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3468
3469           ++GPR_idx;
3470         } else {
3471           needsLoad = true;
3472           ArgSize = PtrByteSize;
3473         }
3474         // All int arguments reserve stack space in the Darwin ABI.
3475         ArgOffset += PtrByteSize;
3476         break;
3477       }
3478       // FALLTHROUGH
3479     case MVT::i64:  // PPC64
3480       if (GPR_idx != Num_GPR_Regs) {
3481         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3482         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3483
3484         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3485           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3486           // value to MVT::i64 and then truncate to the correct register size.
3487           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3488
3489         ++GPR_idx;
3490       } else {
3491         needsLoad = true;
3492         ArgSize = PtrByteSize;
3493       }
3494       // All int arguments reserve stack space in the Darwin ABI.
3495       ArgOffset += 8;
3496       break;
3497
3498     case MVT::f32:
3499     case MVT::f64:
3500       // Every 4 bytes of argument space consumes one of the GPRs available for
3501       // argument passing.
3502       if (GPR_idx != Num_GPR_Regs) {
3503         ++GPR_idx;
3504         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3505           ++GPR_idx;
3506       }
3507       if (FPR_idx != Num_FPR_Regs) {
3508         unsigned VReg;
3509
3510         if (ObjectVT == MVT::f32)
3511           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3512         else
3513           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3514
3515         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3516         ++FPR_idx;
3517       } else {
3518         needsLoad = true;
3519       }
3520
3521       // All FP arguments reserve stack space in the Darwin ABI.
3522       ArgOffset += isPPC64 ? 8 : ObjSize;
3523       break;
3524     case MVT::v4f32:
3525     case MVT::v4i32:
3526     case MVT::v8i16:
3527     case MVT::v16i8:
3528       // Note that vector arguments in registers don't reserve stack space,
3529       // except in varargs functions.
3530       if (VR_idx != Num_VR_Regs) {
3531         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3532         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3533         if (isVarArg) {
3534           while ((ArgOffset % 16) != 0) {
3535             ArgOffset += PtrByteSize;
3536             if (GPR_idx != Num_GPR_Regs)
3537               GPR_idx++;
3538           }
3539           ArgOffset += 16;
3540           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3541         }
3542         ++VR_idx;
3543       } else {
3544         if (!isVarArg && !isPPC64) {
3545           // Vectors go after all the nonvectors.
3546           CurArgOffset = VecArgOffset;
3547           VecArgOffset += 16;
3548         } else {
3549           // Vectors are aligned.
3550           ArgOffset = ((ArgOffset+15)/16)*16;
3551           CurArgOffset = ArgOffset;
3552           ArgOffset += 16;
3553         }
3554         needsLoad = true;
3555       }
3556       break;
3557     }
3558
3559     // We need to load the argument to a virtual register if we determined above
3560     // that we ran out of physical registers of the appropriate type.
3561     if (needsLoad) {
3562       int FI = MFI->CreateFixedObject(ObjSize,
3563                                       CurArgOffset + (ArgSize - ObjSize),
3564                                       isImmutable);
3565       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3566       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3567                            false, false, false, 0);
3568     }
3569
3570     InVals.push_back(ArgVal);
3571   }
3572
3573   // Allow for Altivec parameters at the end, if needed.
3574   if (nAltivecParamsAtEnd) {
3575     MinReservedArea = ((MinReservedArea+15)/16)*16;
3576     MinReservedArea += 16*nAltivecParamsAtEnd;
3577   }
3578
3579   // Area that is at least reserved in the caller of this function.
3580   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3581
3582   // Set the size that is at least reserved in caller of this function.  Tail
3583   // call optimized functions' reserved stack space needs to be aligned so that
3584   // taking the difference between two stack areas will result in an aligned
3585   // stack.
3586   MinReservedArea =
3587       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3588   FuncInfo->setMinReservedArea(MinReservedArea);
3589
3590   // If the function takes variable number of arguments, make a frame index for
3591   // the start of the first vararg value... for expansion of llvm.va_start.
3592   if (isVarArg) {
3593     int Depth = ArgOffset;
3594
3595     FuncInfo->setVarArgsFrameIndex(
3596       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3597                              Depth, true));
3598     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3599
3600     // If this function is vararg, store any remaining integer argument regs
3601     // to their spots on the stack so that they may be loaded by deferencing the
3602     // result of va_next.
3603     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3604       unsigned VReg;
3605
3606       if (isPPC64)
3607         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3608       else
3609         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3610
3611       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3612       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3613                                    MachinePointerInfo(), false, false, 0);
3614       MemOps.push_back(Store);
3615       // Increment the address by four for the next argument to store
3616       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3617       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3618     }
3619   }
3620
3621   if (!MemOps.empty())
3622     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3623
3624   return Chain;
3625 }
3626
3627 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3628 /// adjusted to accommodate the arguments for the tailcall.
3629 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3630                                    unsigned ParamSize) {
3631
3632   if (!isTailCall) return 0;
3633
3634   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3635   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3636   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3637   // Remember only if the new adjustement is bigger.
3638   if (SPDiff < FI->getTailCallSPDelta())
3639     FI->setTailCallSPDelta(SPDiff);
3640
3641   return SPDiff;
3642 }
3643
3644 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3645 /// for tail call optimization. Targets which want to do tail call
3646 /// optimization should implement this function.
3647 bool
3648 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3649                                                      CallingConv::ID CalleeCC,
3650                                                      bool isVarArg,
3651                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3652                                                      SelectionDAG& DAG) const {
3653   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3654     return false;
3655
3656   // Variable argument functions are not supported.
3657   if (isVarArg)
3658     return false;
3659
3660   MachineFunction &MF = DAG.getMachineFunction();
3661   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3662   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3663     // Functions containing by val parameters are not supported.
3664     for (unsigned i = 0; i != Ins.size(); i++) {
3665        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3666        if (Flags.isByVal()) return false;
3667     }
3668
3669     // Non-PIC/GOT tail calls are supported.
3670     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3671       return true;
3672
3673     // At the moment we can only do local tail calls (in same module, hidden
3674     // or protected) if we are generating PIC.
3675     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3676       return G->getGlobal()->hasHiddenVisibility()
3677           || G->getGlobal()->hasProtectedVisibility();
3678   }
3679
3680   return false;
3681 }
3682
3683 /// isCallCompatibleAddress - Return the immediate to use if the specified
3684 /// 32-bit value is representable in the immediate field of a BxA instruction.
3685 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3686   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3687   if (!C) return nullptr;
3688
3689   int Addr = C->getZExtValue();
3690   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3691       SignExtend32<26>(Addr) != Addr)
3692     return nullptr;  // Top 6 bits have to be sext of immediate.
3693
3694   return DAG.getConstant((int)C->getZExtValue() >> 2,
3695                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3696 }
3697
3698 namespace {
3699
3700 struct TailCallArgumentInfo {
3701   SDValue Arg;
3702   SDValue FrameIdxOp;
3703   int       FrameIdx;
3704
3705   TailCallArgumentInfo() : FrameIdx(0) {}
3706 };
3707
3708 }
3709
3710 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3711 static void
3712 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3713                                            SDValue Chain,
3714                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3715                    SmallVectorImpl<SDValue> &MemOpChains,
3716                    SDLoc dl) {
3717   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3718     SDValue Arg = TailCallArgs[i].Arg;
3719     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3720     int FI = TailCallArgs[i].FrameIdx;
3721     // Store relative to framepointer.
3722     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3723                                        MachinePointerInfo::getFixedStack(FI),
3724                                        false, false, 0));
3725   }
3726 }
3727
3728 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3729 /// the appropriate stack slot for the tail call optimized function call.
3730 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3731                                                MachineFunction &MF,
3732                                                SDValue Chain,
3733                                                SDValue OldRetAddr,
3734                                                SDValue OldFP,
3735                                                int SPDiff,
3736                                                bool isPPC64,
3737                                                bool isDarwinABI,
3738                                                SDLoc dl) {
3739   if (SPDiff) {
3740     // Calculate the new stack slot for the return address.
3741     int SlotSize = isPPC64 ? 8 : 4;
3742     const PPCFrameLowering *FL =
3743         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3744     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3745     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3746                                                           NewRetAddrLoc, true);
3747     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3748     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3749     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3750                          MachinePointerInfo::getFixedStack(NewRetAddr),
3751                          false, false, 0);
3752
3753     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3754     // slot as the FP is never overwritten.
3755     if (isDarwinABI) {
3756       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3757       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3758                                                           true);
3759       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3760       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3761                            MachinePointerInfo::getFixedStack(NewFPIdx),
3762                            false, false, 0);
3763     }
3764   }
3765   return Chain;
3766 }
3767
3768 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3769 /// the position of the argument.
3770 static void
3771 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3772                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3773                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3774   int Offset = ArgOffset + SPDiff;
3775   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3776   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3777   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3778   SDValue FIN = DAG.getFrameIndex(FI, VT);
3779   TailCallArgumentInfo Info;
3780   Info.Arg = Arg;
3781   Info.FrameIdxOp = FIN;
3782   Info.FrameIdx = FI;
3783   TailCallArguments.push_back(Info);
3784 }
3785
3786 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3787 /// stack slot. Returns the chain as result and the loaded frame pointers in
3788 /// LROpOut/FPOpout. Used when tail calling.
3789 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3790                                                         int SPDiff,
3791                                                         SDValue Chain,
3792                                                         SDValue &LROpOut,
3793                                                         SDValue &FPOpOut,
3794                                                         bool isDarwinABI,
3795                                                         SDLoc dl) const {
3796   if (SPDiff) {
3797     // Load the LR and FP stack slot for later adjusting.
3798     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3799     LROpOut = getReturnAddrFrameIndex(DAG);
3800     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3801                           false, false, false, 0);
3802     Chain = SDValue(LROpOut.getNode(), 1);
3803
3804     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3805     // slot as the FP is never overwritten.
3806     if (isDarwinABI) {
3807       FPOpOut = getFramePointerFrameIndex(DAG);
3808       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3809                             false, false, false, 0);
3810       Chain = SDValue(FPOpOut.getNode(), 1);
3811     }
3812   }
3813   return Chain;
3814 }
3815
3816 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3817 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3818 /// specified by the specific parameter attribute. The copy will be passed as
3819 /// a byval function parameter.
3820 /// Sometimes what we are copying is the end of a larger object, the part that
3821 /// does not fit in registers.
3822 static SDValue
3823 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3824                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3825                           SDLoc dl) {
3826   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3827   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3828                        false, false, MachinePointerInfo(),
3829                        MachinePointerInfo());
3830 }
3831
3832 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3833 /// tail calls.
3834 static void
3835 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3836                  SDValue Arg, SDValue PtrOff, int SPDiff,
3837                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3838                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3839                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3840                  SDLoc dl) {
3841   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3842   if (!isTailCall) {
3843     if (isVector) {
3844       SDValue StackPtr;
3845       if (isPPC64)
3846         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3847       else
3848         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3849       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3850                            DAG.getConstant(ArgOffset, PtrVT));
3851     }
3852     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3853                                        MachinePointerInfo(), false, false, 0));
3854   // Calculate and remember argument location.
3855   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3856                                   TailCallArguments);
3857 }
3858
3859 static
3860 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3861                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3862                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3863                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3864   MachineFunction &MF = DAG.getMachineFunction();
3865
3866   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3867   // might overwrite each other in case of tail call optimization.
3868   SmallVector<SDValue, 8> MemOpChains2;
3869   // Do not flag preceding copytoreg stuff together with the following stuff.
3870   InFlag = SDValue();
3871   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3872                                     MemOpChains2, dl);
3873   if (!MemOpChains2.empty())
3874     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3875
3876   // Store the return address to the appropriate stack slot.
3877   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3878                                         isPPC64, isDarwinABI, dl);
3879
3880   // Emit callseq_end just before tailcall node.
3881   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3882                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3883   InFlag = Chain.getValue(1);
3884 }
3885
3886 // Is this global address that of a function that can be called by name? (as
3887 // opposed to something that must hold a descriptor for an indirect call).
3888 static bool isFunctionGlobalAddress(SDValue Callee) {
3889   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3890     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3891         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3892       return false;
3893
3894     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3895   }
3896
3897   return false;
3898 }
3899
3900 static
3901 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3902                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3903                      bool isTailCall, bool IsPatchPoint,
3904                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3905                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3906                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3907
3908   bool isPPC64 = Subtarget.isPPC64();
3909   bool isSVR4ABI = Subtarget.isSVR4ABI();
3910   bool isELFv2ABI = Subtarget.isELFv2ABI();
3911
3912   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3913   NodeTys.push_back(MVT::Other);   // Returns a chain
3914   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3915
3916   unsigned CallOpc = PPCISD::CALL;
3917
3918   bool needIndirectCall = true;
3919   if (!isSVR4ABI || !isPPC64)
3920     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3921       // If this is an absolute destination address, use the munged value.
3922       Callee = SDValue(Dest, 0);
3923       needIndirectCall = false;
3924     }
3925
3926   if (isFunctionGlobalAddress(Callee)) {
3927     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3928     // A call to a TLS address is actually an indirect call to a
3929     // thread-specific pointer.
3930     unsigned OpFlags = 0;
3931     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3932          (Subtarget.getTargetTriple().isMacOSX() &&
3933           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3934          (G->getGlobal()->isDeclaration() ||
3935           G->getGlobal()->isWeakForLinker())) ||
3936         (Subtarget.isTargetELF() && !isPPC64 &&
3937          !G->getGlobal()->hasLocalLinkage() &&
3938          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3939       // PC-relative references to external symbols should go through $stub,
3940       // unless we're building with the leopard linker or later, which
3941       // automatically synthesizes these stubs.
3942       OpFlags = PPCII::MO_PLT_OR_STUB;
3943     }
3944
3945     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3946     // every direct call is) turn it into a TargetGlobalAddress /
3947     // TargetExternalSymbol node so that legalize doesn't hack it.
3948     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3949                                         Callee.getValueType(), 0, OpFlags);
3950     needIndirectCall = false;
3951   }
3952
3953   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3954     unsigned char OpFlags = 0;
3955
3956     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3957          (Subtarget.getTargetTriple().isMacOSX() &&
3958           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3959         (Subtarget.isTargetELF() && !isPPC64 &&
3960          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3961       // PC-relative references to external symbols should go through $stub,
3962       // unless we're building with the leopard linker or later, which
3963       // automatically synthesizes these stubs.
3964       OpFlags = PPCII::MO_PLT_OR_STUB;
3965     }
3966
3967     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3968                                          OpFlags);
3969     needIndirectCall = false;
3970   }
3971
3972   if (IsPatchPoint) {
3973     // We'll form an invalid direct call when lowering a patchpoint; the full
3974     // sequence for an indirect call is complicated, and many of the
3975     // instructions introduced might have side effects (and, thus, can't be
3976     // removed later). The call itself will be removed as soon as the
3977     // argument/return lowering is complete, so the fact that it has the wrong
3978     // kind of operands should not really matter.
3979     needIndirectCall = false;
3980   }
3981
3982   if (needIndirectCall) {
3983     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3984     // to do the call, we can't use PPCISD::CALL.
3985     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3986
3987     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3988       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3989       // entry point, but to the function descriptor (the function entry point
3990       // address is part of the function descriptor though).
3991       // The function descriptor is a three doubleword structure with the
3992       // following fields: function entry point, TOC base address and
3993       // environment pointer.
3994       // Thus for a call through a function pointer, the following actions need
3995       // to be performed:
3996       //   1. Save the TOC of the caller in the TOC save area of its stack
3997       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3998       //   2. Load the address of the function entry point from the function
3999       //      descriptor.
4000       //   3. Load the TOC of the callee from the function descriptor into r2.
4001       //   4. Load the environment pointer from the function descriptor into
4002       //      r11.
4003       //   5. Branch to the function entry point address.
4004       //   6. On return of the callee, the TOC of the caller needs to be
4005       //      restored (this is done in FinishCall()).
4006       //
4007       // The loads are scheduled at the beginning of the call sequence, and the
4008       // register copies are flagged together to ensure that no other
4009       // operations can be scheduled in between. E.g. without flagging the
4010       // copies together, a TOC access in the caller could be scheduled between
4011       // the assignment of the callee TOC and the branch to the callee, which
4012       // results in the TOC access going through the TOC of the callee instead
4013       // of going through the TOC of the caller, which leads to incorrect code.
4014
4015       // Load the address of the function entry point from the function
4016       // descriptor.
4017       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4018       if (LDChain.getValueType() == MVT::Glue)
4019         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4020
4021       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4022
4023       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4024       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4025                                         false, false, LoadsInv, 8);
4026
4027       // Load environment pointer into r11.
4028       SDValue PtrOff = DAG.getIntPtrConstant(16);
4029       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4030       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4031                                        MPI.getWithOffset(16), false, false,
4032                                        LoadsInv, 8);
4033
4034       SDValue TOCOff = DAG.getIntPtrConstant(8);
4035       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4036       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4037                                    MPI.getWithOffset(8), false, false,
4038                                    LoadsInv, 8);
4039
4040       setUsesTOCBasePtr(DAG);
4041       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4042                                         InFlag);
4043       Chain = TOCVal.getValue(0);
4044       InFlag = TOCVal.getValue(1);
4045
4046       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4047                                         InFlag);
4048
4049       Chain = EnvVal.getValue(0);
4050       InFlag = EnvVal.getValue(1);
4051
4052       MTCTROps[0] = Chain;
4053       MTCTROps[1] = LoadFuncPtr;
4054       MTCTROps[2] = InFlag;
4055     }
4056
4057     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4058                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4059     InFlag = Chain.getValue(1);
4060
4061     NodeTys.clear();
4062     NodeTys.push_back(MVT::Other);
4063     NodeTys.push_back(MVT::Glue);
4064     Ops.push_back(Chain);
4065     CallOpc = PPCISD::BCTRL;
4066     Callee.setNode(nullptr);
4067     // Add use of X11 (holding environment pointer)
4068     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4069       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4070     // Add CTR register as callee so a bctr can be emitted later.
4071     if (isTailCall)
4072       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4073   }
4074
4075   // If this is a direct call, pass the chain and the callee.
4076   if (Callee.getNode()) {
4077     Ops.push_back(Chain);
4078     Ops.push_back(Callee);
4079   }
4080   // If this is a tail call add stack pointer delta.
4081   if (isTailCall)
4082     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4083
4084   // Add argument registers to the end of the list so that they are known live
4085   // into the call.
4086   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4087     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4088                                   RegsToPass[i].second.getValueType()));
4089
4090   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4091   // into the call.
4092   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4093     setUsesTOCBasePtr(DAG);
4094     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4095   }
4096
4097   return CallOpc;
4098 }
4099
4100 static
4101 bool isLocalCall(const SDValue &Callee)
4102 {
4103   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4104     return !G->getGlobal()->isDeclaration() &&
4105            !G->getGlobal()->isWeakForLinker();
4106   return false;
4107 }
4108
4109 SDValue
4110 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4111                                    CallingConv::ID CallConv, bool isVarArg,
4112                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4113                                    SDLoc dl, SelectionDAG &DAG,
4114                                    SmallVectorImpl<SDValue> &InVals) const {
4115
4116   SmallVector<CCValAssign, 16> RVLocs;
4117   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4118                     *DAG.getContext());
4119   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4120
4121   // Copy all of the result registers out of their specified physreg.
4122   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4123     CCValAssign &VA = RVLocs[i];
4124     assert(VA.isRegLoc() && "Can only return in registers!");
4125
4126     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4127                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4128     Chain = Val.getValue(1);
4129     InFlag = Val.getValue(2);
4130
4131     switch (VA.getLocInfo()) {
4132     default: llvm_unreachable("Unknown loc info!");
4133     case CCValAssign::Full: break;
4134     case CCValAssign::AExt:
4135       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4136       break;
4137     case CCValAssign::ZExt:
4138       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4139                         DAG.getValueType(VA.getValVT()));
4140       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4141       break;
4142     case CCValAssign::SExt:
4143       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4144                         DAG.getValueType(VA.getValVT()));
4145       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4146       break;
4147     }
4148
4149     InVals.push_back(Val);
4150   }
4151
4152   return Chain;
4153 }
4154
4155 SDValue
4156 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4157                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4158                               SelectionDAG &DAG,
4159                               SmallVector<std::pair<unsigned, SDValue>, 8>
4160                                 &RegsToPass,
4161                               SDValue InFlag, SDValue Chain,
4162                               SDValue CallSeqStart, SDValue &Callee,
4163                               int SPDiff, unsigned NumBytes,
4164                               const SmallVectorImpl<ISD::InputArg> &Ins,
4165                               SmallVectorImpl<SDValue> &InVals,
4166                               ImmutableCallSite *CS) const {
4167
4168   std::vector<EVT> NodeTys;
4169   SmallVector<SDValue, 8> Ops;
4170   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4171                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4172                                  Ops, NodeTys, CS, Subtarget);
4173
4174   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4175   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4176     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4177
4178   // When performing tail call optimization the callee pops its arguments off
4179   // the stack. Account for this here so these bytes can be pushed back on in
4180   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4181   int BytesCalleePops =
4182     (CallConv == CallingConv::Fast &&
4183      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4184
4185   // Add a register mask operand representing the call-preserved registers.
4186   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4187   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
4188   assert(Mask && "Missing call preserved mask for calling convention");
4189   Ops.push_back(DAG.getRegisterMask(Mask));
4190
4191   if (InFlag.getNode())
4192     Ops.push_back(InFlag);
4193
4194   // Emit tail call.
4195   if (isTailCall) {
4196     assert(((Callee.getOpcode() == ISD::Register &&
4197              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4198             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4199             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4200             isa<ConstantSDNode>(Callee)) &&
4201     "Expecting an global address, external symbol, absolute value or register");
4202
4203     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4204   }
4205
4206   // Add a NOP immediately after the branch instruction when using the 64-bit
4207   // SVR4 ABI. At link time, if caller and callee are in a different module and
4208   // thus have a different TOC, the call will be replaced with a call to a stub
4209   // function which saves the current TOC, loads the TOC of the callee and
4210   // branches to the callee. The NOP will be replaced with a load instruction
4211   // which restores the TOC of the caller from the TOC save slot of the current
4212   // stack frame. If caller and callee belong to the same module (and have the
4213   // same TOC), the NOP will remain unchanged.
4214
4215   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4216       !IsPatchPoint) {
4217     if (CallOpc == PPCISD::BCTRL) {
4218       // This is a call through a function pointer.
4219       // Restore the caller TOC from the save area into R2.
4220       // See PrepareCall() for more information about calls through function
4221       // pointers in the 64-bit SVR4 ABI.
4222       // We are using a target-specific load with r2 hard coded, because the
4223       // result of a target-independent load would never go directly into r2,
4224       // since r2 is a reserved register (which prevents the register allocator
4225       // from allocating it), resulting in an additional register being
4226       // allocated and an unnecessary move instruction being generated.
4227       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4228
4229       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4230       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4231       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4232       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4233       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4234
4235       // The address needs to go after the chain input but before the flag (or
4236       // any other variadic arguments).
4237       Ops.insert(std::next(Ops.begin()), AddTOC);
4238     } else if ((CallOpc == PPCISD::CALL) &&
4239                (!isLocalCall(Callee) ||
4240                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4241       // Otherwise insert NOP for non-local calls.
4242       CallOpc = PPCISD::CALL_NOP;
4243   }
4244
4245   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4246   InFlag = Chain.getValue(1);
4247
4248   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4249                              DAG.getIntPtrConstant(BytesCalleePops, true),
4250                              InFlag, dl);
4251   if (!Ins.empty())
4252     InFlag = Chain.getValue(1);
4253
4254   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4255                          Ins, dl, DAG, InVals);
4256 }
4257
4258 SDValue
4259 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4260                              SmallVectorImpl<SDValue> &InVals) const {
4261   SelectionDAG &DAG                     = CLI.DAG;
4262   SDLoc &dl                             = CLI.DL;
4263   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4264   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4265   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4266   SDValue Chain                         = CLI.Chain;
4267   SDValue Callee                        = CLI.Callee;
4268   bool &isTailCall                      = CLI.IsTailCall;
4269   CallingConv::ID CallConv              = CLI.CallConv;
4270   bool isVarArg                         = CLI.IsVarArg;
4271   bool IsPatchPoint                     = CLI.IsPatchPoint;
4272   ImmutableCallSite *CS                 = CLI.CS;
4273
4274   if (isTailCall)
4275     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4276                                                    Ins, DAG);
4277
4278   if (!isTailCall && CS && CS->isMustTailCall())
4279     report_fatal_error("failed to perform tail call elimination on a call "
4280                        "site marked musttail");
4281
4282   if (Subtarget.isSVR4ABI()) {
4283     if (Subtarget.isPPC64())
4284       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4285                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4286                               dl, DAG, InVals, CS);
4287     else
4288       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4289                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4290                               dl, DAG, InVals, CS);
4291   }
4292
4293   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4294                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4295                           dl, DAG, InVals, CS);
4296 }
4297
4298 SDValue
4299 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4300                                     CallingConv::ID CallConv, bool isVarArg,
4301                                     bool isTailCall, bool IsPatchPoint,
4302                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4303                                     const SmallVectorImpl<SDValue> &OutVals,
4304                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4305                                     SDLoc dl, SelectionDAG &DAG,
4306                                     SmallVectorImpl<SDValue> &InVals,
4307                                     ImmutableCallSite *CS) const {
4308   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4309   // of the 32-bit SVR4 ABI stack frame layout.
4310
4311   assert((CallConv == CallingConv::C ||
4312           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4313
4314   unsigned PtrByteSize = 4;
4315
4316   MachineFunction &MF = DAG.getMachineFunction();
4317
4318   // Mark this function as potentially containing a function that contains a
4319   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4320   // and restoring the callers stack pointer in this functions epilog. This is
4321   // done because by tail calling the called function might overwrite the value
4322   // in this function's (MF) stack pointer stack slot 0(SP).
4323   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4324       CallConv == CallingConv::Fast)
4325     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4326
4327   // Count how many bytes are to be pushed on the stack, including the linkage
4328   // area, parameter list area and the part of the local variable space which
4329   // contains copies of aggregates which are passed by value.
4330
4331   // Assign locations to all of the outgoing arguments.
4332   SmallVector<CCValAssign, 16> ArgLocs;
4333   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4334                  *DAG.getContext());
4335
4336   // Reserve space for the linkage area on the stack.
4337   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4338                        PtrByteSize);
4339
4340   if (isVarArg) {
4341     // Handle fixed and variable vector arguments differently.
4342     // Fixed vector arguments go into registers as long as registers are
4343     // available. Variable vector arguments always go into memory.
4344     unsigned NumArgs = Outs.size();
4345
4346     for (unsigned i = 0; i != NumArgs; ++i) {
4347       MVT ArgVT = Outs[i].VT;
4348       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4349       bool Result;
4350
4351       if (Outs[i].IsFixed) {
4352         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4353                                CCInfo);
4354       } else {
4355         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4356                                       ArgFlags, CCInfo);
4357       }
4358
4359       if (Result) {
4360 #ifndef NDEBUG
4361         errs() << "Call operand #" << i << " has unhandled type "
4362              << EVT(ArgVT).getEVTString() << "\n";
4363 #endif
4364         llvm_unreachable(nullptr);
4365       }
4366     }
4367   } else {
4368     // All arguments are treated the same.
4369     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4370   }
4371
4372   // Assign locations to all of the outgoing aggregate by value arguments.
4373   SmallVector<CCValAssign, 16> ByValArgLocs;
4374   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4375                       ByValArgLocs, *DAG.getContext());
4376
4377   // Reserve stack space for the allocations in CCInfo.
4378   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4379
4380   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4381
4382   // Size of the linkage area, parameter list area and the part of the local
4383   // space variable where copies of aggregates which are passed by value are
4384   // stored.
4385   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4386
4387   // Calculate by how many bytes the stack has to be adjusted in case of tail
4388   // call optimization.
4389   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4390
4391   // Adjust the stack pointer for the new arguments...
4392   // These operations are automatically eliminated by the prolog/epilog pass
4393   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4394                                dl);
4395   SDValue CallSeqStart = Chain;
4396
4397   // Load the return address and frame pointer so it can be moved somewhere else
4398   // later.
4399   SDValue LROp, FPOp;
4400   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4401                                        dl);
4402
4403   // Set up a copy of the stack pointer for use loading and storing any
4404   // arguments that may not fit in the registers available for argument
4405   // passing.
4406   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4407
4408   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4409   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4410   SmallVector<SDValue, 8> MemOpChains;
4411
4412   bool seenFloatArg = false;
4413   // Walk the register/memloc assignments, inserting copies/loads.
4414   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4415        i != e;
4416        ++i) {
4417     CCValAssign &VA = ArgLocs[i];
4418     SDValue Arg = OutVals[i];
4419     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4420
4421     if (Flags.isByVal()) {
4422       // Argument is an aggregate which is passed by value, thus we need to
4423       // create a copy of it in the local variable space of the current stack
4424       // frame (which is the stack frame of the caller) and pass the address of
4425       // this copy to the callee.
4426       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4427       CCValAssign &ByValVA = ByValArgLocs[j++];
4428       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4429
4430       // Memory reserved in the local variable space of the callers stack frame.
4431       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4432
4433       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4434       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4435
4436       // Create a copy of the argument in the local area of the current
4437       // stack frame.
4438       SDValue MemcpyCall =
4439         CreateCopyOfByValArgument(Arg, PtrOff,
4440                                   CallSeqStart.getNode()->getOperand(0),
4441                                   Flags, DAG, dl);
4442
4443       // This must go outside the CALLSEQ_START..END.
4444       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4445                            CallSeqStart.getNode()->getOperand(1),
4446                            SDLoc(MemcpyCall));
4447       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4448                              NewCallSeqStart.getNode());
4449       Chain = CallSeqStart = NewCallSeqStart;
4450
4451       // Pass the address of the aggregate copy on the stack either in a
4452       // physical register or in the parameter list area of the current stack
4453       // frame to the callee.
4454       Arg = PtrOff;
4455     }
4456
4457     if (VA.isRegLoc()) {
4458       if (Arg.getValueType() == MVT::i1)
4459         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4460
4461       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4462       // Put argument in a physical register.
4463       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4464     } else {
4465       // Put argument in the parameter list area of the current stack frame.
4466       assert(VA.isMemLoc());
4467       unsigned LocMemOffset = VA.getLocMemOffset();
4468
4469       if (!isTailCall) {
4470         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4471         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4472
4473         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4474                                            MachinePointerInfo(),
4475                                            false, false, 0));
4476       } else {
4477         // Calculate and remember argument location.
4478         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4479                                  TailCallArguments);
4480       }
4481     }
4482   }
4483
4484   if (!MemOpChains.empty())
4485     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4486
4487   // Build a sequence of copy-to-reg nodes chained together with token chain
4488   // and flag operands which copy the outgoing args into the appropriate regs.
4489   SDValue InFlag;
4490   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4491     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4492                              RegsToPass[i].second, InFlag);
4493     InFlag = Chain.getValue(1);
4494   }
4495
4496   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4497   // registers.
4498   if (isVarArg) {
4499     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4500     SDValue Ops[] = { Chain, InFlag };
4501
4502     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4503                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4504
4505     InFlag = Chain.getValue(1);
4506   }
4507
4508   if (isTailCall)
4509     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4510                     false, TailCallArguments);
4511
4512   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4513                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4514                     NumBytes, Ins, InVals, CS);
4515 }
4516
4517 // Copy an argument into memory, being careful to do this outside the
4518 // call sequence for the call to which the argument belongs.
4519 SDValue
4520 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4521                                               SDValue CallSeqStart,
4522                                               ISD::ArgFlagsTy Flags,
4523                                               SelectionDAG &DAG,
4524                                               SDLoc dl) const {
4525   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4526                         CallSeqStart.getNode()->getOperand(0),
4527                         Flags, DAG, dl);
4528   // The MEMCPY must go outside the CALLSEQ_START..END.
4529   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4530                              CallSeqStart.getNode()->getOperand(1),
4531                              SDLoc(MemcpyCall));
4532   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4533                          NewCallSeqStart.getNode());
4534   return NewCallSeqStart;
4535 }
4536
4537 SDValue
4538 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4539                                     CallingConv::ID CallConv, bool isVarArg,
4540                                     bool isTailCall, bool IsPatchPoint,
4541                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4542                                     const SmallVectorImpl<SDValue> &OutVals,
4543                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4544                                     SDLoc dl, SelectionDAG &DAG,
4545                                     SmallVectorImpl<SDValue> &InVals,
4546                                     ImmutableCallSite *CS) const {
4547
4548   bool isELFv2ABI = Subtarget.isELFv2ABI();
4549   bool isLittleEndian = Subtarget.isLittleEndian();
4550   unsigned NumOps = Outs.size();
4551
4552   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4553   unsigned PtrByteSize = 8;
4554
4555   MachineFunction &MF = DAG.getMachineFunction();
4556
4557   // Mark this function as potentially containing a function that contains a
4558   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4559   // and restoring the callers stack pointer in this functions epilog. This is
4560   // done because by tail calling the called function might overwrite the value
4561   // in this function's (MF) stack pointer stack slot 0(SP).
4562   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4563       CallConv == CallingConv::Fast)
4564     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4565
4566   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4567          "fastcc not supported on varargs functions");
4568
4569   // Count how many bytes are to be pushed on the stack, including the linkage
4570   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4571   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4572   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4573   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4574   unsigned NumBytes = LinkageSize;
4575   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4576   unsigned &QFPR_idx = FPR_idx;
4577
4578   static const MCPhysReg GPR[] = {
4579     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4580     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4581   };
4582   static const MCPhysReg VR[] = {
4583     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4584     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4585   };
4586   static const MCPhysReg VSRH[] = {
4587     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4588     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4589   };
4590
4591   const unsigned NumGPRs = array_lengthof(GPR);
4592   const unsigned NumFPRs = 13;
4593   const unsigned NumVRs  = array_lengthof(VR);
4594   const unsigned NumQFPRs = NumFPRs;
4595
4596   // When using the fast calling convention, we don't provide backing for
4597   // arguments that will be in registers.
4598   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4599
4600   // Add up all the space actually used.
4601   for (unsigned i = 0; i != NumOps; ++i) {
4602     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4603     EVT ArgVT = Outs[i].VT;
4604     EVT OrigVT = Outs[i].ArgVT;
4605
4606     if (CallConv == CallingConv::Fast) {
4607       if (Flags.isByVal())
4608         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4609       else
4610         switch (ArgVT.getSimpleVT().SimpleTy) {
4611         default: llvm_unreachable("Unexpected ValueType for argument!");
4612         case MVT::i1:
4613         case MVT::i32:
4614         case MVT::i64:
4615           if (++NumGPRsUsed <= NumGPRs)
4616             continue;
4617           break;
4618         case MVT::v4i32:
4619         case MVT::v8i16:
4620         case MVT::v16i8:
4621         case MVT::v2f64:
4622         case MVT::v2i64:
4623           if (++NumVRsUsed <= NumVRs)
4624             continue;
4625           break;
4626         case MVT::v4f32:
4627           // When using QPX, this is handled like a FP register, otherwise, it
4628           // is an Altivec register.
4629           if (Subtarget.hasQPX()) {
4630             if (++NumFPRsUsed <= NumFPRs)
4631               continue;
4632           } else {
4633             if (++NumVRsUsed <= NumVRs)
4634               continue;
4635           }
4636           break;
4637         case MVT::f32:
4638         case MVT::f64:
4639         case MVT::v4f64: // QPX
4640         case MVT::v4i1:  // QPX
4641           if (++NumFPRsUsed <= NumFPRs)
4642             continue;
4643           break;
4644         }
4645     }
4646
4647     /* Respect alignment of argument on the stack.  */
4648     unsigned Align =
4649       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4650     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4651
4652     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4653     if (Flags.isInConsecutiveRegsLast())
4654       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4655   }
4656
4657   unsigned NumBytesActuallyUsed = NumBytes;
4658
4659   // The prolog code of the callee may store up to 8 GPR argument registers to
4660   // the stack, allowing va_start to index over them in memory if its varargs.
4661   // Because we cannot tell if this is needed on the caller side, we have to
4662   // conservatively assume that it is needed.  As such, make sure we have at
4663   // least enough stack space for the caller to store the 8 GPRs.
4664   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4665   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4666
4667   // Tail call needs the stack to be aligned.
4668   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4669       CallConv == CallingConv::Fast)
4670     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4671
4672   // Calculate by how many bytes the stack has to be adjusted in case of tail
4673   // call optimization.
4674   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4675
4676   // To protect arguments on the stack from being clobbered in a tail call,
4677   // force all the loads to happen before doing any other lowering.
4678   if (isTailCall)
4679     Chain = DAG.getStackArgumentTokenFactor(Chain);
4680
4681   // Adjust the stack pointer for the new arguments...
4682   // These operations are automatically eliminated by the prolog/epilog pass
4683   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4684                                dl);
4685   SDValue CallSeqStart = Chain;
4686
4687   // Load the return address and frame pointer so it can be move somewhere else
4688   // later.
4689   SDValue LROp, FPOp;
4690   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4691                                        dl);
4692
4693   // Set up a copy of the stack pointer for use loading and storing any
4694   // arguments that may not fit in the registers available for argument
4695   // passing.
4696   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4697
4698   // Figure out which arguments are going to go in registers, and which in
4699   // memory.  Also, if this is a vararg function, floating point operations
4700   // must be stored to our stack, and loaded into integer regs as well, if
4701   // any integer regs are available for argument passing.
4702   unsigned ArgOffset = LinkageSize;
4703
4704   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4705   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4706
4707   SmallVector<SDValue, 8> MemOpChains;
4708   for (unsigned i = 0; i != NumOps; ++i) {
4709     SDValue Arg = OutVals[i];
4710     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4711     EVT ArgVT = Outs[i].VT;
4712     EVT OrigVT = Outs[i].ArgVT;
4713
4714     // PtrOff will be used to store the current argument to the stack if a
4715     // register cannot be found for it.
4716     SDValue PtrOff;
4717
4718     // We re-align the argument offset for each argument, except when using the
4719     // fast calling convention, when we need to make sure we do that only when
4720     // we'll actually use a stack slot.
4721     auto ComputePtrOff = [&]() {
4722       /* Respect alignment of argument on the stack.  */
4723       unsigned Align =
4724         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4725       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4726
4727       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4728
4729       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4730     };
4731
4732     if (CallConv != CallingConv::Fast) {
4733       ComputePtrOff();
4734
4735       /* Compute GPR index associated with argument offset.  */
4736       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4737       GPR_idx = std::min(GPR_idx, NumGPRs);
4738     }
4739
4740     // Promote integers to 64-bit values.
4741     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4742       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4743       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4744       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4745     }
4746
4747     // FIXME memcpy is used way more than necessary.  Correctness first.
4748     // Note: "by value" is code for passing a structure by value, not
4749     // basic types.
4750     if (Flags.isByVal()) {
4751       // Note: Size includes alignment padding, so
4752       //   struct x { short a; char b; }
4753       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4754       // These are the proper values we need for right-justifying the
4755       // aggregate in a parameter register.
4756       unsigned Size = Flags.getByValSize();
4757
4758       // An empty aggregate parameter takes up no storage and no
4759       // registers.
4760       if (Size == 0)
4761         continue;
4762
4763       if (CallConv == CallingConv::Fast)
4764         ComputePtrOff();
4765
4766       // All aggregates smaller than 8 bytes must be passed right-justified.
4767       if (Size==1 || Size==2 || Size==4) {
4768         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4769         if (GPR_idx != NumGPRs) {
4770           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4771                                         MachinePointerInfo(), VT,
4772                                         false, false, false, 0);
4773           MemOpChains.push_back(Load.getValue(1));
4774           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4775
4776           ArgOffset += PtrByteSize;
4777           continue;
4778         }
4779       }
4780
4781       if (GPR_idx == NumGPRs && Size < 8) {
4782         SDValue AddPtr = PtrOff;
4783         if (!isLittleEndian) {
4784           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4785                                           PtrOff.getValueType());
4786           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4787         }
4788         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4789                                                           CallSeqStart,
4790                                                           Flags, DAG, dl);
4791         ArgOffset += PtrByteSize;
4792         continue;
4793       }
4794       // Copy entire object into memory.  There are cases where gcc-generated
4795       // code assumes it is there, even if it could be put entirely into
4796       // registers.  (This is not what the doc says.)
4797
4798       // FIXME: The above statement is likely due to a misunderstanding of the
4799       // documents.  All arguments must be copied into the parameter area BY
4800       // THE CALLEE in the event that the callee takes the address of any
4801       // formal argument.  That has not yet been implemented.  However, it is
4802       // reasonable to use the stack area as a staging area for the register
4803       // load.
4804
4805       // Skip this for small aggregates, as we will use the same slot for a
4806       // right-justified copy, below.
4807       if (Size >= 8)
4808         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4809                                                           CallSeqStart,
4810                                                           Flags, DAG, dl);
4811
4812       // When a register is available, pass a small aggregate right-justified.
4813       if (Size < 8 && GPR_idx != NumGPRs) {
4814         // The easiest way to get this right-justified in a register
4815         // is to copy the structure into the rightmost portion of a
4816         // local variable slot, then load the whole slot into the
4817         // register.
4818         // FIXME: The memcpy seems to produce pretty awful code for
4819         // small aggregates, particularly for packed ones.
4820         // FIXME: It would be preferable to use the slot in the
4821         // parameter save area instead of a new local variable.
4822         SDValue AddPtr = PtrOff;
4823         if (!isLittleEndian) {
4824           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4825           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4826         }
4827         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4828                                                           CallSeqStart,
4829                                                           Flags, DAG, dl);
4830
4831         // Load the slot into the register.
4832         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4833                                    MachinePointerInfo(),
4834                                    false, false, false, 0);
4835         MemOpChains.push_back(Load.getValue(1));
4836         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4837
4838         // Done with this argument.
4839         ArgOffset += PtrByteSize;
4840         continue;
4841       }
4842
4843       // For aggregates larger than PtrByteSize, copy the pieces of the
4844       // object that fit into registers from the parameter save area.
4845       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4846         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4847         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4848         if (GPR_idx != NumGPRs) {
4849           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4850                                      MachinePointerInfo(),
4851                                      false, false, false, 0);
4852           MemOpChains.push_back(Load.getValue(1));
4853           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4854           ArgOffset += PtrByteSize;
4855         } else {
4856           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4857           break;
4858         }
4859       }
4860       continue;
4861     }
4862
4863     switch (Arg.getSimpleValueType().SimpleTy) {
4864     default: llvm_unreachable("Unexpected ValueType for argument!");
4865     case MVT::i1:
4866     case MVT::i32:
4867     case MVT::i64:
4868       // These can be scalar arguments or elements of an integer array type
4869       // passed directly.  Clang may use those instead of "byval" aggregate
4870       // types to avoid forcing arguments to memory unnecessarily.
4871       if (GPR_idx != NumGPRs) {
4872         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4873       } else {
4874         if (CallConv == CallingConv::Fast)
4875           ComputePtrOff();
4876
4877         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4878                          true, isTailCall, false, MemOpChains,
4879                          TailCallArguments, dl);
4880         if (CallConv == CallingConv::Fast)
4881           ArgOffset += PtrByteSize;
4882       }
4883       if (CallConv != CallingConv::Fast)
4884         ArgOffset += PtrByteSize;
4885       break;
4886     case MVT::f32:
4887     case MVT::f64: {
4888       // These can be scalar arguments or elements of a float array type
4889       // passed directly.  The latter are used to implement ELFv2 homogenous
4890       // float aggregates.
4891
4892       // Named arguments go into FPRs first, and once they overflow, the
4893       // remaining arguments go into GPRs and then the parameter save area.
4894       // Unnamed arguments for vararg functions always go to GPRs and
4895       // then the parameter save area.  For now, put all arguments to vararg
4896       // routines always in both locations (FPR *and* GPR or stack slot).
4897       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4898       bool NeededLoad = false;
4899
4900       // First load the argument into the next available FPR.
4901       if (FPR_idx != NumFPRs)
4902         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4903
4904       // Next, load the argument into GPR or stack slot if needed.
4905       if (!NeedGPROrStack)
4906         ;
4907       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4908         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4909         // once we support fp <-> gpr moves.
4910
4911         // In the non-vararg case, this can only ever happen in the
4912         // presence of f32 array types, since otherwise we never run
4913         // out of FPRs before running out of GPRs.
4914         SDValue ArgVal;
4915
4916         // Double values are always passed in a single GPR.
4917         if (Arg.getValueType() != MVT::f32) {
4918           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4919
4920         // Non-array float values are extended and passed in a GPR.
4921         } else if (!Flags.isInConsecutiveRegs()) {
4922           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4923           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4924
4925         // If we have an array of floats, we collect every odd element
4926         // together with its predecessor into one GPR.
4927         } else if (ArgOffset % PtrByteSize != 0) {
4928           SDValue Lo, Hi;
4929           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4930           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4931           if (!isLittleEndian)
4932             std::swap(Lo, Hi);
4933           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4934
4935         // The final element, if even, goes into the first half of a GPR.
4936         } else if (Flags.isInConsecutiveRegsLast()) {
4937           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4938           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4939           if (!isLittleEndian)
4940             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4941                                  DAG.getConstant(32, MVT::i32));
4942
4943         // Non-final even elements are skipped; they will be handled
4944         // together the with subsequent argument on the next go-around.
4945         } else
4946           ArgVal = SDValue();
4947
4948         if (ArgVal.getNode())
4949           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4950       } else {
4951         if (CallConv == CallingConv::Fast)
4952           ComputePtrOff();
4953
4954         // Single-precision floating-point values are mapped to the
4955         // second (rightmost) word of the stack doubleword.
4956         if (Arg.getValueType() == MVT::f32 &&
4957             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4958           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4959           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4960         }
4961
4962         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4963                          true, isTailCall, false, MemOpChains,
4964                          TailCallArguments, dl);
4965
4966         NeededLoad = true;
4967       }
4968       // When passing an array of floats, the array occupies consecutive
4969       // space in the argument area; only round up to the next doubleword
4970       // at the end of the array.  Otherwise, each float takes 8 bytes.
4971       if (CallConv != CallingConv::Fast || NeededLoad) {
4972         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4973                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4974         if (Flags.isInConsecutiveRegsLast())
4975           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4976       }
4977       break;
4978     }
4979     case MVT::v4f32:
4980     case MVT::v4i32:
4981     case MVT::v8i16:
4982     case MVT::v16i8:
4983     case MVT::v2f64:
4984     case MVT::v2i64:
4985       if (!Subtarget.hasQPX()) {
4986       // These can be scalar arguments or elements of a vector array type
4987       // passed directly.  The latter are used to implement ELFv2 homogenous
4988       // vector aggregates.
4989
4990       // For a varargs call, named arguments go into VRs or on the stack as
4991       // usual; unnamed arguments always go to the stack or the corresponding
4992       // GPRs when within range.  For now, we always put the value in both
4993       // locations (or even all three).
4994       if (isVarArg) {
4995         // We could elide this store in the case where the object fits
4996         // entirely in R registers.  Maybe later.
4997         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4998                                      MachinePointerInfo(), false, false, 0);
4999         MemOpChains.push_back(Store);
5000         if (VR_idx != NumVRs) {
5001           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5002                                      MachinePointerInfo(),
5003                                      false, false, false, 0);
5004           MemOpChains.push_back(Load.getValue(1));
5005
5006           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5007                            Arg.getSimpleValueType() == MVT::v2i64) ?
5008                           VSRH[VR_idx] : VR[VR_idx];
5009           ++VR_idx;
5010
5011           RegsToPass.push_back(std::make_pair(VReg, Load));
5012         }
5013         ArgOffset += 16;
5014         for (unsigned i=0; i<16; i+=PtrByteSize) {
5015           if (GPR_idx == NumGPRs)
5016             break;
5017           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5018                                   DAG.getConstant(i, PtrVT));
5019           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5020                                      false, false, false, 0);
5021           MemOpChains.push_back(Load.getValue(1));
5022           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5023         }
5024         break;
5025       }
5026
5027       // Non-varargs Altivec params go into VRs or on the stack.
5028       if (VR_idx != NumVRs) {
5029         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5030                          Arg.getSimpleValueType() == MVT::v2i64) ?
5031                         VSRH[VR_idx] : VR[VR_idx];
5032         ++VR_idx;
5033
5034         RegsToPass.push_back(std::make_pair(VReg, Arg));
5035       } else {
5036         if (CallConv == CallingConv::Fast)
5037           ComputePtrOff();
5038
5039         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5040                          true, isTailCall, true, MemOpChains,
5041                          TailCallArguments, dl);
5042         if (CallConv == CallingConv::Fast)
5043           ArgOffset += 16;
5044       }
5045
5046       if (CallConv != CallingConv::Fast)
5047         ArgOffset += 16;
5048       break;
5049       } // not QPX
5050
5051       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5052              "Invalid QPX parameter type");
5053
5054       /* fall through */
5055     case MVT::v4f64:
5056     case MVT::v4i1: {
5057       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5058       if (isVarArg) {
5059         // We could elide this store in the case where the object fits
5060         // entirely in R registers.  Maybe later.
5061         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5062                                      MachinePointerInfo(), false, false, 0);
5063         MemOpChains.push_back(Store);
5064         if (QFPR_idx != NumQFPRs) {
5065           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5066                                      Store, PtrOff, MachinePointerInfo(),
5067                                      false, false, false, 0);
5068           MemOpChains.push_back(Load.getValue(1));
5069           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5070         }
5071         ArgOffset += (IsF32 ? 16 : 32);
5072         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5073           if (GPR_idx == NumGPRs)
5074             break;
5075           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5076                                   DAG.getConstant(i, PtrVT));
5077           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5078                                      false, false, false, 0);
5079           MemOpChains.push_back(Load.getValue(1));
5080           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5081         }
5082         break;
5083       }
5084
5085       // Non-varargs QPX params go into registers or on the stack.
5086       if (QFPR_idx != NumQFPRs) {
5087         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5088       } else {
5089         if (CallConv == CallingConv::Fast)
5090           ComputePtrOff();
5091
5092         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5093                          true, isTailCall, true, MemOpChains,
5094                          TailCallArguments, dl);
5095         if (CallConv == CallingConv::Fast)
5096           ArgOffset += (IsF32 ? 16 : 32);
5097       }
5098
5099       if (CallConv != CallingConv::Fast)
5100         ArgOffset += (IsF32 ? 16 : 32);
5101       break;
5102       }
5103     }
5104   }
5105
5106   assert(NumBytesActuallyUsed == ArgOffset);
5107   (void)NumBytesActuallyUsed;
5108
5109   if (!MemOpChains.empty())
5110     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5111
5112   // Check if this is an indirect call (MTCTR/BCTRL).
5113   // See PrepareCall() for more information about calls through function
5114   // pointers in the 64-bit SVR4 ABI.
5115   if (!isTailCall && !IsPatchPoint &&
5116       !isFunctionGlobalAddress(Callee) &&
5117       !isa<ExternalSymbolSDNode>(Callee)) {
5118     // Load r2 into a virtual register and store it to the TOC save area.
5119     setUsesTOCBasePtr(DAG);
5120     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5121     // TOC save area offset.
5122     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5123     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5124     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5125     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5126                          MachinePointerInfo::getStack(TOCSaveOffset),
5127                          false, false, 0);
5128     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5129     // This does not mean the MTCTR instruction must use R12; it's easier
5130     // to model this as an extra parameter, so do that.
5131     if (isELFv2ABI && !IsPatchPoint)
5132       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5133   }
5134
5135   // Build a sequence of copy-to-reg nodes chained together with token chain
5136   // and flag operands which copy the outgoing args into the appropriate regs.
5137   SDValue InFlag;
5138   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5139     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5140                              RegsToPass[i].second, InFlag);
5141     InFlag = Chain.getValue(1);
5142   }
5143
5144   if (isTailCall)
5145     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5146                     FPOp, true, TailCallArguments);
5147
5148   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5149                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5150                     NumBytes, Ins, InVals, CS);
5151 }
5152
5153 SDValue
5154 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5155                                     CallingConv::ID CallConv, bool isVarArg,
5156                                     bool isTailCall, bool IsPatchPoint,
5157                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5158                                     const SmallVectorImpl<SDValue> &OutVals,
5159                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5160                                     SDLoc dl, SelectionDAG &DAG,
5161                                     SmallVectorImpl<SDValue> &InVals,
5162                                     ImmutableCallSite *CS) const {
5163
5164   unsigned NumOps = Outs.size();
5165
5166   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5167   bool isPPC64 = PtrVT == MVT::i64;
5168   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5169
5170   MachineFunction &MF = DAG.getMachineFunction();
5171
5172   // Mark this function as potentially containing a function that contains a
5173   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5174   // and restoring the callers stack pointer in this functions epilog. This is
5175   // done because by tail calling the called function might overwrite the value
5176   // in this function's (MF) stack pointer stack slot 0(SP).
5177   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5178       CallConv == CallingConv::Fast)
5179     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5180
5181   // Count how many bytes are to be pushed on the stack, including the linkage
5182   // area, and parameter passing area.  We start with 24/48 bytes, which is
5183   // prereserved space for [SP][CR][LR][3 x unused].
5184   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5185   unsigned NumBytes = LinkageSize;
5186
5187   // Add up all the space actually used.
5188   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5189   // they all go in registers, but we must reserve stack space for them for
5190   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5191   // assigned stack space in order, with padding so Altivec parameters are
5192   // 16-byte aligned.
5193   unsigned nAltivecParamsAtEnd = 0;
5194   for (unsigned i = 0; i != NumOps; ++i) {
5195     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5196     EVT ArgVT = Outs[i].VT;
5197     // Varargs Altivec parameters are padded to a 16 byte boundary.
5198     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5199         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5200         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5201       if (!isVarArg && !isPPC64) {
5202         // Non-varargs Altivec parameters go after all the non-Altivec
5203         // parameters; handle those later so we know how much padding we need.
5204         nAltivecParamsAtEnd++;
5205         continue;
5206       }
5207       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5208       NumBytes = ((NumBytes+15)/16)*16;
5209     }
5210     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5211   }
5212
5213   // Allow for Altivec parameters at the end, if needed.
5214   if (nAltivecParamsAtEnd) {
5215     NumBytes = ((NumBytes+15)/16)*16;
5216     NumBytes += 16*nAltivecParamsAtEnd;
5217   }
5218
5219   // The prolog code of the callee may store up to 8 GPR argument registers to
5220   // the stack, allowing va_start to index over them in memory if its varargs.
5221   // Because we cannot tell if this is needed on the caller side, we have to
5222   // conservatively assume that it is needed.  As such, make sure we have at
5223   // least enough stack space for the caller to store the 8 GPRs.
5224   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5225
5226   // Tail call needs the stack to be aligned.
5227   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5228       CallConv == CallingConv::Fast)
5229     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5230
5231   // Calculate by how many bytes the stack has to be adjusted in case of tail
5232   // call optimization.
5233   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5234
5235   // To protect arguments on the stack from being clobbered in a tail call,
5236   // force all the loads to happen before doing any other lowering.
5237   if (isTailCall)
5238     Chain = DAG.getStackArgumentTokenFactor(Chain);
5239
5240   // Adjust the stack pointer for the new arguments...
5241   // These operations are automatically eliminated by the prolog/epilog pass
5242   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5243                                dl);
5244   SDValue CallSeqStart = Chain;
5245
5246   // Load the return address and frame pointer so it can be move somewhere else
5247   // later.
5248   SDValue LROp, FPOp;
5249   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5250                                        dl);
5251
5252   // Set up a copy of the stack pointer for use loading and storing any
5253   // arguments that may not fit in the registers available for argument
5254   // passing.
5255   SDValue StackPtr;
5256   if (isPPC64)
5257     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5258   else
5259     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5260
5261   // Figure out which arguments are going to go in registers, and which in
5262   // memory.  Also, if this is a vararg function, floating point operations
5263   // must be stored to our stack, and loaded into integer regs as well, if
5264   // any integer regs are available for argument passing.
5265   unsigned ArgOffset = LinkageSize;
5266   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5267
5268   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5269     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5270     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5271   };
5272   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5273     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5274     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5275   };
5276   static const MCPhysReg VR[] = {
5277     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5278     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5279   };
5280   const unsigned NumGPRs = array_lengthof(GPR_32);
5281   const unsigned NumFPRs = 13;
5282   const unsigned NumVRs  = array_lengthof(VR);
5283
5284   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5285
5286   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5287   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5288
5289   SmallVector<SDValue, 8> MemOpChains;
5290   for (unsigned i = 0; i != NumOps; ++i) {
5291     SDValue Arg = OutVals[i];
5292     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5293
5294     // PtrOff will be used to store the current argument to the stack if a
5295     // register cannot be found for it.
5296     SDValue PtrOff;
5297
5298     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5299
5300     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5301
5302     // On PPC64, promote integers to 64-bit values.
5303     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5304       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5305       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5306       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5307     }
5308
5309     // FIXME memcpy is used way more than necessary.  Correctness first.
5310     // Note: "by value" is code for passing a structure by value, not
5311     // basic types.
5312     if (Flags.isByVal()) {
5313       unsigned Size = Flags.getByValSize();
5314       // Very small objects are passed right-justified.  Everything else is
5315       // passed left-justified.
5316       if (Size==1 || Size==2) {
5317         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5318         if (GPR_idx != NumGPRs) {
5319           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5320                                         MachinePointerInfo(), VT,
5321                                         false, false, false, 0);
5322           MemOpChains.push_back(Load.getValue(1));
5323           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5324
5325           ArgOffset += PtrByteSize;
5326         } else {
5327           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5328                                           PtrOff.getValueType());
5329           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5330           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5331                                                             CallSeqStart,
5332                                                             Flags, DAG, dl);
5333           ArgOffset += PtrByteSize;
5334         }
5335         continue;
5336       }
5337       // Copy entire object into memory.  There are cases where gcc-generated
5338       // code assumes it is there, even if it could be put entirely into
5339       // registers.  (This is not what the doc says.)
5340       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5341                                                         CallSeqStart,
5342                                                         Flags, DAG, dl);
5343
5344       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5345       // copy the pieces of the object that fit into registers from the
5346       // parameter save area.
5347       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5348         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5349         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5350         if (GPR_idx != NumGPRs) {
5351           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5352                                      MachinePointerInfo(),
5353                                      false, false, false, 0);
5354           MemOpChains.push_back(Load.getValue(1));
5355           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5356           ArgOffset += PtrByteSize;
5357         } else {
5358           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5359           break;
5360         }
5361       }
5362       continue;
5363     }
5364
5365     switch (Arg.getSimpleValueType().SimpleTy) {
5366     default: llvm_unreachable("Unexpected ValueType for argument!");
5367     case MVT::i1:
5368     case MVT::i32:
5369     case MVT::i64:
5370       if (GPR_idx != NumGPRs) {
5371         if (Arg.getValueType() == MVT::i1)
5372           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5373
5374         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5375       } else {
5376         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5377                          isPPC64, isTailCall, false, MemOpChains,
5378                          TailCallArguments, dl);
5379       }
5380       ArgOffset += PtrByteSize;
5381       break;
5382     case MVT::f32:
5383     case MVT::f64:
5384       if (FPR_idx != NumFPRs) {
5385         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5386
5387         if (isVarArg) {
5388           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5389                                        MachinePointerInfo(), false, false, 0);
5390           MemOpChains.push_back(Store);
5391
5392           // Float varargs are always shadowed in available integer registers
5393           if (GPR_idx != NumGPRs) {
5394             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5395                                        MachinePointerInfo(), false, false,
5396                                        false, 0);
5397             MemOpChains.push_back(Load.getValue(1));
5398             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5399           }
5400           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5401             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5402             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5403             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5404                                        MachinePointerInfo(),
5405                                        false, false, false, 0);
5406             MemOpChains.push_back(Load.getValue(1));
5407             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5408           }
5409         } else {
5410           // If we have any FPRs remaining, we may also have GPRs remaining.
5411           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5412           // GPRs.
5413           if (GPR_idx != NumGPRs)
5414             ++GPR_idx;
5415           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5416               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5417             ++GPR_idx;
5418         }
5419       } else
5420         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5421                          isPPC64, isTailCall, false, MemOpChains,
5422                          TailCallArguments, dl);
5423       if (isPPC64)
5424         ArgOffset += 8;
5425       else
5426         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5427       break;
5428     case MVT::v4f32:
5429     case MVT::v4i32:
5430     case MVT::v8i16:
5431     case MVT::v16i8:
5432       if (isVarArg) {
5433         // These go aligned on the stack, or in the corresponding R registers
5434         // when within range.  The Darwin PPC ABI doc claims they also go in
5435         // V registers; in fact gcc does this only for arguments that are
5436         // prototyped, not for those that match the ...  We do it for all
5437         // arguments, seems to work.
5438         while (ArgOffset % 16 !=0) {
5439           ArgOffset += PtrByteSize;
5440           if (GPR_idx != NumGPRs)
5441             GPR_idx++;
5442         }
5443         // We could elide this store in the case where the object fits
5444         // entirely in R registers.  Maybe later.
5445         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5446                             DAG.getConstant(ArgOffset, PtrVT));
5447         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5448                                      MachinePointerInfo(), false, false, 0);
5449         MemOpChains.push_back(Store);
5450         if (VR_idx != NumVRs) {
5451           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5452                                      MachinePointerInfo(),
5453                                      false, false, false, 0);
5454           MemOpChains.push_back(Load.getValue(1));
5455           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5456         }
5457         ArgOffset += 16;
5458         for (unsigned i=0; i<16; i+=PtrByteSize) {
5459           if (GPR_idx == NumGPRs)
5460             break;
5461           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5462                                   DAG.getConstant(i, PtrVT));
5463           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5464                                      false, false, false, 0);
5465           MemOpChains.push_back(Load.getValue(1));
5466           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5467         }
5468         break;
5469       }
5470
5471       // Non-varargs Altivec params generally go in registers, but have
5472       // stack space allocated at the end.
5473       if (VR_idx != NumVRs) {
5474         // Doesn't have GPR space allocated.
5475         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5476       } else if (nAltivecParamsAtEnd==0) {
5477         // We are emitting Altivec params in order.
5478         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5479                          isPPC64, isTailCall, true, MemOpChains,
5480                          TailCallArguments, dl);
5481         ArgOffset += 16;
5482       }
5483       break;
5484     }
5485   }
5486   // If all Altivec parameters fit in registers, as they usually do,
5487   // they get stack space following the non-Altivec parameters.  We
5488   // don't track this here because nobody below needs it.
5489   // If there are more Altivec parameters than fit in registers emit
5490   // the stores here.
5491   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5492     unsigned j = 0;
5493     // Offset is aligned; skip 1st 12 params which go in V registers.
5494     ArgOffset = ((ArgOffset+15)/16)*16;
5495     ArgOffset += 12*16;
5496     for (unsigned i = 0; i != NumOps; ++i) {
5497       SDValue Arg = OutVals[i];
5498       EVT ArgType = Outs[i].VT;
5499       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5500           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5501         if (++j > NumVRs) {
5502           SDValue PtrOff;
5503           // We are emitting Altivec params in order.
5504           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5505                            isPPC64, isTailCall, true, MemOpChains,
5506                            TailCallArguments, dl);
5507           ArgOffset += 16;
5508         }
5509       }
5510     }
5511   }
5512
5513   if (!MemOpChains.empty())
5514     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5515
5516   // On Darwin, R12 must contain the address of an indirect callee.  This does
5517   // not mean the MTCTR instruction must use R12; it's easier to model this as
5518   // an extra parameter, so do that.
5519   if (!isTailCall &&
5520       !isFunctionGlobalAddress(Callee) &&
5521       !isa<ExternalSymbolSDNode>(Callee) &&
5522       !isBLACompatibleAddress(Callee, DAG))
5523     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5524                                                    PPC::R12), Callee));
5525
5526   // Build a sequence of copy-to-reg nodes chained together with token chain
5527   // and flag operands which copy the outgoing args into the appropriate regs.
5528   SDValue InFlag;
5529   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5530     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5531                              RegsToPass[i].second, InFlag);
5532     InFlag = Chain.getValue(1);
5533   }
5534
5535   if (isTailCall)
5536     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5537                     FPOp, true, TailCallArguments);
5538
5539   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5540                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5541                     NumBytes, Ins, InVals, CS);
5542 }
5543
5544 bool
5545 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5546                                   MachineFunction &MF, bool isVarArg,
5547                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5548                                   LLVMContext &Context) const {
5549   SmallVector<CCValAssign, 16> RVLocs;
5550   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5551   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5552 }
5553
5554 SDValue
5555 PPCTargetLowering::LowerReturn(SDValue Chain,
5556                                CallingConv::ID CallConv, bool isVarArg,
5557                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5558                                const SmallVectorImpl<SDValue> &OutVals,
5559                                SDLoc dl, SelectionDAG &DAG) const {
5560
5561   SmallVector<CCValAssign, 16> RVLocs;
5562   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5563                  *DAG.getContext());
5564   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5565
5566   SDValue Flag;
5567   SmallVector<SDValue, 4> RetOps(1, Chain);
5568
5569   // Copy the result values into the output registers.
5570   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5571     CCValAssign &VA = RVLocs[i];
5572     assert(VA.isRegLoc() && "Can only return in registers!");
5573
5574     SDValue Arg = OutVals[i];
5575
5576     switch (VA.getLocInfo()) {
5577     default: llvm_unreachable("Unknown loc info!");
5578     case CCValAssign::Full: break;
5579     case CCValAssign::AExt:
5580       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5581       break;
5582     case CCValAssign::ZExt:
5583       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5584       break;
5585     case CCValAssign::SExt:
5586       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5587       break;
5588     }
5589
5590     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5591     Flag = Chain.getValue(1);
5592     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5593   }
5594
5595   RetOps[0] = Chain;  // Update chain.
5596
5597   // Add the flag if we have it.
5598   if (Flag.getNode())
5599     RetOps.push_back(Flag);
5600
5601   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5602 }
5603
5604 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5605                                    const PPCSubtarget &Subtarget) const {
5606   // When we pop the dynamic allocation we need to restore the SP link.
5607   SDLoc dl(Op);
5608
5609   // Get the corect type for pointers.
5610   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5611
5612   // Construct the stack pointer operand.
5613   bool isPPC64 = Subtarget.isPPC64();
5614   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5615   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5616
5617   // Get the operands for the STACKRESTORE.
5618   SDValue Chain = Op.getOperand(0);
5619   SDValue SaveSP = Op.getOperand(1);
5620
5621   // Load the old link SP.
5622   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5623                                    MachinePointerInfo(),
5624                                    false, false, false, 0);
5625
5626   // Restore the stack pointer.
5627   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5628
5629   // Store the old link SP.
5630   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5631                       false, false, 0);
5632 }
5633
5634
5635
5636 SDValue
5637 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5638   MachineFunction &MF = DAG.getMachineFunction();
5639   bool isPPC64 = Subtarget.isPPC64();
5640   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5641
5642   // Get current frame pointer save index.  The users of this index will be
5643   // primarily DYNALLOC instructions.
5644   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5645   int RASI = FI->getReturnAddrSaveIndex();
5646
5647   // If the frame pointer save index hasn't been defined yet.
5648   if (!RASI) {
5649     // Find out what the fix offset of the frame pointer save area.
5650     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5651     // Allocate the frame index for frame pointer save area.
5652     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5653     // Save the result.
5654     FI->setReturnAddrSaveIndex(RASI);
5655   }
5656   return DAG.getFrameIndex(RASI, PtrVT);
5657 }
5658
5659 SDValue
5660 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5661   MachineFunction &MF = DAG.getMachineFunction();
5662   bool isPPC64 = Subtarget.isPPC64();
5663   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5664
5665   // Get current frame pointer save index.  The users of this index will be
5666   // primarily DYNALLOC instructions.
5667   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5668   int FPSI = FI->getFramePointerSaveIndex();
5669
5670   // If the frame pointer save index hasn't been defined yet.
5671   if (!FPSI) {
5672     // Find out what the fix offset of the frame pointer save area.
5673     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5674     // Allocate the frame index for frame pointer save area.
5675     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5676     // Save the result.
5677     FI->setFramePointerSaveIndex(FPSI);
5678   }
5679   return DAG.getFrameIndex(FPSI, PtrVT);
5680 }
5681
5682 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5683                                          SelectionDAG &DAG,
5684                                          const PPCSubtarget &Subtarget) const {
5685   // Get the inputs.
5686   SDValue Chain = Op.getOperand(0);
5687   SDValue Size  = Op.getOperand(1);
5688   SDLoc dl(Op);
5689
5690   // Get the corect type for pointers.
5691   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5692   // Negate the size.
5693   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5694                                   DAG.getConstant(0, PtrVT), Size);
5695   // Construct a node for the frame pointer save index.
5696   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5697   // Build a DYNALLOC node.
5698   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5699   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5700   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5701 }
5702
5703 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5704                                                SelectionDAG &DAG) const {
5705   SDLoc DL(Op);
5706   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5707                      DAG.getVTList(MVT::i32, MVT::Other),
5708                      Op.getOperand(0), Op.getOperand(1));
5709 }
5710
5711 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5712                                                 SelectionDAG &DAG) const {
5713   SDLoc DL(Op);
5714   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5715                      Op.getOperand(0), Op.getOperand(1));
5716 }
5717
5718 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5719   if (Op.getValueType().isVector())
5720     return LowerVectorLoad(Op, DAG);
5721
5722   assert(Op.getValueType() == MVT::i1 &&
5723          "Custom lowering only for i1 loads");
5724
5725   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5726
5727   SDLoc dl(Op);
5728   LoadSDNode *LD = cast<LoadSDNode>(Op);
5729
5730   SDValue Chain = LD->getChain();
5731   SDValue BasePtr = LD->getBasePtr();
5732   MachineMemOperand *MMO = LD->getMemOperand();
5733
5734   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5735                                  BasePtr, MVT::i8, MMO);
5736   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5737
5738   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5739   return DAG.getMergeValues(Ops, dl);
5740 }
5741
5742 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5743   if (Op.getOperand(1).getValueType().isVector())
5744     return LowerVectorStore(Op, DAG);
5745
5746   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5747          "Custom lowering only for i1 stores");
5748
5749   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5750
5751   SDLoc dl(Op);
5752   StoreSDNode *ST = cast<StoreSDNode>(Op);
5753
5754   SDValue Chain = ST->getChain();
5755   SDValue BasePtr = ST->getBasePtr();
5756   SDValue Value = ST->getValue();
5757   MachineMemOperand *MMO = ST->getMemOperand();
5758
5759   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5760   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5761 }
5762
5763 // FIXME: Remove this once the ANDI glue bug is fixed:
5764 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5765   assert(Op.getValueType() == MVT::i1 &&
5766          "Custom lowering only for i1 results");
5767
5768   SDLoc DL(Op);
5769   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5770                      Op.getOperand(0));
5771 }
5772
5773 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5774 /// possible.
5775 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5776   // Not FP? Not a fsel.
5777   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5778       !Op.getOperand(2).getValueType().isFloatingPoint())
5779     return Op;
5780
5781   // We might be able to do better than this under some circumstances, but in
5782   // general, fsel-based lowering of select is a finite-math-only optimization.
5783   // For more information, see section F.3 of the 2.06 ISA specification.
5784   if (!DAG.getTarget().Options.NoInfsFPMath ||
5785       !DAG.getTarget().Options.NoNaNsFPMath)
5786     return Op;
5787
5788   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5789
5790   EVT ResVT = Op.getValueType();
5791   EVT CmpVT = Op.getOperand(0).getValueType();
5792   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5793   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5794   SDLoc dl(Op);
5795
5796   // If the RHS of the comparison is a 0.0, we don't need to do the
5797   // subtraction at all.
5798   SDValue Sel1;
5799   if (isFloatingPointZero(RHS))
5800     switch (CC) {
5801     default: break;       // SETUO etc aren't handled by fsel.
5802     case ISD::SETNE:
5803       std::swap(TV, FV);
5804     case ISD::SETEQ:
5805       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5806         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5807       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5808       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5809         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5810       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5811                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5812     case ISD::SETULT:
5813     case ISD::SETLT:
5814       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5815     case ISD::SETOGE:
5816     case ISD::SETGE:
5817       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5818         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5819       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5820     case ISD::SETUGT:
5821     case ISD::SETGT:
5822       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5823     case ISD::SETOLE:
5824     case ISD::SETLE:
5825       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5826         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5827       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5828                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5829     }
5830
5831   SDValue Cmp;
5832   switch (CC) {
5833   default: break;       // SETUO etc aren't handled by fsel.
5834   case ISD::SETNE:
5835     std::swap(TV, FV);
5836   case ISD::SETEQ:
5837     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5838     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5839       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5840     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5841     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5842       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5843     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5844                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5845   case ISD::SETULT:
5846   case ISD::SETLT:
5847     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5848     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5849       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5850     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5851   case ISD::SETOGE:
5852   case ISD::SETGE:
5853     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5854     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5855       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5856     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5857   case ISD::SETUGT:
5858   case ISD::SETGT:
5859     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5860     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5861       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5862     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5863   case ISD::SETOLE:
5864   case ISD::SETLE:
5865     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5866     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5867       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5868     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5869   }
5870   return Op;
5871 }
5872
5873 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5874                                                SelectionDAG &DAG,
5875                                                SDLoc dl) const {
5876   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5877   SDValue Src = Op.getOperand(0);
5878   if (Src.getValueType() == MVT::f32)
5879     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5880
5881   SDValue Tmp;
5882   switch (Op.getSimpleValueType().SimpleTy) {
5883   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5884   case MVT::i32:
5885     Tmp = DAG.getNode(
5886         Op.getOpcode() == ISD::FP_TO_SINT
5887             ? PPCISD::FCTIWZ
5888             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5889         dl, MVT::f64, Src);
5890     break;
5891   case MVT::i64:
5892     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5893            "i64 FP_TO_UINT is supported only with FPCVT");
5894     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5895                                                         PPCISD::FCTIDUZ,
5896                       dl, MVT::f64, Src);
5897     break;
5898   }
5899
5900   // Convert the FP value to an int value through memory.
5901   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5902     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5903   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5904   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5905   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5906
5907   // Emit a store to the stack slot.
5908   SDValue Chain;
5909   if (i32Stack) {
5910     MachineFunction &MF = DAG.getMachineFunction();
5911     MachineMemOperand *MMO =
5912       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5913     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5914     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5915               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5916   } else
5917     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5918                          MPI, false, false, 0);
5919
5920   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5921   // add in a bias.
5922   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5923     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5924                         DAG.getConstant(4, FIPtr.getValueType()));
5925     MPI = MPI.getWithOffset(4);
5926   }
5927
5928   RLI.Chain = Chain;
5929   RLI.Ptr = FIPtr;
5930   RLI.MPI = MPI;
5931 }
5932
5933 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5934                                           SDLoc dl) const {
5935   ReuseLoadInfo RLI;
5936   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5937
5938   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5939                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5940                      RLI.Ranges);
5941 }
5942
5943 // We're trying to insert a regular store, S, and then a load, L. If the
5944 // incoming value, O, is a load, we might just be able to have our load use the
5945 // address used by O. However, we don't know if anything else will store to
5946 // that address before we can load from it. To prevent this situation, we need
5947 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5948 // the same chain operand as O, we create a token factor from the chain results
5949 // of O and L, and we replace all uses of O's chain result with that token
5950 // factor (see spliceIntoChain below for this last part).
5951 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5952                                             ReuseLoadInfo &RLI,
5953                                             SelectionDAG &DAG,
5954                                             ISD::LoadExtType ET) const {
5955   SDLoc dl(Op);
5956   if (ET == ISD::NON_EXTLOAD &&
5957       (Op.getOpcode() == ISD::FP_TO_UINT ||
5958        Op.getOpcode() == ISD::FP_TO_SINT) &&
5959       isOperationLegalOrCustom(Op.getOpcode(),
5960                                Op.getOperand(0).getValueType())) {
5961
5962     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5963     return true;
5964   }
5965
5966   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5967   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5968       LD->isNonTemporal())
5969     return false;
5970   if (LD->getMemoryVT() != MemVT)
5971     return false;
5972
5973   RLI.Ptr = LD->getBasePtr();
5974   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5975     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5976            "Non-pre-inc AM on PPC?");
5977     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5978                           LD->getOffset());
5979   }
5980
5981   RLI.Chain = LD->getChain();
5982   RLI.MPI = LD->getPointerInfo();
5983   RLI.IsInvariant = LD->isInvariant();
5984   RLI.Alignment = LD->getAlignment();
5985   RLI.AAInfo = LD->getAAInfo();
5986   RLI.Ranges = LD->getRanges();
5987
5988   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5989   return true;
5990 }
5991
5992 // Given the head of the old chain, ResChain, insert a token factor containing
5993 // it and NewResChain, and make users of ResChain now be users of that token
5994 // factor.
5995 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5996                                         SDValue NewResChain,
5997                                         SelectionDAG &DAG) const {
5998   if (!ResChain)
5999     return;
6000
6001   SDLoc dl(NewResChain);
6002
6003   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6004                            NewResChain, DAG.getUNDEF(MVT::Other));
6005   assert(TF.getNode() != NewResChain.getNode() &&
6006          "A new TF really is required here");
6007
6008   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6009   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6010 }
6011
6012 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6013                                           SelectionDAG &DAG) const {
6014   SDLoc dl(Op);
6015
6016   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6017     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6018       return SDValue();
6019
6020     SDValue Value = Op.getOperand(0);
6021     // The values are now known to be -1 (false) or 1 (true). To convert this
6022     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6023     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6024     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6025   
6026     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6027     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6028                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6029   
6030     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6031
6032     if (Op.getValueType() != MVT::v4f64)
6033       Value = DAG.getNode(ISD::FP_ROUND, dl,
6034                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6035     return Value;
6036   }
6037
6038   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6039   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6040     return SDValue();
6041
6042   if (Op.getOperand(0).getValueType() == MVT::i1)
6043     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6044                        DAG.getConstantFP(1.0, Op.getValueType()),
6045                        DAG.getConstantFP(0.0, Op.getValueType()));
6046
6047   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6048          "UINT_TO_FP is supported only with FPCVT");
6049
6050   // If we have FCFIDS, then use it when converting to single-precision.
6051   // Otherwise, convert to double-precision and then round.
6052   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6053                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6054                                                             : PPCISD::FCFIDS)
6055                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6056                                                             : PPCISD::FCFID);
6057   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6058                   ? MVT::f32
6059                   : MVT::f64;
6060
6061   if (Op.getOperand(0).getValueType() == MVT::i64) {
6062     SDValue SINT = Op.getOperand(0);
6063     // When converting to single-precision, we actually need to convert
6064     // to double-precision first and then round to single-precision.
6065     // To avoid double-rounding effects during that operation, we have
6066     // to prepare the input operand.  Bits that might be truncated when
6067     // converting to double-precision are replaced by a bit that won't
6068     // be lost at this stage, but is below the single-precision rounding
6069     // position.
6070     //
6071     // However, if -enable-unsafe-fp-math is in effect, accept double
6072     // rounding to avoid the extra overhead.
6073     if (Op.getValueType() == MVT::f32 &&
6074         !Subtarget.hasFPCVT() &&
6075         !DAG.getTarget().Options.UnsafeFPMath) {
6076
6077       // Twiddle input to make sure the low 11 bits are zero.  (If this
6078       // is the case, we are guaranteed the value will fit into the 53 bit
6079       // mantissa of an IEEE double-precision value without rounding.)
6080       // If any of those low 11 bits were not zero originally, make sure
6081       // bit 12 (value 2048) is set instead, so that the final rounding
6082       // to single-precision gets the correct result.
6083       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6084                                   SINT, DAG.getConstant(2047, MVT::i64));
6085       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6086                           Round, DAG.getConstant(2047, MVT::i64));
6087       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6088       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6089                           Round, DAG.getConstant(-2048, MVT::i64));
6090
6091       // However, we cannot use that value unconditionally: if the magnitude
6092       // of the input value is small, the bit-twiddling we did above might
6093       // end up visibly changing the output.  Fortunately, in that case, we
6094       // don't need to twiddle bits since the original input will convert
6095       // exactly to double-precision floating-point already.  Therefore,
6096       // construct a conditional to use the original value if the top 11
6097       // bits are all sign-bit copies, and use the rounded value computed
6098       // above otherwise.
6099       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6100                                  SINT, DAG.getConstant(53, MVT::i32));
6101       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6102                          Cond, DAG.getConstant(1, MVT::i64));
6103       Cond = DAG.getSetCC(dl, MVT::i32,
6104                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6105
6106       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6107     }
6108
6109     ReuseLoadInfo RLI;
6110     SDValue Bits;
6111
6112     MachineFunction &MF = DAG.getMachineFunction();
6113     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6114       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6115                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6116                          RLI.Ranges);
6117       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6118     } else if (Subtarget.hasLFIWAX() &&
6119                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6120       MachineMemOperand *MMO =
6121         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6122                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6123       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6124       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6125                                      DAG.getVTList(MVT::f64, MVT::Other),
6126                                      Ops, MVT::i32, MMO);
6127       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6128     } else if (Subtarget.hasFPCVT() &&
6129                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6130       MachineMemOperand *MMO =
6131         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6132                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6133       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6134       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6135                                      DAG.getVTList(MVT::f64, MVT::Other),
6136                                      Ops, MVT::i32, MMO);
6137       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6138     } else if (((Subtarget.hasLFIWAX() &&
6139                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6140                 (Subtarget.hasFPCVT() &&
6141                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6142                SINT.getOperand(0).getValueType() == MVT::i32) {
6143       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6144       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6145
6146       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6147       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6148
6149       SDValue Store =
6150         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6151                      MachinePointerInfo::getFixedStack(FrameIdx),
6152                      false, false, 0);
6153
6154       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6155              "Expected an i32 store");
6156
6157       RLI.Ptr = FIdx;
6158       RLI.Chain = Store;
6159       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6160       RLI.Alignment = 4;
6161
6162       MachineMemOperand *MMO =
6163         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6164                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6165       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6166       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6167                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6168                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6169                                      Ops, MVT::i32, MMO);
6170     } else
6171       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6172
6173     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6174
6175     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6176       FP = DAG.getNode(ISD::FP_ROUND, dl,
6177                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6178     return FP;
6179   }
6180
6181   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6182          "Unhandled INT_TO_FP type in custom expander!");
6183   // Since we only generate this in 64-bit mode, we can take advantage of
6184   // 64-bit registers.  In particular, sign extend the input value into the
6185   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6186   // then lfd it and fcfid it.
6187   MachineFunction &MF = DAG.getMachineFunction();
6188   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6189   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6190
6191   SDValue Ld;
6192   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6193     ReuseLoadInfo RLI;
6194     bool ReusingLoad;
6195     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6196                                             DAG))) {
6197       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6198       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6199
6200       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6201                                    MachinePointerInfo::getFixedStack(FrameIdx),
6202                                    false, false, 0);
6203
6204       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6205              "Expected an i32 store");
6206
6207       RLI.Ptr = FIdx;
6208       RLI.Chain = Store;
6209       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6210       RLI.Alignment = 4;
6211     }
6212
6213     MachineMemOperand *MMO =
6214       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6215                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6216     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6217     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6218                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6219                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6220                                  Ops, MVT::i32, MMO);
6221     if (ReusingLoad)
6222       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6223   } else {
6224     assert(Subtarget.isPPC64() &&
6225            "i32->FP without LFIWAX supported only on PPC64");
6226
6227     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6228     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6229
6230     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6231                                 Op.getOperand(0));
6232
6233     // STD the extended value into the stack slot.
6234     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6235                                  MachinePointerInfo::getFixedStack(FrameIdx),
6236                                  false, false, 0);
6237
6238     // Load the value as a double.
6239     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6240                      MachinePointerInfo::getFixedStack(FrameIdx),
6241                      false, false, false, 0);
6242   }
6243
6244   // FCFID it and return it.
6245   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6246   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6247     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6248   return FP;
6249 }
6250
6251 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6252                                             SelectionDAG &DAG) const {
6253   SDLoc dl(Op);
6254   /*
6255    The rounding mode is in bits 30:31 of FPSR, and has the following
6256    settings:
6257      00 Round to nearest
6258      01 Round to 0
6259      10 Round to +inf
6260      11 Round to -inf
6261
6262   FLT_ROUNDS, on the other hand, expects the following:
6263     -1 Undefined
6264      0 Round to 0
6265      1 Round to nearest
6266      2 Round to +inf
6267      3 Round to -inf
6268
6269   To perform the conversion, we do:
6270     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6271   */
6272
6273   MachineFunction &MF = DAG.getMachineFunction();
6274   EVT VT = Op.getValueType();
6275   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6276
6277   // Save FP Control Word to register
6278   EVT NodeTys[] = {
6279     MVT::f64,    // return register
6280     MVT::Glue    // unused in this context
6281   };
6282   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6283
6284   // Save FP register to stack slot
6285   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6286   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6287   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6288                                StackSlot, MachinePointerInfo(), false, false,0);
6289
6290   // Load FP Control Word from low 32 bits of stack slot.
6291   SDValue Four = DAG.getConstant(4, PtrVT);
6292   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6293   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6294                             false, false, false, 0);
6295
6296   // Transform as necessary
6297   SDValue CWD1 =
6298     DAG.getNode(ISD::AND, dl, MVT::i32,
6299                 CWD, DAG.getConstant(3, MVT::i32));
6300   SDValue CWD2 =
6301     DAG.getNode(ISD::SRL, dl, MVT::i32,
6302                 DAG.getNode(ISD::AND, dl, MVT::i32,
6303                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6304                                         CWD, DAG.getConstant(3, MVT::i32)),
6305                             DAG.getConstant(3, MVT::i32)),
6306                 DAG.getConstant(1, MVT::i32));
6307
6308   SDValue RetVal =
6309     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6310
6311   return DAG.getNode((VT.getSizeInBits() < 16 ?
6312                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6313 }
6314
6315 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6316   EVT VT = Op.getValueType();
6317   unsigned BitWidth = VT.getSizeInBits();
6318   SDLoc dl(Op);
6319   assert(Op.getNumOperands() == 3 &&
6320          VT == Op.getOperand(1).getValueType() &&
6321          "Unexpected SHL!");
6322
6323   // Expand into a bunch of logical ops.  Note that these ops
6324   // depend on the PPC behavior for oversized shift amounts.
6325   SDValue Lo = Op.getOperand(0);
6326   SDValue Hi = Op.getOperand(1);
6327   SDValue Amt = Op.getOperand(2);
6328   EVT AmtVT = Amt.getValueType();
6329
6330   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6331                              DAG.getConstant(BitWidth, AmtVT), Amt);
6332   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6333   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6334   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6335   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6336                              DAG.getConstant(-BitWidth, AmtVT));
6337   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6338   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6339   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6340   SDValue OutOps[] = { OutLo, OutHi };
6341   return DAG.getMergeValues(OutOps, dl);
6342 }
6343
6344 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6345   EVT VT = Op.getValueType();
6346   SDLoc dl(Op);
6347   unsigned BitWidth = VT.getSizeInBits();
6348   assert(Op.getNumOperands() == 3 &&
6349          VT == Op.getOperand(1).getValueType() &&
6350          "Unexpected SRL!");
6351
6352   // Expand into a bunch of logical ops.  Note that these ops
6353   // depend on the PPC behavior for oversized shift amounts.
6354   SDValue Lo = Op.getOperand(0);
6355   SDValue Hi = Op.getOperand(1);
6356   SDValue Amt = Op.getOperand(2);
6357   EVT AmtVT = Amt.getValueType();
6358
6359   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6360                              DAG.getConstant(BitWidth, AmtVT), Amt);
6361   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6362   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6363   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6364   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6365                              DAG.getConstant(-BitWidth, AmtVT));
6366   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6367   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6368   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6369   SDValue OutOps[] = { OutLo, OutHi };
6370   return DAG.getMergeValues(OutOps, dl);
6371 }
6372
6373 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6374   SDLoc dl(Op);
6375   EVT VT = Op.getValueType();
6376   unsigned BitWidth = VT.getSizeInBits();
6377   assert(Op.getNumOperands() == 3 &&
6378          VT == Op.getOperand(1).getValueType() &&
6379          "Unexpected SRA!");
6380
6381   // Expand into a bunch of logical ops, followed by a select_cc.
6382   SDValue Lo = Op.getOperand(0);
6383   SDValue Hi = Op.getOperand(1);
6384   SDValue Amt = Op.getOperand(2);
6385   EVT AmtVT = Amt.getValueType();
6386
6387   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6388                              DAG.getConstant(BitWidth, AmtVT), Amt);
6389   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6390   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6391   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6392   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6393                              DAG.getConstant(-BitWidth, AmtVT));
6394   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6395   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6396   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6397                                   Tmp4, Tmp6, ISD::SETLE);
6398   SDValue OutOps[] = { OutLo, OutHi };
6399   return DAG.getMergeValues(OutOps, dl);
6400 }
6401
6402 //===----------------------------------------------------------------------===//
6403 // Vector related lowering.
6404 //
6405
6406 /// BuildSplatI - Build a canonical splati of Val with an element size of
6407 /// SplatSize.  Cast the result to VT.
6408 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6409                              SelectionDAG &DAG, SDLoc dl) {
6410   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6411
6412   static const MVT VTys[] = { // canonical VT to use for each size.
6413     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6414   };
6415
6416   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6417
6418   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6419   if (Val == -1)
6420     SplatSize = 1;
6421
6422   EVT CanonicalVT = VTys[SplatSize-1];
6423
6424   // Build a canonical splat for this value.
6425   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6426   SmallVector<SDValue, 8> Ops;
6427   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6428   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6429   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6430 }
6431
6432 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6433 /// specified intrinsic ID.
6434 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6435                                 SelectionDAG &DAG, SDLoc dl,
6436                                 EVT DestVT = MVT::Other) {
6437   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6438   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6439                      DAG.getConstant(IID, MVT::i32), Op);
6440 }
6441
6442 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6443 /// specified intrinsic ID.
6444 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6445                                 SelectionDAG &DAG, SDLoc dl,
6446                                 EVT DestVT = MVT::Other) {
6447   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6448   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6449                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6450 }
6451
6452 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6453 /// specified intrinsic ID.
6454 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6455                                 SDValue Op2, SelectionDAG &DAG,
6456                                 SDLoc dl, EVT DestVT = MVT::Other) {
6457   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6458   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6459                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6460 }
6461
6462
6463 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6464 /// amount.  The result has the specified value type.
6465 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6466                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6467   // Force LHS/RHS to be the right type.
6468   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6469   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6470
6471   int Ops[16];
6472   for (unsigned i = 0; i != 16; ++i)
6473     Ops[i] = i + Amt;
6474   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6475   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6476 }
6477
6478 // If this is a case we can't handle, return null and let the default
6479 // expansion code take care of it.  If we CAN select this case, and if it
6480 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6481 // this case more efficiently than a constant pool load, lower it to the
6482 // sequence of ops that should be used.
6483 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6484                                              SelectionDAG &DAG) const {
6485   SDLoc dl(Op);
6486   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6487   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6488
6489   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6490     // We first build an i32 vector, load it into a QPX register,
6491     // then convert it to a floating-point vector and compare it
6492     // to a zero vector to get the boolean result.
6493     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6494     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6495     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6496     EVT PtrVT = getPointerTy();
6497     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6498
6499     assert(BVN->getNumOperands() == 4 &&
6500       "BUILD_VECTOR for v4i1 does not have 4 operands");
6501
6502     bool IsConst = true;
6503     for (unsigned i = 0; i < 4; ++i) {
6504       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6505       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6506         IsConst = false;
6507         break;
6508       }
6509     }
6510
6511     if (IsConst) {
6512       Constant *One =
6513         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6514       Constant *NegOne =
6515         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6516
6517       SmallVector<Constant*, 4> CV(4, NegOne);
6518       for (unsigned i = 0; i < 4; ++i) {
6519         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6520           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6521         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6522                    getConstantIntValue()->isZero())
6523           continue;
6524         else
6525           CV[i] = One;
6526       }
6527
6528       Constant *CP = ConstantVector::get(CV);
6529       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6530                       16 /* alignment */);
6531  
6532       SmallVector<SDValue, 2> Ops;
6533       Ops.push_back(DAG.getEntryNode());
6534       Ops.push_back(CPIdx);
6535
6536       SmallVector<EVT, 2> ValueVTs;
6537       ValueVTs.push_back(MVT::v4i1);
6538       ValueVTs.push_back(MVT::Other); // chain
6539       SDVTList VTs = DAG.getVTList(ValueVTs);
6540
6541       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6542         dl, VTs, Ops, MVT::v4f32,
6543         MachinePointerInfo::getConstantPool());
6544     }
6545
6546     SmallVector<SDValue, 4> Stores;
6547     for (unsigned i = 0; i < 4; ++i) {
6548       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6549
6550       unsigned Offset = 4*i;
6551       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6552       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6553
6554       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6555       if (StoreSize > 4) {
6556         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6557                                            BVN->getOperand(i), Idx,
6558                                            PtrInfo.getWithOffset(Offset),
6559                                            MVT::i32, false, false, 0));
6560       } else {
6561         SDValue StoreValue = BVN->getOperand(i);
6562         if (StoreSize < 4)
6563           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6564
6565         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6566                                       StoreValue, Idx,
6567                                       PtrInfo.getWithOffset(Offset),
6568                                       false, false, 0));
6569       }
6570     }
6571
6572     SDValue StoreChain;
6573     if (!Stores.empty())
6574       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6575     else
6576       StoreChain = DAG.getEntryNode();
6577
6578     // Now load from v4i32 into the QPX register; this will extend it to
6579     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6580     // is typed as v4f64 because the QPX register integer states are not
6581     // explicitly represented.
6582
6583     SmallVector<SDValue, 2> Ops;
6584     Ops.push_back(StoreChain);
6585     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6586     Ops.push_back(FIdx);
6587
6588     SmallVector<EVT, 2> ValueVTs;
6589     ValueVTs.push_back(MVT::v4f64);
6590     ValueVTs.push_back(MVT::Other); // chain
6591     SDVTList VTs = DAG.getVTList(ValueVTs);
6592
6593     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6594       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6595     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6596       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6597       LoadedVect);
6598
6599     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6600     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6601                           FPZeros, FPZeros, FPZeros, FPZeros);
6602
6603     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6604   }
6605
6606   // All other QPX vectors are handled by generic code.
6607   if (Subtarget.hasQPX())
6608     return SDValue();
6609
6610   // Check if this is a splat of a constant value.
6611   APInt APSplatBits, APSplatUndef;
6612   unsigned SplatBitSize;
6613   bool HasAnyUndefs;
6614   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6615                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6616     return SDValue();
6617
6618   unsigned SplatBits = APSplatBits.getZExtValue();
6619   unsigned SplatUndef = APSplatUndef.getZExtValue();
6620   unsigned SplatSize = SplatBitSize / 8;
6621
6622   // First, handle single instruction cases.
6623
6624   // All zeros?
6625   if (SplatBits == 0) {
6626     // Canonicalize all zero vectors to be v4i32.
6627     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6628       SDValue Z = DAG.getConstant(0, MVT::i32);
6629       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6630       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6631     }
6632     return Op;
6633   }
6634
6635   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6636   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6637                     (32-SplatBitSize));
6638   if (SextVal >= -16 && SextVal <= 15)
6639     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6640
6641
6642   // Two instruction sequences.
6643
6644   // If this value is in the range [-32,30] and is even, use:
6645   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6646   // If this value is in the range [17,31] and is odd, use:
6647   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6648   // If this value is in the range [-31,-17] and is odd, use:
6649   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6650   // Note the last two are three-instruction sequences.
6651   if (SextVal >= -32 && SextVal <= 31) {
6652     // To avoid having these optimizations undone by constant folding,
6653     // we convert to a pseudo that will be expanded later into one of
6654     // the above forms.
6655     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6656     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6657               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6658     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6659     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6660     if (VT == Op.getValueType())
6661       return RetVal;
6662     else
6663       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6664   }
6665
6666   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6667   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6668   // for fneg/fabs.
6669   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6670     // Make -1 and vspltisw -1:
6671     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6672
6673     // Make the VSLW intrinsic, computing 0x8000_0000.
6674     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6675                                    OnesV, DAG, dl);
6676
6677     // xor by OnesV to invert it.
6678     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6679     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6680   }
6681
6682   // The remaining cases assume either big endian element order or
6683   // a splat-size that equates to the element size of the vector
6684   // to be built.  An example that doesn't work for little endian is
6685   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6686   // and a vector element size of 16 bits.  The code below will
6687   // produce the vector in big endian element order, which for little
6688   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6689
6690   // For now, just avoid these optimizations in that case.
6691   // FIXME: Develop correct optimizations for LE with mismatched
6692   // splat and element sizes.
6693
6694   if (Subtarget.isLittleEndian() &&
6695       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6696     return SDValue();
6697
6698   // Check to see if this is a wide variety of vsplti*, binop self cases.
6699   static const signed char SplatCsts[] = {
6700     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6701     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6702   };
6703
6704   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6705     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6706     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6707     int i = SplatCsts[idx];
6708
6709     // Figure out what shift amount will be used by altivec if shifted by i in
6710     // this splat size.
6711     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6712
6713     // vsplti + shl self.
6714     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6715       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6716       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6717         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6718         Intrinsic::ppc_altivec_vslw
6719       };
6720       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6721       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6722     }
6723
6724     // vsplti + srl self.
6725     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6726       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6727       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6728         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6729         Intrinsic::ppc_altivec_vsrw
6730       };
6731       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6732       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6733     }
6734
6735     // vsplti + sra self.
6736     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6737       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6738       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6739         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6740         Intrinsic::ppc_altivec_vsraw
6741       };
6742       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6743       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6744     }
6745
6746     // vsplti + rol self.
6747     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6748                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6749       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6750       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6751         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6752         Intrinsic::ppc_altivec_vrlw
6753       };
6754       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6755       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6756     }
6757
6758     // t = vsplti c, result = vsldoi t, t, 1
6759     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6760       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6761       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6762     }
6763     // t = vsplti c, result = vsldoi t, t, 2
6764     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6765       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6766       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6767     }
6768     // t = vsplti c, result = vsldoi t, t, 3
6769     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6770       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6771       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6772     }
6773   }
6774
6775   return SDValue();
6776 }
6777
6778 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6779 /// the specified operations to build the shuffle.
6780 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6781                                       SDValue RHS, SelectionDAG &DAG,
6782                                       SDLoc dl) {
6783   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6784   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6785   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6786
6787   enum {
6788     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6789     OP_VMRGHW,
6790     OP_VMRGLW,
6791     OP_VSPLTISW0,
6792     OP_VSPLTISW1,
6793     OP_VSPLTISW2,
6794     OP_VSPLTISW3,
6795     OP_VSLDOI4,
6796     OP_VSLDOI8,
6797     OP_VSLDOI12
6798   };
6799
6800   if (OpNum == OP_COPY) {
6801     if (LHSID == (1*9+2)*9+3) return LHS;
6802     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6803     return RHS;
6804   }
6805
6806   SDValue OpLHS, OpRHS;
6807   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6808   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6809
6810   int ShufIdxs[16];
6811   switch (OpNum) {
6812   default: llvm_unreachable("Unknown i32 permute!");
6813   case OP_VMRGHW:
6814     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6815     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6816     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6817     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6818     break;
6819   case OP_VMRGLW:
6820     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6821     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6822     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6823     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6824     break;
6825   case OP_VSPLTISW0:
6826     for (unsigned i = 0; i != 16; ++i)
6827       ShufIdxs[i] = (i&3)+0;
6828     break;
6829   case OP_VSPLTISW1:
6830     for (unsigned i = 0; i != 16; ++i)
6831       ShufIdxs[i] = (i&3)+4;
6832     break;
6833   case OP_VSPLTISW2:
6834     for (unsigned i = 0; i != 16; ++i)
6835       ShufIdxs[i] = (i&3)+8;
6836     break;
6837   case OP_VSPLTISW3:
6838     for (unsigned i = 0; i != 16; ++i)
6839       ShufIdxs[i] = (i&3)+12;
6840     break;
6841   case OP_VSLDOI4:
6842     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6843   case OP_VSLDOI8:
6844     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6845   case OP_VSLDOI12:
6846     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6847   }
6848   EVT VT = OpLHS.getValueType();
6849   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6850   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6851   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6852   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6853 }
6854
6855 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6856 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6857 /// return the code it can be lowered into.  Worst case, it can always be
6858 /// lowered into a vperm.
6859 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6860                                                SelectionDAG &DAG) const {
6861   SDLoc dl(Op);
6862   SDValue V1 = Op.getOperand(0);
6863   SDValue V2 = Op.getOperand(1);
6864   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6865   EVT VT = Op.getValueType();
6866   bool isLittleEndian = Subtarget.isLittleEndian();
6867
6868   if (Subtarget.hasQPX()) {
6869     if (VT.getVectorNumElements() != 4)
6870       return SDValue();
6871
6872     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6873
6874     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6875     if (AlignIdx != -1) {
6876       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6877                          DAG.getConstant(AlignIdx, MVT::i32));
6878     } else if (SVOp->isSplat()) {
6879       int SplatIdx = SVOp->getSplatIndex();
6880       if (SplatIdx >= 4) {
6881         std::swap(V1, V2);
6882         SplatIdx -= 4;
6883       }
6884
6885       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6886       // nothing to do.
6887
6888       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6889                          DAG.getConstant(SplatIdx, MVT::i32));
6890     }
6891
6892     // Lower this into a qvgpci/qvfperm pair.
6893
6894     // Compute the qvgpci literal
6895     unsigned idx = 0;
6896     for (unsigned i = 0; i < 4; ++i) {
6897       int m = SVOp->getMaskElt(i);
6898       unsigned mm = m >= 0 ? (unsigned) m : i;
6899       idx |= mm << (3-i)*3;
6900     }
6901
6902     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6903                              DAG.getConstant(idx, MVT::i32));
6904     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6905   }
6906
6907   // Cases that are handled by instructions that take permute immediates
6908   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6909   // selected by the instruction selector.
6910   if (V2.getOpcode() == ISD::UNDEF) {
6911     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6912         PPC::isSplatShuffleMask(SVOp, 2) ||
6913         PPC::isSplatShuffleMask(SVOp, 4) ||
6914         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6915         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6916         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6917         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6918         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6919         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6920         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6921         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6922         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6923       return Op;
6924     }
6925   }
6926
6927   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6928   // and produce a fixed permutation.  If any of these match, do not lower to
6929   // VPERM.
6930   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6931   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6932       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6933       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6934       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6935       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6936       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6937       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6938       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6939       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6940     return Op;
6941
6942   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6943   // perfect shuffle table to emit an optimal matching sequence.
6944   ArrayRef<int> PermMask = SVOp->getMask();
6945
6946   unsigned PFIndexes[4];
6947   bool isFourElementShuffle = true;
6948   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6949     unsigned EltNo = 8;   // Start out undef.
6950     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6951       if (PermMask[i*4+j] < 0)
6952         continue;   // Undef, ignore it.
6953
6954       unsigned ByteSource = PermMask[i*4+j];
6955       if ((ByteSource & 3) != j) {
6956         isFourElementShuffle = false;
6957         break;
6958       }
6959
6960       if (EltNo == 8) {
6961         EltNo = ByteSource/4;
6962       } else if (EltNo != ByteSource/4) {
6963         isFourElementShuffle = false;
6964         break;
6965       }
6966     }
6967     PFIndexes[i] = EltNo;
6968   }
6969
6970   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6971   // perfect shuffle vector to determine if it is cost effective to do this as
6972   // discrete instructions, or whether we should use a vperm.
6973   // For now, we skip this for little endian until such time as we have a
6974   // little-endian perfect shuffle table.
6975   if (isFourElementShuffle && !isLittleEndian) {
6976     // Compute the index in the perfect shuffle table.
6977     unsigned PFTableIndex =
6978       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6979
6980     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6981     unsigned Cost  = (PFEntry >> 30);
6982
6983     // Determining when to avoid vperm is tricky.  Many things affect the cost
6984     // of vperm, particularly how many times the perm mask needs to be computed.
6985     // For example, if the perm mask can be hoisted out of a loop or is already
6986     // used (perhaps because there are multiple permutes with the same shuffle
6987     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6988     // the loop requires an extra register.
6989     //
6990     // As a compromise, we only emit discrete instructions if the shuffle can be
6991     // generated in 3 or fewer operations.  When we have loop information
6992     // available, if this block is within a loop, we should avoid using vperm
6993     // for 3-operation perms and use a constant pool load instead.
6994     if (Cost < 3)
6995       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6996   }
6997
6998   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6999   // vector that will get spilled to the constant pool.
7000   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7001
7002   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7003   // that it is in input element units, not in bytes.  Convert now.
7004
7005   // For little endian, the order of the input vectors is reversed, and
7006   // the permutation mask is complemented with respect to 31.  This is
7007   // necessary to produce proper semantics with the big-endian-biased vperm
7008   // instruction.
7009   EVT EltVT = V1.getValueType().getVectorElementType();
7010   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7011
7012   SmallVector<SDValue, 16> ResultMask;
7013   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7014     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7015
7016     for (unsigned j = 0; j != BytesPerElement; ++j)
7017       if (isLittleEndian)
7018         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7019                                              MVT::i32));
7020       else
7021         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7022                                              MVT::i32));
7023   }
7024
7025   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7026                                   ResultMask);
7027   if (isLittleEndian)
7028     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7029                        V2, V1, VPermMask);
7030   else
7031     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7032                        V1, V2, VPermMask);
7033 }
7034
7035 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7036 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7037 /// information about the intrinsic.
7038 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7039                                   bool &isDot, const PPCSubtarget &Subtarget) {
7040   unsigned IntrinsicID =
7041     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7042   CompareOpc = -1;
7043   isDot = false;
7044   switch (IntrinsicID) {
7045   default: return false;
7046     // Comparison predicates.
7047   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7048   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7049   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7050   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7051   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7052   case Intrinsic::ppc_altivec_vcmpequd_p: 
7053     if (Subtarget.hasP8Altivec()) {
7054       CompareOpc = 199; 
7055       isDot = 1; 
7056     }
7057     else 
7058       return false;
7059
7060     break;
7061   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7062   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7063   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7064   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7065   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7066   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7067     if (Subtarget.hasP8Altivec()) {
7068       CompareOpc = 967; 
7069       isDot = 1; 
7070     }
7071     else 
7072       return false;
7073
7074     break;
7075   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7076   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7077   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7078   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7079     if (Subtarget.hasP8Altivec()) {
7080       CompareOpc = 711; 
7081       isDot = 1; 
7082     }
7083     else 
7084       return false;
7085
7086     break;
7087       
7088     // Normal Comparisons.
7089   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7090   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7091   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7092   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7093   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7094   case Intrinsic::ppc_altivec_vcmpequd:
7095     if (Subtarget.hasP8Altivec()) {
7096       CompareOpc = 199; 
7097       isDot = 0; 
7098     }
7099     else
7100       return false;
7101
7102     break;
7103   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7104   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7105   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7106   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7107   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7108   case Intrinsic::ppc_altivec_vcmpgtsd:   
7109     if (Subtarget.hasP8Altivec()) {
7110       CompareOpc = 967; 
7111       isDot = 0; 
7112     }
7113     else
7114       return false;
7115
7116     break;
7117   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7118   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7119   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7120   case Intrinsic::ppc_altivec_vcmpgtud:   
7121     if (Subtarget.hasP8Altivec()) {
7122       CompareOpc = 711; 
7123       isDot = 0; 
7124     }
7125     else
7126       return false;
7127
7128     break;
7129   }
7130   return true;
7131 }
7132
7133 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7134 /// lower, do it, otherwise return null.
7135 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7136                                                    SelectionDAG &DAG) const {
7137   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7138   // opcode number of the comparison.
7139   SDLoc dl(Op);
7140   int CompareOpc;
7141   bool isDot;
7142   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7143     return SDValue();    // Don't custom lower most intrinsics.
7144
7145   // If this is a non-dot comparison, make the VCMP node and we are done.
7146   if (!isDot) {
7147     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7148                               Op.getOperand(1), Op.getOperand(2),
7149                               DAG.getConstant(CompareOpc, MVT::i32));
7150     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7151   }
7152
7153   // Create the PPCISD altivec 'dot' comparison node.
7154   SDValue Ops[] = {
7155     Op.getOperand(2),  // LHS
7156     Op.getOperand(3),  // RHS
7157     DAG.getConstant(CompareOpc, MVT::i32)
7158   };
7159   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7160   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7161
7162   // Now that we have the comparison, emit a copy from the CR to a GPR.
7163   // This is flagged to the above dot comparison.
7164   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7165                                 DAG.getRegister(PPC::CR6, MVT::i32),
7166                                 CompNode.getValue(1));
7167
7168   // Unpack the result based on how the target uses it.
7169   unsigned BitNo;   // Bit # of CR6.
7170   bool InvertBit;   // Invert result?
7171   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7172   default:  // Can't happen, don't crash on invalid number though.
7173   case 0:   // Return the value of the EQ bit of CR6.
7174     BitNo = 0; InvertBit = false;
7175     break;
7176   case 1:   // Return the inverted value of the EQ bit of CR6.
7177     BitNo = 0; InvertBit = true;
7178     break;
7179   case 2:   // Return the value of the LT bit of CR6.
7180     BitNo = 2; InvertBit = false;
7181     break;
7182   case 3:   // Return the inverted value of the LT bit of CR6.
7183     BitNo = 2; InvertBit = true;
7184     break;
7185   }
7186
7187   // Shift the bit into the low position.
7188   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7189                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7190   // Isolate the bit.
7191   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7192                       DAG.getConstant(1, MVT::i32));
7193
7194   // If we are supposed to, toggle the bit.
7195   if (InvertBit)
7196     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7197                         DAG.getConstant(1, MVT::i32));
7198   return Flags;
7199 }
7200
7201 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7202                                                   SelectionDAG &DAG) const {
7203   SDLoc dl(Op);
7204   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7205   // instructions), but for smaller types, we need to first extend up to v2i32
7206   // before doing going farther.
7207   if (Op.getValueType() == MVT::v2i64) {
7208     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7209     if (ExtVT != MVT::v2i32) {
7210       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7211       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7212                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7213                                         ExtVT.getVectorElementType(), 4)));
7214       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7215       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7216                        DAG.getValueType(MVT::v2i32));
7217     }
7218
7219     return Op;
7220   }
7221
7222   return SDValue();
7223 }
7224
7225 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7226                                                    SelectionDAG &DAG) const {
7227   SDLoc dl(Op);
7228   // Create a stack slot that is 16-byte aligned.
7229   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7230   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7231   EVT PtrVT = getPointerTy();
7232   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7233
7234   // Store the input value into Value#0 of the stack slot.
7235   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7236                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7237                                false, false, 0);
7238   // Load it out.
7239   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7240                      false, false, false, 0);
7241 }
7242
7243 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7244                                                    SelectionDAG &DAG) const {
7245   SDLoc dl(Op);
7246   SDNode *N = Op.getNode();
7247
7248   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7249          "Unknown extract_vector_elt type");
7250
7251   SDValue Value = N->getOperand(0);
7252
7253   // The first part of this is like the store lowering except that we don't
7254   // need to track the chain.
7255
7256   // The values are now known to be -1 (false) or 1 (true). To convert this
7257   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7258   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7259   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7260
7261   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7262   // understand how to form the extending load.
7263   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7264   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7265                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7266
7267   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7268
7269   // Now convert to an integer and store.
7270   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7271     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7272     Value);
7273
7274   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7275   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7276   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7277   EVT PtrVT = getPointerTy();
7278   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7279
7280   SDValue StoreChain = DAG.getEntryNode();
7281   SmallVector<SDValue, 2> Ops;
7282   Ops.push_back(StoreChain);
7283   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7284   Ops.push_back(Value);
7285   Ops.push_back(FIdx);
7286
7287   SmallVector<EVT, 2> ValueVTs;
7288   ValueVTs.push_back(MVT::Other); // chain
7289   SDVTList VTs = DAG.getVTList(ValueVTs);
7290
7291   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7292     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7293
7294   // Extract the value requested.
7295   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7296   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7297   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7298
7299   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7300                                PtrInfo.getWithOffset(Offset),
7301                                false, false, false, 0);
7302
7303   if (!Subtarget.useCRBits())
7304     return IntVal;
7305
7306   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7307 }
7308
7309 /// Lowering for QPX v4i1 loads
7310 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7311                                            SelectionDAG &DAG) const {
7312   SDLoc dl(Op);
7313   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7314   SDValue LoadChain = LN->getChain();
7315   SDValue BasePtr = LN->getBasePtr();
7316
7317   if (Op.getValueType() == MVT::v4f64 ||
7318       Op.getValueType() == MVT::v4f32) {
7319     EVT MemVT = LN->getMemoryVT();
7320     unsigned Alignment = LN->getAlignment();
7321
7322     // If this load is properly aligned, then it is legal.
7323     if (Alignment >= MemVT.getStoreSize())
7324       return Op;
7325
7326     EVT ScalarVT = Op.getValueType().getScalarType(),
7327         ScalarMemVT = MemVT.getScalarType();
7328     unsigned Stride = ScalarMemVT.getStoreSize();
7329
7330     SmallVector<SDValue, 8> Vals, LoadChains;
7331     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7332       SDValue Load;
7333       if (ScalarVT != ScalarMemVT)
7334         Load =
7335           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7336                          BasePtr,
7337                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7338                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7339                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7340                          LN->getAAInfo());
7341       else
7342         Load =
7343           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7344                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7345                        LN->isVolatile(), LN->isNonTemporal(),
7346                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7347                        LN->getAAInfo());
7348
7349       if (Idx == 0 && LN->isIndexed()) {
7350         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7351                "Unknown addressing mode on vector load");
7352         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7353                                   LN->getAddressingMode());
7354       }
7355
7356       Vals.push_back(Load);
7357       LoadChains.push_back(Load.getValue(1));
7358
7359       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7360                             DAG.getConstant(Stride, BasePtr.getValueType()));
7361     }
7362
7363     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7364     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7365                                    Op.getValueType(), Vals);
7366
7367     if (LN->isIndexed()) {
7368       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7369       return DAG.getMergeValues(RetOps, dl);
7370     }
7371
7372     SDValue RetOps[] = { Value, TF };
7373     return DAG.getMergeValues(RetOps, dl);
7374   }
7375
7376   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7377   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7378
7379   // To lower v4i1 from a byte array, we load the byte elements of the
7380   // vector and then reuse the BUILD_VECTOR logic.
7381
7382   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7383   for (unsigned i = 0; i < 4; ++i) {
7384     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7385     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7386
7387     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7388                         dl, MVT::i32, LoadChain, Idx,
7389                         LN->getPointerInfo().getWithOffset(i),
7390                         MVT::i8 /* memory type */,
7391                         LN->isVolatile(), LN->isNonTemporal(),
7392                         LN->isInvariant(),
7393                         1 /* alignment */, LN->getAAInfo()));
7394     VectElmtChains.push_back(VectElmts[i].getValue(1));
7395   }
7396
7397   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7398   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7399
7400   SDValue RVals[] = { Value, LoadChain };
7401   return DAG.getMergeValues(RVals, dl);
7402 }
7403
7404 /// Lowering for QPX v4i1 stores
7405 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7406                                             SelectionDAG &DAG) const {
7407   SDLoc dl(Op);
7408   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7409   SDValue StoreChain = SN->getChain();
7410   SDValue BasePtr = SN->getBasePtr();
7411   SDValue Value = SN->getValue();
7412
7413   if (Value.getValueType() == MVT::v4f64 ||
7414       Value.getValueType() == MVT::v4f32) {
7415     EVT MemVT = SN->getMemoryVT();
7416     unsigned Alignment = SN->getAlignment();
7417
7418     // If this store is properly aligned, then it is legal.
7419     if (Alignment >= MemVT.getStoreSize())
7420       return Op;
7421
7422     EVT ScalarVT = Value.getValueType().getScalarType(),
7423         ScalarMemVT = MemVT.getScalarType();
7424     unsigned Stride = ScalarMemVT.getStoreSize();
7425
7426     SmallVector<SDValue, 8> Stores;
7427     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7428       SDValue Ex =
7429         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7430                     DAG.getConstant(Idx, getVectorIdxTy()));
7431       SDValue Store;
7432       if (ScalarVT != ScalarMemVT)
7433         Store =
7434           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7435                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7436                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7437                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7438       else
7439         Store =
7440           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7441                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7442                        SN->isVolatile(), SN->isNonTemporal(),
7443                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7444
7445       if (Idx == 0 && SN->isIndexed()) {
7446         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7447                "Unknown addressing mode on vector store");
7448         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7449                                     SN->getAddressingMode());
7450       }
7451
7452       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7453                             DAG.getConstant(Stride, BasePtr.getValueType()));
7454       Stores.push_back(Store);
7455     }
7456
7457     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7458
7459     if (SN->isIndexed()) {
7460       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7461       return DAG.getMergeValues(RetOps, dl);
7462     }
7463
7464     return TF;
7465   }
7466
7467   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7468   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7469
7470   // The values are now known to be -1 (false) or 1 (true). To convert this
7471   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7472   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7473   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7474
7475   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7476   // understand how to form the extending load.
7477   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7478   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7479                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7480
7481   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7482
7483   // Now convert to an integer and store.
7484   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7485     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7486     Value);
7487
7488   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7489   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7490   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7491   EVT PtrVT = getPointerTy();
7492   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7493
7494   SmallVector<SDValue, 2> Ops;
7495   Ops.push_back(StoreChain);
7496   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7497   Ops.push_back(Value);
7498   Ops.push_back(FIdx);
7499
7500   SmallVector<EVT, 2> ValueVTs;
7501   ValueVTs.push_back(MVT::Other); // chain
7502   SDVTList VTs = DAG.getVTList(ValueVTs);
7503
7504   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7505     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7506
7507   // Move data into the byte array.
7508   SmallVector<SDValue, 4> Loads, LoadChains;
7509   for (unsigned i = 0; i < 4; ++i) {
7510     unsigned Offset = 4*i;
7511     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7512     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7513
7514     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7515                                    PtrInfo.getWithOffset(Offset),
7516                                    false, false, false, 0));
7517     LoadChains.push_back(Loads[i].getValue(1));
7518   }
7519
7520   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7521
7522   SmallVector<SDValue, 4> Stores;
7523   for (unsigned i = 0; i < 4; ++i) {
7524     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7525     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7526
7527     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7528                                        SN->getPointerInfo().getWithOffset(i),
7529                                        MVT::i8 /* memory type */,
7530                                        SN->isNonTemporal(), SN->isVolatile(), 
7531                                        1 /* alignment */, SN->getAAInfo()));
7532   }
7533
7534   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7535
7536   return StoreChain;
7537 }
7538
7539 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7540   SDLoc dl(Op);
7541   if (Op.getValueType() == MVT::v4i32) {
7542     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7543
7544     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7545     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7546
7547     SDValue RHSSwap =   // = vrlw RHS, 16
7548       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7549
7550     // Shrinkify inputs to v8i16.
7551     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7552     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7553     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7554
7555     // Low parts multiplied together, generating 32-bit results (we ignore the
7556     // top parts).
7557     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7558                                         LHS, RHS, DAG, dl, MVT::v4i32);
7559
7560     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7561                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7562     // Shift the high parts up 16 bits.
7563     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7564                               Neg16, DAG, dl);
7565     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7566   } else if (Op.getValueType() == MVT::v8i16) {
7567     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7568
7569     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7570
7571     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7572                             LHS, RHS, Zero, DAG, dl);
7573   } else if (Op.getValueType() == MVT::v16i8) {
7574     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7575     bool isLittleEndian = Subtarget.isLittleEndian();
7576
7577     // Multiply the even 8-bit parts, producing 16-bit sums.
7578     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7579                                            LHS, RHS, DAG, dl, MVT::v8i16);
7580     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7581
7582     // Multiply the odd 8-bit parts, producing 16-bit sums.
7583     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7584                                           LHS, RHS, DAG, dl, MVT::v8i16);
7585     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7586
7587     // Merge the results together.  Because vmuleub and vmuloub are
7588     // instructions with a big-endian bias, we must reverse the
7589     // element numbering and reverse the meaning of "odd" and "even"
7590     // when generating little endian code.
7591     int Ops[16];
7592     for (unsigned i = 0; i != 8; ++i) {
7593       if (isLittleEndian) {
7594         Ops[i*2  ] = 2*i;
7595         Ops[i*2+1] = 2*i+16;
7596       } else {
7597         Ops[i*2  ] = 2*i+1;
7598         Ops[i*2+1] = 2*i+1+16;
7599       }
7600     }
7601     if (isLittleEndian)
7602       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7603     else
7604       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7605   } else {
7606     llvm_unreachable("Unknown mul to lower!");
7607   }
7608 }
7609
7610 /// LowerOperation - Provide custom lowering hooks for some operations.
7611 ///
7612 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7613   switch (Op.getOpcode()) {
7614   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7615   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7616   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7617   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7618   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7619   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7620   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7621   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7622   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7623   case ISD::VASTART:
7624     return LowerVASTART(Op, DAG, Subtarget);
7625
7626   case ISD::VAARG:
7627     return LowerVAARG(Op, DAG, Subtarget);
7628
7629   case ISD::VACOPY:
7630     return LowerVACOPY(Op, DAG, Subtarget);
7631
7632   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7633   case ISD::DYNAMIC_STACKALLOC:
7634     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7635
7636   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7637   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7638
7639   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7640   case ISD::STORE:              return LowerSTORE(Op, DAG);
7641   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7642   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7643   case ISD::FP_TO_UINT:
7644   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7645                                                       SDLoc(Op));
7646   case ISD::UINT_TO_FP:
7647   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7648   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7649
7650   // Lower 64-bit shifts.
7651   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7652   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7653   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7654
7655   // Vector-related lowering.
7656   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7657   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7658   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7659   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7660   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7661   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7662   case ISD::MUL:                return LowerMUL(Op, DAG);
7663
7664   // For counter-based loop handling.
7665   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7666
7667   // Frame & Return address.
7668   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7669   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7670   }
7671 }
7672
7673 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7674                                            SmallVectorImpl<SDValue>&Results,
7675                                            SelectionDAG &DAG) const {
7676   SDLoc dl(N);
7677   switch (N->getOpcode()) {
7678   default:
7679     llvm_unreachable("Do not know how to custom type legalize this operation!");
7680   case ISD::READCYCLECOUNTER: {
7681     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7682     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7683
7684     Results.push_back(RTB);
7685     Results.push_back(RTB.getValue(1));
7686     Results.push_back(RTB.getValue(2));
7687     break;
7688   }
7689   case ISD::INTRINSIC_W_CHAIN: {
7690     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7691         Intrinsic::ppc_is_decremented_ctr_nonzero)
7692       break;
7693
7694     assert(N->getValueType(0) == MVT::i1 &&
7695            "Unexpected result type for CTR decrement intrinsic");
7696     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7697     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7698     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7699                                  N->getOperand(1)); 
7700
7701     Results.push_back(NewInt);
7702     Results.push_back(NewInt.getValue(1));
7703     break;
7704   }
7705   case ISD::VAARG: {
7706     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7707       return;
7708
7709     EVT VT = N->getValueType(0);
7710
7711     if (VT == MVT::i64) {
7712       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7713
7714       Results.push_back(NewNode);
7715       Results.push_back(NewNode.getValue(1));
7716     }
7717     return;
7718   }
7719   case ISD::FP_ROUND_INREG: {
7720     assert(N->getValueType(0) == MVT::ppcf128);
7721     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7722     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7723                              MVT::f64, N->getOperand(0),
7724                              DAG.getIntPtrConstant(0));
7725     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7726                              MVT::f64, N->getOperand(0),
7727                              DAG.getIntPtrConstant(1));
7728
7729     // Add the two halves of the long double in round-to-zero mode.
7730     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7731
7732     // We know the low half is about to be thrown away, so just use something
7733     // convenient.
7734     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7735                                 FPreg, FPreg));
7736     return;
7737   }
7738   case ISD::FP_TO_SINT:
7739     // LowerFP_TO_INT() can only handle f32 and f64.
7740     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7741       return;
7742     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7743     return;
7744   }
7745 }
7746
7747
7748 //===----------------------------------------------------------------------===//
7749 //  Other Lowering Code
7750 //===----------------------------------------------------------------------===//
7751
7752 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7753   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7754   Function *Func = Intrinsic::getDeclaration(M, Id);
7755   return Builder.CreateCall(Func);
7756 }
7757
7758 // The mappings for emitLeading/TrailingFence is taken from
7759 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7760 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7761                                          AtomicOrdering Ord, bool IsStore,
7762                                          bool IsLoad) const {
7763   if (Ord == SequentiallyConsistent)
7764     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7765   else if (isAtLeastRelease(Ord))
7766     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7767   else
7768     return nullptr;
7769 }
7770
7771 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7772                                           AtomicOrdering Ord, bool IsStore,
7773                                           bool IsLoad) const {
7774   if (IsLoad && isAtLeastAcquire(Ord))
7775     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7776   // FIXME: this is too conservative, a dependent branch + isync is enough.
7777   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7778   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7779   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7780   else
7781     return nullptr;
7782 }
7783
7784 MachineBasicBlock *
7785 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7786                                     bool is64bit, unsigned BinOpcode) const {
7787   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7788   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7789
7790   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7791   MachineFunction *F = BB->getParent();
7792   MachineFunction::iterator It = BB;
7793   ++It;
7794
7795   unsigned dest = MI->getOperand(0).getReg();
7796   unsigned ptrA = MI->getOperand(1).getReg();
7797   unsigned ptrB = MI->getOperand(2).getReg();
7798   unsigned incr = MI->getOperand(3).getReg();
7799   DebugLoc dl = MI->getDebugLoc();
7800
7801   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7802   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7803   F->insert(It, loopMBB);
7804   F->insert(It, exitMBB);
7805   exitMBB->splice(exitMBB->begin(), BB,
7806                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7807   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7808
7809   MachineRegisterInfo &RegInfo = F->getRegInfo();
7810   unsigned TmpReg = (!BinOpcode) ? incr :
7811     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
7812                                            : &PPC::GPRCRegClass);
7813
7814   //  thisMBB:
7815   //   ...
7816   //   fallthrough --> loopMBB
7817   BB->addSuccessor(loopMBB);
7818
7819   //  loopMBB:
7820   //   l[wd]arx dest, ptr
7821   //   add r0, dest, incr
7822   //   st[wd]cx. r0, ptr
7823   //   bne- loopMBB
7824   //   fallthrough --> exitMBB
7825   BB = loopMBB;
7826   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7827     .addReg(ptrA).addReg(ptrB);
7828   if (BinOpcode)
7829     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7830   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7831     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7832   BuildMI(BB, dl, TII->get(PPC::BCC))
7833     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7834   BB->addSuccessor(loopMBB);
7835   BB->addSuccessor(exitMBB);
7836
7837   //  exitMBB:
7838   //   ...
7839   BB = exitMBB;
7840   return BB;
7841 }
7842
7843 MachineBasicBlock *
7844 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7845                                             MachineBasicBlock *BB,
7846                                             bool is8bit,    // operation
7847                                             unsigned BinOpcode) const {
7848   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7849   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7850   // In 64 bit mode we have to use 64 bits for addresses, even though the
7851   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7852   // registers without caring whether they're 32 or 64, but here we're
7853   // doing actual arithmetic on the addresses.
7854   bool is64bit = Subtarget.isPPC64();
7855   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7856
7857   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7858   MachineFunction *F = BB->getParent();
7859   MachineFunction::iterator It = BB;
7860   ++It;
7861
7862   unsigned dest = MI->getOperand(0).getReg();
7863   unsigned ptrA = MI->getOperand(1).getReg();
7864   unsigned ptrB = MI->getOperand(2).getReg();
7865   unsigned incr = MI->getOperand(3).getReg();
7866   DebugLoc dl = MI->getDebugLoc();
7867
7868   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7869   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7870   F->insert(It, loopMBB);
7871   F->insert(It, exitMBB);
7872   exitMBB->splice(exitMBB->begin(), BB,
7873                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7874   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7875
7876   MachineRegisterInfo &RegInfo = F->getRegInfo();
7877   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7878                                           : &PPC::GPRCRegClass;
7879   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7880   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7881   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7882   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7883   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7884   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7885   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7886   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7887   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7888   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7889   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7890   unsigned Ptr1Reg;
7891   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7892
7893   //  thisMBB:
7894   //   ...
7895   //   fallthrough --> loopMBB
7896   BB->addSuccessor(loopMBB);
7897
7898   // The 4-byte load must be aligned, while a char or short may be
7899   // anywhere in the word.  Hence all this nasty bookkeeping code.
7900   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7901   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7902   //   xori shift, shift1, 24 [16]
7903   //   rlwinm ptr, ptr1, 0, 0, 29
7904   //   slw incr2, incr, shift
7905   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7906   //   slw mask, mask2, shift
7907   //  loopMBB:
7908   //   lwarx tmpDest, ptr
7909   //   add tmp, tmpDest, incr2
7910   //   andc tmp2, tmpDest, mask
7911   //   and tmp3, tmp, mask
7912   //   or tmp4, tmp3, tmp2
7913   //   stwcx. tmp4, ptr
7914   //   bne- loopMBB
7915   //   fallthrough --> exitMBB
7916   //   srw dest, tmpDest, shift
7917   if (ptrA != ZeroReg) {
7918     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7919     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7920       .addReg(ptrA).addReg(ptrB);
7921   } else {
7922     Ptr1Reg = ptrB;
7923   }
7924   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7925       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7926   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7927       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7928   if (is64bit)
7929     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7930       .addReg(Ptr1Reg).addImm(0).addImm(61);
7931   else
7932     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7933       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7934   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7935       .addReg(incr).addReg(ShiftReg);
7936   if (is8bit)
7937     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7938   else {
7939     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7940     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7941   }
7942   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7943       .addReg(Mask2Reg).addReg(ShiftReg);
7944
7945   BB = loopMBB;
7946   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7947     .addReg(ZeroReg).addReg(PtrReg);
7948   if (BinOpcode)
7949     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7950       .addReg(Incr2Reg).addReg(TmpDestReg);
7951   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7952     .addReg(TmpDestReg).addReg(MaskReg);
7953   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7954     .addReg(TmpReg).addReg(MaskReg);
7955   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7956     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7957   BuildMI(BB, dl, TII->get(PPC::STWCX))
7958     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7959   BuildMI(BB, dl, TII->get(PPC::BCC))
7960     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7961   BB->addSuccessor(loopMBB);
7962   BB->addSuccessor(exitMBB);
7963
7964   //  exitMBB:
7965   //   ...
7966   BB = exitMBB;
7967   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7968     .addReg(ShiftReg);
7969   return BB;
7970 }
7971
7972 llvm::MachineBasicBlock*
7973 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7974                                     MachineBasicBlock *MBB) const {
7975   DebugLoc DL = MI->getDebugLoc();
7976   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7977
7978   MachineFunction *MF = MBB->getParent();
7979   MachineRegisterInfo &MRI = MF->getRegInfo();
7980
7981   const BasicBlock *BB = MBB->getBasicBlock();
7982   MachineFunction::iterator I = MBB;
7983   ++I;
7984
7985   // Memory Reference
7986   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7987   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7988
7989   unsigned DstReg = MI->getOperand(0).getReg();
7990   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7991   assert(RC->hasType(MVT::i32) && "Invalid destination!");
7992   unsigned mainDstReg = MRI.createVirtualRegister(RC);
7993   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7994
7995   MVT PVT = getPointerTy();
7996   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7997          "Invalid Pointer Size!");
7998   // For v = setjmp(buf), we generate
7999   //
8000   // thisMBB:
8001   //  SjLjSetup mainMBB
8002   //  bl mainMBB
8003   //  v_restore = 1
8004   //  b sinkMBB
8005   //
8006   // mainMBB:
8007   //  buf[LabelOffset] = LR
8008   //  v_main = 0
8009   //
8010   // sinkMBB:
8011   //  v = phi(main, restore)
8012   //
8013
8014   MachineBasicBlock *thisMBB = MBB;
8015   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8016   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8017   MF->insert(I, mainMBB);
8018   MF->insert(I, sinkMBB);
8019
8020   MachineInstrBuilder MIB;
8021
8022   // Transfer the remainder of BB and its successor edges to sinkMBB.
8023   sinkMBB->splice(sinkMBB->begin(), MBB,
8024                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8025   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8026
8027   // Note that the structure of the jmp_buf used here is not compatible
8028   // with that used by libc, and is not designed to be. Specifically, it
8029   // stores only those 'reserved' registers that LLVM does not otherwise
8030   // understand how to spill. Also, by convention, by the time this
8031   // intrinsic is called, Clang has already stored the frame address in the
8032   // first slot of the buffer and stack address in the third. Following the
8033   // X86 target code, we'll store the jump address in the second slot. We also
8034   // need to save the TOC pointer (R2) to handle jumps between shared
8035   // libraries, and that will be stored in the fourth slot. The thread
8036   // identifier (R13) is not affected.
8037
8038   // thisMBB:
8039   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8040   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8041   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8042
8043   // Prepare IP either in reg.
8044   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8045   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8046   unsigned BufReg = MI->getOperand(1).getReg();
8047
8048   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8049     setUsesTOCBasePtr(*MBB->getParent());
8050     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8051             .addReg(PPC::X2)
8052             .addImm(TOCOffset)
8053             .addReg(BufReg);
8054     MIB.setMemRefs(MMOBegin, MMOEnd);
8055   }
8056
8057   // Naked functions never have a base pointer, and so we use r1. For all
8058   // other functions, this decision must be delayed until during PEI.
8059   unsigned BaseReg;
8060   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8061     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8062   else
8063     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8064
8065   MIB = BuildMI(*thisMBB, MI, DL,
8066                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8067             .addReg(BaseReg)
8068             .addImm(BPOffset)
8069             .addReg(BufReg);
8070   MIB.setMemRefs(MMOBegin, MMOEnd);
8071
8072   // Setup
8073   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8074   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8075   MIB.addRegMask(TRI->getNoPreservedMask());
8076
8077   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8078
8079   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8080           .addMBB(mainMBB);
8081   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8082
8083   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8084   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8085
8086   // mainMBB:
8087   //  mainDstReg = 0
8088   MIB =
8089       BuildMI(mainMBB, DL,
8090               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8091
8092   // Store IP
8093   if (Subtarget.isPPC64()) {
8094     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8095             .addReg(LabelReg)
8096             .addImm(LabelOffset)
8097             .addReg(BufReg);
8098   } else {
8099     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8100             .addReg(LabelReg)
8101             .addImm(LabelOffset)
8102             .addReg(BufReg);
8103   }
8104
8105   MIB.setMemRefs(MMOBegin, MMOEnd);
8106
8107   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8108   mainMBB->addSuccessor(sinkMBB);
8109
8110   // sinkMBB:
8111   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8112           TII->get(PPC::PHI), DstReg)
8113     .addReg(mainDstReg).addMBB(mainMBB)
8114     .addReg(restoreDstReg).addMBB(thisMBB);
8115
8116   MI->eraseFromParent();
8117   return sinkMBB;
8118 }
8119
8120 MachineBasicBlock *
8121 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8122                                      MachineBasicBlock *MBB) const {
8123   DebugLoc DL = MI->getDebugLoc();
8124   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8125
8126   MachineFunction *MF = MBB->getParent();
8127   MachineRegisterInfo &MRI = MF->getRegInfo();
8128
8129   // Memory Reference
8130   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8131   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8132
8133   MVT PVT = getPointerTy();
8134   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8135          "Invalid Pointer Size!");
8136
8137   const TargetRegisterClass *RC =
8138     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8139   unsigned Tmp = MRI.createVirtualRegister(RC);
8140   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8141   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8142   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8143   unsigned BP =
8144       (PVT == MVT::i64)
8145           ? PPC::X30
8146           : (Subtarget.isSVR4ABI() &&
8147                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8148                  ? PPC::R29
8149                  : PPC::R30);
8150
8151   MachineInstrBuilder MIB;
8152
8153   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8154   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8155   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8156   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8157
8158   unsigned BufReg = MI->getOperand(0).getReg();
8159
8160   // Reload FP (the jumped-to function may not have had a
8161   // frame pointer, and if so, then its r31 will be restored
8162   // as necessary).
8163   if (PVT == MVT::i64) {
8164     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8165             .addImm(0)
8166             .addReg(BufReg);
8167   } else {
8168     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8169             .addImm(0)
8170             .addReg(BufReg);
8171   }
8172   MIB.setMemRefs(MMOBegin, MMOEnd);
8173
8174   // Reload IP
8175   if (PVT == MVT::i64) {
8176     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8177             .addImm(LabelOffset)
8178             .addReg(BufReg);
8179   } else {
8180     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8181             .addImm(LabelOffset)
8182             .addReg(BufReg);
8183   }
8184   MIB.setMemRefs(MMOBegin, MMOEnd);
8185
8186   // Reload SP
8187   if (PVT == MVT::i64) {
8188     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8189             .addImm(SPOffset)
8190             .addReg(BufReg);
8191   } else {
8192     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8193             .addImm(SPOffset)
8194             .addReg(BufReg);
8195   }
8196   MIB.setMemRefs(MMOBegin, MMOEnd);
8197
8198   // Reload BP
8199   if (PVT == MVT::i64) {
8200     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8201             .addImm(BPOffset)
8202             .addReg(BufReg);
8203   } else {
8204     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8205             .addImm(BPOffset)
8206             .addReg(BufReg);
8207   }
8208   MIB.setMemRefs(MMOBegin, MMOEnd);
8209
8210   // Reload TOC
8211   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8212     setUsesTOCBasePtr(*MBB->getParent());
8213     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8214             .addImm(TOCOffset)
8215             .addReg(BufReg);
8216
8217     MIB.setMemRefs(MMOBegin, MMOEnd);
8218   }
8219
8220   // Jump
8221   BuildMI(*MBB, MI, DL,
8222           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8223   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8224
8225   MI->eraseFromParent();
8226   return MBB;
8227 }
8228
8229 MachineBasicBlock *
8230 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8231                                                MachineBasicBlock *BB) const {
8232   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8233       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8234     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8235         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8236       // Call lowering should have added an r2 operand to indicate a dependence
8237       // on the TOC base pointer value. It can't however, because there is no
8238       // way to mark the dependence as implicit there, and so the stackmap code
8239       // will confuse it with a regular operand. Instead, add the dependence
8240       // here.
8241       setUsesTOCBasePtr(*BB->getParent());
8242       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8243     }
8244
8245     return emitPatchPoint(MI, BB);
8246   }
8247
8248   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8249       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8250     return emitEHSjLjSetJmp(MI, BB);
8251   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8252              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8253     return emitEHSjLjLongJmp(MI, BB);
8254   }
8255
8256   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8257
8258   // To "insert" these instructions we actually have to insert their
8259   // control-flow patterns.
8260   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8261   MachineFunction::iterator It = BB;
8262   ++It;
8263
8264   MachineFunction *F = BB->getParent();
8265
8266   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8267                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8268                               MI->getOpcode() == PPC::SELECT_I4 ||
8269                               MI->getOpcode() == PPC::SELECT_I8)) {
8270     SmallVector<MachineOperand, 2> Cond;
8271     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8272         MI->getOpcode() == PPC::SELECT_CC_I8)
8273       Cond.push_back(MI->getOperand(4));
8274     else
8275       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8276     Cond.push_back(MI->getOperand(1));
8277
8278     DebugLoc dl = MI->getDebugLoc();
8279     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8280                       Cond, MI->getOperand(2).getReg(),
8281                       MI->getOperand(3).getReg());
8282   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8283              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8284              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8285              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8286              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8287              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8288              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8289              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8290              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8291              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8292              MI->getOpcode() == PPC::SELECT_I4 ||
8293              MI->getOpcode() == PPC::SELECT_I8 ||
8294              MI->getOpcode() == PPC::SELECT_F4 ||
8295              MI->getOpcode() == PPC::SELECT_F8 ||
8296              MI->getOpcode() == PPC::SELECT_QFRC ||
8297              MI->getOpcode() == PPC::SELECT_QSRC ||
8298              MI->getOpcode() == PPC::SELECT_QBRC ||
8299              MI->getOpcode() == PPC::SELECT_VRRC ||
8300              MI->getOpcode() == PPC::SELECT_VSFRC ||
8301              MI->getOpcode() == PPC::SELECT_VSRC) {
8302     // The incoming instruction knows the destination vreg to set, the
8303     // condition code register to branch on, the true/false values to
8304     // select between, and a branch opcode to use.
8305
8306     //  thisMBB:
8307     //  ...
8308     //   TrueVal = ...
8309     //   cmpTY ccX, r1, r2
8310     //   bCC copy1MBB
8311     //   fallthrough --> copy0MBB
8312     MachineBasicBlock *thisMBB = BB;
8313     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8314     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8315     DebugLoc dl = MI->getDebugLoc();
8316     F->insert(It, copy0MBB);
8317     F->insert(It, sinkMBB);
8318
8319     // Transfer the remainder of BB and its successor edges to sinkMBB.
8320     sinkMBB->splice(sinkMBB->begin(), BB,
8321                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8322     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8323
8324     // Next, add the true and fallthrough blocks as its successors.
8325     BB->addSuccessor(copy0MBB);
8326     BB->addSuccessor(sinkMBB);
8327
8328     if (MI->getOpcode() == PPC::SELECT_I4 ||
8329         MI->getOpcode() == PPC::SELECT_I8 ||
8330         MI->getOpcode() == PPC::SELECT_F4 ||
8331         MI->getOpcode() == PPC::SELECT_F8 ||
8332         MI->getOpcode() == PPC::SELECT_QFRC ||
8333         MI->getOpcode() == PPC::SELECT_QSRC ||
8334         MI->getOpcode() == PPC::SELECT_QBRC ||
8335         MI->getOpcode() == PPC::SELECT_VRRC ||
8336         MI->getOpcode() == PPC::SELECT_VSFRC ||
8337         MI->getOpcode() == PPC::SELECT_VSRC) {
8338       BuildMI(BB, dl, TII->get(PPC::BC))
8339         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8340     } else {
8341       unsigned SelectPred = MI->getOperand(4).getImm();
8342       BuildMI(BB, dl, TII->get(PPC::BCC))
8343         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8344     }
8345
8346     //  copy0MBB:
8347     //   %FalseValue = ...
8348     //   # fallthrough to sinkMBB
8349     BB = copy0MBB;
8350
8351     // Update machine-CFG edges
8352     BB->addSuccessor(sinkMBB);
8353
8354     //  sinkMBB:
8355     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8356     //  ...
8357     BB = sinkMBB;
8358     BuildMI(*BB, BB->begin(), dl,
8359             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8360       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8361       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8362   } else if (MI->getOpcode() == PPC::ReadTB) {
8363     // To read the 64-bit time-base register on a 32-bit target, we read the
8364     // two halves. Should the counter have wrapped while it was being read, we
8365     // need to try again.
8366     // ...
8367     // readLoop:
8368     // mfspr Rx,TBU # load from TBU
8369     // mfspr Ry,TB  # load from TB
8370     // mfspr Rz,TBU # load from TBU
8371     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8372     // bne readLoop   # branch if they're not equal
8373     // ...
8374
8375     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8376     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8377     DebugLoc dl = MI->getDebugLoc();
8378     F->insert(It, readMBB);
8379     F->insert(It, sinkMBB);
8380
8381     // Transfer the remainder of BB and its successor edges to sinkMBB.
8382     sinkMBB->splice(sinkMBB->begin(), BB,
8383                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8384     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8385
8386     BB->addSuccessor(readMBB);
8387     BB = readMBB;
8388
8389     MachineRegisterInfo &RegInfo = F->getRegInfo();
8390     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8391     unsigned LoReg = MI->getOperand(0).getReg();
8392     unsigned HiReg = MI->getOperand(1).getReg();
8393
8394     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8395     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8396     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8397
8398     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8399
8400     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8401       .addReg(HiReg).addReg(ReadAgainReg);
8402     BuildMI(BB, dl, TII->get(PPC::BCC))
8403       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8404
8405     BB->addSuccessor(readMBB);
8406     BB->addSuccessor(sinkMBB);
8407   }
8408   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8409     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8410   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8411     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8412   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8413     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
8414   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8415     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
8416
8417   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8418     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8419   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8420     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8421   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8422     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
8423   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8424     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
8425
8426   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8427     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8428   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8429     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8430   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8431     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
8432   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8433     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
8434
8435   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8436     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8437   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8438     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8439   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8440     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
8441   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8442     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
8443
8444   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8445     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8446   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8447     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8448   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8449     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
8450   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8451     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
8452
8453   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8454     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8455   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8456     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8457   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8458     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
8459   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8460     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
8461
8462   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8463     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8464   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8465     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8466   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8467     BB = EmitAtomicBinary(MI, BB, false, 0);
8468   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8469     BB = EmitAtomicBinary(MI, BB, true, 0);
8470
8471   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8472            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
8473     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8474
8475     unsigned dest   = MI->getOperand(0).getReg();
8476     unsigned ptrA   = MI->getOperand(1).getReg();
8477     unsigned ptrB   = MI->getOperand(2).getReg();
8478     unsigned oldval = MI->getOperand(3).getReg();
8479     unsigned newval = MI->getOperand(4).getReg();
8480     DebugLoc dl     = MI->getDebugLoc();
8481
8482     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8483     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8484     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8485     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8486     F->insert(It, loop1MBB);
8487     F->insert(It, loop2MBB);
8488     F->insert(It, midMBB);
8489     F->insert(It, exitMBB);
8490     exitMBB->splice(exitMBB->begin(), BB,
8491                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8492     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8493
8494     //  thisMBB:
8495     //   ...
8496     //   fallthrough --> loopMBB
8497     BB->addSuccessor(loop1MBB);
8498
8499     // loop1MBB:
8500     //   l[wd]arx dest, ptr
8501     //   cmp[wd] dest, oldval
8502     //   bne- midMBB
8503     // loop2MBB:
8504     //   st[wd]cx. newval, ptr
8505     //   bne- loopMBB
8506     //   b exitBB
8507     // midMBB:
8508     //   st[wd]cx. dest, ptr
8509     // exitBB:
8510     BB = loop1MBB;
8511     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
8512       .addReg(ptrA).addReg(ptrB);
8513     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8514       .addReg(oldval).addReg(dest);
8515     BuildMI(BB, dl, TII->get(PPC::BCC))
8516       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8517     BB->addSuccessor(loop2MBB);
8518     BB->addSuccessor(midMBB);
8519
8520     BB = loop2MBB;
8521     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8522       .addReg(newval).addReg(ptrA).addReg(ptrB);
8523     BuildMI(BB, dl, TII->get(PPC::BCC))
8524       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8525     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8526     BB->addSuccessor(loop1MBB);
8527     BB->addSuccessor(exitMBB);
8528
8529     BB = midMBB;
8530     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8531       .addReg(dest).addReg(ptrA).addReg(ptrB);
8532     BB->addSuccessor(exitMBB);
8533
8534     //  exitMBB:
8535     //   ...
8536     BB = exitMBB;
8537   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8538              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8539     // We must use 64-bit registers for addresses when targeting 64-bit,
8540     // since we're actually doing arithmetic on them.  Other registers
8541     // can be 32-bit.
8542     bool is64bit = Subtarget.isPPC64();
8543     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8544
8545     unsigned dest   = MI->getOperand(0).getReg();
8546     unsigned ptrA   = MI->getOperand(1).getReg();
8547     unsigned ptrB   = MI->getOperand(2).getReg();
8548     unsigned oldval = MI->getOperand(3).getReg();
8549     unsigned newval = MI->getOperand(4).getReg();
8550     DebugLoc dl     = MI->getDebugLoc();
8551
8552     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8553     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8554     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8555     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8556     F->insert(It, loop1MBB);
8557     F->insert(It, loop2MBB);
8558     F->insert(It, midMBB);
8559     F->insert(It, exitMBB);
8560     exitMBB->splice(exitMBB->begin(), BB,
8561                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8562     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8563
8564     MachineRegisterInfo &RegInfo = F->getRegInfo();
8565     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8566                                             : &PPC::GPRCRegClass;
8567     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8568     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8569     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8570     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8571     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8572     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8573     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8574     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8575     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8576     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8577     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8578     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8579     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8580     unsigned Ptr1Reg;
8581     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8582     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8583     //  thisMBB:
8584     //   ...
8585     //   fallthrough --> loopMBB
8586     BB->addSuccessor(loop1MBB);
8587
8588     // The 4-byte load must be aligned, while a char or short may be
8589     // anywhere in the word.  Hence all this nasty bookkeeping code.
8590     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8591     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8592     //   xori shift, shift1, 24 [16]
8593     //   rlwinm ptr, ptr1, 0, 0, 29
8594     //   slw newval2, newval, shift
8595     //   slw oldval2, oldval,shift
8596     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8597     //   slw mask, mask2, shift
8598     //   and newval3, newval2, mask
8599     //   and oldval3, oldval2, mask
8600     // loop1MBB:
8601     //   lwarx tmpDest, ptr
8602     //   and tmp, tmpDest, mask
8603     //   cmpw tmp, oldval3
8604     //   bne- midMBB
8605     // loop2MBB:
8606     //   andc tmp2, tmpDest, mask
8607     //   or tmp4, tmp2, newval3
8608     //   stwcx. tmp4, ptr
8609     //   bne- loop1MBB
8610     //   b exitBB
8611     // midMBB:
8612     //   stwcx. tmpDest, ptr
8613     // exitBB:
8614     //   srw dest, tmpDest, shift
8615     if (ptrA != ZeroReg) {
8616       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8617       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8618         .addReg(ptrA).addReg(ptrB);
8619     } else {
8620       Ptr1Reg = ptrB;
8621     }
8622     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8623         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8624     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8625         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8626     if (is64bit)
8627       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8628         .addReg(Ptr1Reg).addImm(0).addImm(61);
8629     else
8630       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8631         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8632     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8633         .addReg(newval).addReg(ShiftReg);
8634     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8635         .addReg(oldval).addReg(ShiftReg);
8636     if (is8bit)
8637       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8638     else {
8639       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8640       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8641         .addReg(Mask3Reg).addImm(65535);
8642     }
8643     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8644         .addReg(Mask2Reg).addReg(ShiftReg);
8645     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8646         .addReg(NewVal2Reg).addReg(MaskReg);
8647     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8648         .addReg(OldVal2Reg).addReg(MaskReg);
8649
8650     BB = loop1MBB;
8651     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8652         .addReg(ZeroReg).addReg(PtrReg);
8653     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8654         .addReg(TmpDestReg).addReg(MaskReg);
8655     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8656         .addReg(TmpReg).addReg(OldVal3Reg);
8657     BuildMI(BB, dl, TII->get(PPC::BCC))
8658         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8659     BB->addSuccessor(loop2MBB);
8660     BB->addSuccessor(midMBB);
8661
8662     BB = loop2MBB;
8663     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8664         .addReg(TmpDestReg).addReg(MaskReg);
8665     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8666         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8667     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8668         .addReg(ZeroReg).addReg(PtrReg);
8669     BuildMI(BB, dl, TII->get(PPC::BCC))
8670       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8671     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8672     BB->addSuccessor(loop1MBB);
8673     BB->addSuccessor(exitMBB);
8674
8675     BB = midMBB;
8676     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8677       .addReg(ZeroReg).addReg(PtrReg);
8678     BB->addSuccessor(exitMBB);
8679
8680     //  exitMBB:
8681     //   ...
8682     BB = exitMBB;
8683     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8684       .addReg(ShiftReg);
8685   } else if (MI->getOpcode() == PPC::FADDrtz) {
8686     // This pseudo performs an FADD with rounding mode temporarily forced
8687     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8688     // is not modeled at the SelectionDAG level.
8689     unsigned Dest = MI->getOperand(0).getReg();
8690     unsigned Src1 = MI->getOperand(1).getReg();
8691     unsigned Src2 = MI->getOperand(2).getReg();
8692     DebugLoc dl   = MI->getDebugLoc();
8693
8694     MachineRegisterInfo &RegInfo = F->getRegInfo();
8695     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8696
8697     // Save FPSCR value.
8698     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8699
8700     // Set rounding mode to round-to-zero.
8701     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8702     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8703
8704     // Perform addition.
8705     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8706
8707     // Restore FPSCR value.
8708     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8709   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8710              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8711              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8712              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8713     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8714                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8715                       PPC::ANDIo8 : PPC::ANDIo;
8716     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8717                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8718
8719     MachineRegisterInfo &RegInfo = F->getRegInfo();
8720     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8721                                                   &PPC::GPRCRegClass :
8722                                                   &PPC::G8RCRegClass);
8723
8724     DebugLoc dl   = MI->getDebugLoc();
8725     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8726       .addReg(MI->getOperand(1).getReg()).addImm(1);
8727     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8728             MI->getOperand(0).getReg())
8729       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8730   } else {
8731     llvm_unreachable("Unexpected instr type to insert");
8732   }
8733
8734   MI->eraseFromParent();   // The pseudo instruction is gone now.
8735   return BB;
8736 }
8737
8738 //===----------------------------------------------------------------------===//
8739 // Target Optimization Hooks
8740 //===----------------------------------------------------------------------===//
8741
8742 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8743                                             DAGCombinerInfo &DCI,
8744                                             unsigned &RefinementSteps,
8745                                             bool &UseOneConstNR) const {
8746   EVT VT = Operand.getValueType();
8747   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8748       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8749       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8750       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8751       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8752       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8753     // Convergence is quadratic, so we essentially double the number of digits
8754     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8755     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8756     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8757     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8758     if (VT.getScalarType() == MVT::f64)
8759       ++RefinementSteps;
8760     UseOneConstNR = true;
8761     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8762   }
8763   return SDValue();
8764 }
8765
8766 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8767                                             DAGCombinerInfo &DCI,
8768                                             unsigned &RefinementSteps) const {
8769   EVT VT = Operand.getValueType();
8770   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8771       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8772       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8773       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8774       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8775       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8776     // Convergence is quadratic, so we essentially double the number of digits
8777     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8778     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8779     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8780     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8781     if (VT.getScalarType() == MVT::f64)
8782       ++RefinementSteps;
8783     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8784   }
8785   return SDValue();
8786 }
8787
8788 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8789   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8790   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8791   // enabled for division), this functionality is redundant with the default
8792   // combiner logic (once the division -> reciprocal/multiply transformation
8793   // has taken place). As a result, this matters more for older cores than for
8794   // newer ones.
8795
8796   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8797   // reciprocal if there are two or more FDIVs (for embedded cores with only
8798   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8799   switch (Subtarget.getDarwinDirective()) {
8800   default:
8801     return NumUsers > 2;
8802   case PPC::DIR_440:
8803   case PPC::DIR_A2:
8804   case PPC::DIR_E500mc:
8805   case PPC::DIR_E5500:
8806     return NumUsers > 1;
8807   }
8808 }
8809
8810 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8811                             unsigned Bytes, int Dist,
8812                             SelectionDAG &DAG) {
8813   if (VT.getSizeInBits() / 8 != Bytes)
8814     return false;
8815
8816   SDValue BaseLoc = Base->getBasePtr();
8817   if (Loc.getOpcode() == ISD::FrameIndex) {
8818     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8819       return false;
8820     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8821     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8822     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8823     int FS  = MFI->getObjectSize(FI);
8824     int BFS = MFI->getObjectSize(BFI);
8825     if (FS != BFS || FS != (int)Bytes) return false;
8826     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8827   }
8828
8829   // Handle X+C
8830   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8831       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8832     return true;
8833
8834   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8835   const GlobalValue *GV1 = nullptr;
8836   const GlobalValue *GV2 = nullptr;
8837   int64_t Offset1 = 0;
8838   int64_t Offset2 = 0;
8839   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8840   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8841   if (isGA1 && isGA2 && GV1 == GV2)
8842     return Offset1 == (Offset2 + Dist*Bytes);
8843   return false;
8844 }
8845
8846 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8847 // not enforce equality of the chain operands.
8848 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8849                             unsigned Bytes, int Dist,
8850                             SelectionDAG &DAG) {
8851   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8852     EVT VT = LS->getMemoryVT();
8853     SDValue Loc = LS->getBasePtr();
8854     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8855   }
8856
8857   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8858     EVT VT;
8859     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8860     default: return false;
8861     case Intrinsic::ppc_qpx_qvlfd:
8862     case Intrinsic::ppc_qpx_qvlfda:
8863       VT = MVT::v4f64;
8864       break;
8865     case Intrinsic::ppc_qpx_qvlfs:
8866     case Intrinsic::ppc_qpx_qvlfsa:
8867       VT = MVT::v4f32;
8868       break;
8869     case Intrinsic::ppc_qpx_qvlfcd:
8870     case Intrinsic::ppc_qpx_qvlfcda:
8871       VT = MVT::v2f64;
8872       break;
8873     case Intrinsic::ppc_qpx_qvlfcs:
8874     case Intrinsic::ppc_qpx_qvlfcsa:
8875       VT = MVT::v2f32;
8876       break;
8877     case Intrinsic::ppc_qpx_qvlfiwa:
8878     case Intrinsic::ppc_qpx_qvlfiwz:
8879     case Intrinsic::ppc_altivec_lvx:
8880     case Intrinsic::ppc_altivec_lvxl:
8881     case Intrinsic::ppc_vsx_lxvw4x:
8882       VT = MVT::v4i32;
8883       break;
8884     case Intrinsic::ppc_vsx_lxvd2x:
8885       VT = MVT::v2f64;
8886       break;
8887     case Intrinsic::ppc_altivec_lvebx:
8888       VT = MVT::i8;
8889       break;
8890     case Intrinsic::ppc_altivec_lvehx:
8891       VT = MVT::i16;
8892       break;
8893     case Intrinsic::ppc_altivec_lvewx:
8894       VT = MVT::i32;
8895       break;
8896     }
8897
8898     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8899   }
8900
8901   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8902     EVT VT;
8903     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8904     default: return false;
8905     case Intrinsic::ppc_qpx_qvstfd:
8906     case Intrinsic::ppc_qpx_qvstfda:
8907       VT = MVT::v4f64;
8908       break;
8909     case Intrinsic::ppc_qpx_qvstfs:
8910     case Intrinsic::ppc_qpx_qvstfsa:
8911       VT = MVT::v4f32;
8912       break;
8913     case Intrinsic::ppc_qpx_qvstfcd:
8914     case Intrinsic::ppc_qpx_qvstfcda:
8915       VT = MVT::v2f64;
8916       break;
8917     case Intrinsic::ppc_qpx_qvstfcs:
8918     case Intrinsic::ppc_qpx_qvstfcsa:
8919       VT = MVT::v2f32;
8920       break;
8921     case Intrinsic::ppc_qpx_qvstfiw:
8922     case Intrinsic::ppc_qpx_qvstfiwa:
8923     case Intrinsic::ppc_altivec_stvx:
8924     case Intrinsic::ppc_altivec_stvxl:
8925     case Intrinsic::ppc_vsx_stxvw4x:
8926       VT = MVT::v4i32;
8927       break;
8928     case Intrinsic::ppc_vsx_stxvd2x:
8929       VT = MVT::v2f64;
8930       break;
8931     case Intrinsic::ppc_altivec_stvebx:
8932       VT = MVT::i8;
8933       break;
8934     case Intrinsic::ppc_altivec_stvehx:
8935       VT = MVT::i16;
8936       break;
8937     case Intrinsic::ppc_altivec_stvewx:
8938       VT = MVT::i32;
8939       break;
8940     }
8941
8942     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8943   }
8944
8945   return false;
8946 }
8947
8948 // Return true is there is a nearyby consecutive load to the one provided
8949 // (regardless of alignment). We search up and down the chain, looking though
8950 // token factors and other loads (but nothing else). As a result, a true result
8951 // indicates that it is safe to create a new consecutive load adjacent to the
8952 // load provided.
8953 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8954   SDValue Chain = LD->getChain();
8955   EVT VT = LD->getMemoryVT();
8956
8957   SmallSet<SDNode *, 16> LoadRoots;
8958   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8959   SmallSet<SDNode *, 16> Visited;
8960
8961   // First, search up the chain, branching to follow all token-factor operands.
8962   // If we find a consecutive load, then we're done, otherwise, record all
8963   // nodes just above the top-level loads and token factors.
8964   while (!Queue.empty()) {
8965     SDNode *ChainNext = Queue.pop_back_val();
8966     if (!Visited.insert(ChainNext).second)
8967       continue;
8968
8969     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8970       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8971         return true;
8972
8973       if (!Visited.count(ChainLD->getChain().getNode()))
8974         Queue.push_back(ChainLD->getChain().getNode());
8975     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8976       for (const SDUse &O : ChainNext->ops())
8977         if (!Visited.count(O.getNode()))
8978           Queue.push_back(O.getNode());
8979     } else
8980       LoadRoots.insert(ChainNext);
8981   }
8982
8983   // Second, search down the chain, starting from the top-level nodes recorded
8984   // in the first phase. These top-level nodes are the nodes just above all
8985   // loads and token factors. Starting with their uses, recursively look though
8986   // all loads (just the chain uses) and token factors to find a consecutive
8987   // load.
8988   Visited.clear();
8989   Queue.clear();
8990
8991   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8992        IE = LoadRoots.end(); I != IE; ++I) {
8993     Queue.push_back(*I);
8994        
8995     while (!Queue.empty()) {
8996       SDNode *LoadRoot = Queue.pop_back_val();
8997       if (!Visited.insert(LoadRoot).second)
8998         continue;
8999
9000       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9001         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9002           return true;
9003
9004       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9005            UE = LoadRoot->use_end(); UI != UE; ++UI)
9006         if (((isa<MemSDNode>(*UI) &&
9007             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9008             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9009           Queue.push_back(*UI);
9010     }
9011   }
9012
9013   return false;
9014 }
9015
9016 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9017                                                   DAGCombinerInfo &DCI) const {
9018   SelectionDAG &DAG = DCI.DAG;
9019   SDLoc dl(N);
9020
9021   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9022   // If we're tracking CR bits, we need to be careful that we don't have:
9023   //   trunc(binary-ops(zext(x), zext(y)))
9024   // or
9025   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9026   // such that we're unnecessarily moving things into GPRs when it would be
9027   // better to keep them in CR bits.
9028
9029   // Note that trunc here can be an actual i1 trunc, or can be the effective
9030   // truncation that comes from a setcc or select_cc.
9031   if (N->getOpcode() == ISD::TRUNCATE &&
9032       N->getValueType(0) != MVT::i1)
9033     return SDValue();
9034
9035   if (N->getOperand(0).getValueType() != MVT::i32 &&
9036       N->getOperand(0).getValueType() != MVT::i64)
9037     return SDValue();
9038
9039   if (N->getOpcode() == ISD::SETCC ||
9040       N->getOpcode() == ISD::SELECT_CC) {
9041     // If we're looking at a comparison, then we need to make sure that the
9042     // high bits (all except for the first) don't matter the result.
9043     ISD::CondCode CC =
9044       cast<CondCodeSDNode>(N->getOperand(
9045         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9046     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9047
9048     if (ISD::isSignedIntSetCC(CC)) {
9049       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9050           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9051         return SDValue();
9052     } else if (ISD::isUnsignedIntSetCC(CC)) {
9053       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9054                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9055           !DAG.MaskedValueIsZero(N->getOperand(1),
9056                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9057         return SDValue();
9058     } else {
9059       // This is neither a signed nor an unsigned comparison, just make sure
9060       // that the high bits are equal.
9061       APInt Op1Zero, Op1One;
9062       APInt Op2Zero, Op2One;
9063       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9064       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9065
9066       // We don't really care about what is known about the first bit (if
9067       // anything), so clear it in all masks prior to comparing them.
9068       Op1Zero.clearBit(0); Op1One.clearBit(0);
9069       Op2Zero.clearBit(0); Op2One.clearBit(0);
9070
9071       if (Op1Zero != Op2Zero || Op1One != Op2One)
9072         return SDValue();
9073     }
9074   }
9075
9076   // We now know that the higher-order bits are irrelevant, we just need to
9077   // make sure that all of the intermediate operations are bit operations, and
9078   // all inputs are extensions.
9079   if (N->getOperand(0).getOpcode() != ISD::AND &&
9080       N->getOperand(0).getOpcode() != ISD::OR  &&
9081       N->getOperand(0).getOpcode() != ISD::XOR &&
9082       N->getOperand(0).getOpcode() != ISD::SELECT &&
9083       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9084       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9085       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9086       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9087       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9088     return SDValue();
9089
9090   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9091       N->getOperand(1).getOpcode() != ISD::AND &&
9092       N->getOperand(1).getOpcode() != ISD::OR  &&
9093       N->getOperand(1).getOpcode() != ISD::XOR &&
9094       N->getOperand(1).getOpcode() != ISD::SELECT &&
9095       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9096       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9097       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9098       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9099       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9100     return SDValue();
9101
9102   SmallVector<SDValue, 4> Inputs;
9103   SmallVector<SDValue, 8> BinOps, PromOps;
9104   SmallPtrSet<SDNode *, 16> Visited;
9105
9106   for (unsigned i = 0; i < 2; ++i) {
9107     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9108           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9109           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9110           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9111         isa<ConstantSDNode>(N->getOperand(i)))
9112       Inputs.push_back(N->getOperand(i));
9113     else
9114       BinOps.push_back(N->getOperand(i));
9115
9116     if (N->getOpcode() == ISD::TRUNCATE)
9117       break;
9118   }
9119
9120   // Visit all inputs, collect all binary operations (and, or, xor and
9121   // select) that are all fed by extensions. 
9122   while (!BinOps.empty()) {
9123     SDValue BinOp = BinOps.back();
9124     BinOps.pop_back();
9125
9126     if (!Visited.insert(BinOp.getNode()).second)
9127       continue;
9128
9129     PromOps.push_back(BinOp);
9130
9131     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9132       // The condition of the select is not promoted.
9133       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9134         continue;
9135       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9136         continue;
9137
9138       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9139             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9140             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9141            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9142           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9143         Inputs.push_back(BinOp.getOperand(i)); 
9144       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9145                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9146                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9147                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9148                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9149                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9150                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9151                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9152                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9153         BinOps.push_back(BinOp.getOperand(i));
9154       } else {
9155         // We have an input that is not an extension or another binary
9156         // operation; we'll abort this transformation.
9157         return SDValue();
9158       }
9159     }
9160   }
9161
9162   // Make sure that this is a self-contained cluster of operations (which
9163   // is not quite the same thing as saying that everything has only one
9164   // use).
9165   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9166     if (isa<ConstantSDNode>(Inputs[i]))
9167       continue;
9168
9169     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9170                               UE = Inputs[i].getNode()->use_end();
9171          UI != UE; ++UI) {
9172       SDNode *User = *UI;
9173       if (User != N && !Visited.count(User))
9174         return SDValue();
9175
9176       // Make sure that we're not going to promote the non-output-value
9177       // operand(s) or SELECT or SELECT_CC.
9178       // FIXME: Although we could sometimes handle this, and it does occur in
9179       // practice that one of the condition inputs to the select is also one of
9180       // the outputs, we currently can't deal with this.
9181       if (User->getOpcode() == ISD::SELECT) {
9182         if (User->getOperand(0) == Inputs[i])
9183           return SDValue();
9184       } else if (User->getOpcode() == ISD::SELECT_CC) {
9185         if (User->getOperand(0) == Inputs[i] ||
9186             User->getOperand(1) == Inputs[i])
9187           return SDValue();
9188       }
9189     }
9190   }
9191
9192   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9193     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9194                               UE = PromOps[i].getNode()->use_end();
9195          UI != UE; ++UI) {
9196       SDNode *User = *UI;
9197       if (User != N && !Visited.count(User))
9198         return SDValue();
9199
9200       // Make sure that we're not going to promote the non-output-value
9201       // operand(s) or SELECT or SELECT_CC.
9202       // FIXME: Although we could sometimes handle this, and it does occur in
9203       // practice that one of the condition inputs to the select is also one of
9204       // the outputs, we currently can't deal with this.
9205       if (User->getOpcode() == ISD::SELECT) {
9206         if (User->getOperand(0) == PromOps[i])
9207           return SDValue();
9208       } else if (User->getOpcode() == ISD::SELECT_CC) {
9209         if (User->getOperand(0) == PromOps[i] ||
9210             User->getOperand(1) == PromOps[i])
9211           return SDValue();
9212       }
9213     }
9214   }
9215
9216   // Replace all inputs with the extension operand.
9217   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9218     // Constants may have users outside the cluster of to-be-promoted nodes,
9219     // and so we need to replace those as we do the promotions.
9220     if (isa<ConstantSDNode>(Inputs[i]))
9221       continue;
9222     else
9223       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9224   }
9225
9226   // Replace all operations (these are all the same, but have a different
9227   // (i1) return type). DAG.getNode will validate that the types of
9228   // a binary operator match, so go through the list in reverse so that
9229   // we've likely promoted both operands first. Any intermediate truncations or
9230   // extensions disappear.
9231   while (!PromOps.empty()) {
9232     SDValue PromOp = PromOps.back();
9233     PromOps.pop_back();
9234
9235     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9236         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9237         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9238         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9239       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9240           PromOp.getOperand(0).getValueType() != MVT::i1) {
9241         // The operand is not yet ready (see comment below).
9242         PromOps.insert(PromOps.begin(), PromOp);
9243         continue;
9244       }
9245
9246       SDValue RepValue = PromOp.getOperand(0);
9247       if (isa<ConstantSDNode>(RepValue))
9248         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9249
9250       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9251       continue;
9252     }
9253
9254     unsigned C;
9255     switch (PromOp.getOpcode()) {
9256     default:             C = 0; break;
9257     case ISD::SELECT:    C = 1; break;
9258     case ISD::SELECT_CC: C = 2; break;
9259     }
9260
9261     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9262          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9263         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9264          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9265       // The to-be-promoted operands of this node have not yet been
9266       // promoted (this should be rare because we're going through the
9267       // list backward, but if one of the operands has several users in
9268       // this cluster of to-be-promoted nodes, it is possible).
9269       PromOps.insert(PromOps.begin(), PromOp);
9270       continue;
9271     }
9272
9273     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9274                                 PromOp.getNode()->op_end());
9275
9276     // If there are any constant inputs, make sure they're replaced now.
9277     for (unsigned i = 0; i < 2; ++i)
9278       if (isa<ConstantSDNode>(Ops[C+i]))
9279         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9280
9281     DAG.ReplaceAllUsesOfValueWith(PromOp,
9282       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9283   }
9284
9285   // Now we're left with the initial truncation itself.
9286   if (N->getOpcode() == ISD::TRUNCATE)
9287     return N->getOperand(0);
9288
9289   // Otherwise, this is a comparison. The operands to be compared have just
9290   // changed type (to i1), but everything else is the same.
9291   return SDValue(N, 0);
9292 }
9293
9294 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9295                                                   DAGCombinerInfo &DCI) const {
9296   SelectionDAG &DAG = DCI.DAG;
9297   SDLoc dl(N);
9298
9299   // If we're tracking CR bits, we need to be careful that we don't have:
9300   //   zext(binary-ops(trunc(x), trunc(y)))
9301   // or
9302   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9303   // such that we're unnecessarily moving things into CR bits that can more
9304   // efficiently stay in GPRs. Note that if we're not certain that the high
9305   // bits are set as required by the final extension, we still may need to do
9306   // some masking to get the proper behavior.
9307
9308   // This same functionality is important on PPC64 when dealing with
9309   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9310   // the return values of functions. Because it is so similar, it is handled
9311   // here as well.
9312
9313   if (N->getValueType(0) != MVT::i32 &&
9314       N->getValueType(0) != MVT::i64)
9315     return SDValue();
9316
9317   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9318         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9319     return SDValue();
9320
9321   if (N->getOperand(0).getOpcode() != ISD::AND &&
9322       N->getOperand(0).getOpcode() != ISD::OR  &&
9323       N->getOperand(0).getOpcode() != ISD::XOR &&
9324       N->getOperand(0).getOpcode() != ISD::SELECT &&
9325       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9326     return SDValue();
9327
9328   SmallVector<SDValue, 4> Inputs;
9329   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9330   SmallPtrSet<SDNode *, 16> Visited;
9331
9332   // Visit all inputs, collect all binary operations (and, or, xor and
9333   // select) that are all fed by truncations. 
9334   while (!BinOps.empty()) {
9335     SDValue BinOp = BinOps.back();
9336     BinOps.pop_back();
9337
9338     if (!Visited.insert(BinOp.getNode()).second)
9339       continue;
9340
9341     PromOps.push_back(BinOp);
9342
9343     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9344       // The condition of the select is not promoted.
9345       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9346         continue;
9347       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9348         continue;
9349
9350       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9351           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9352         Inputs.push_back(BinOp.getOperand(i)); 
9353       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9354                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9355                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9356                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9357                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9358         BinOps.push_back(BinOp.getOperand(i));
9359       } else {
9360         // We have an input that is not a truncation or another binary
9361         // operation; we'll abort this transformation.
9362         return SDValue();
9363       }
9364     }
9365   }
9366
9367   // The operands of a select that must be truncated when the select is
9368   // promoted because the operand is actually part of the to-be-promoted set.
9369   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9370
9371   // Make sure that this is a self-contained cluster of operations (which
9372   // is not quite the same thing as saying that everything has only one
9373   // use).
9374   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9375     if (isa<ConstantSDNode>(Inputs[i]))
9376       continue;
9377
9378     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9379                               UE = Inputs[i].getNode()->use_end();
9380          UI != UE; ++UI) {
9381       SDNode *User = *UI;
9382       if (User != N && !Visited.count(User))
9383         return SDValue();
9384
9385       // If we're going to promote the non-output-value operand(s) or SELECT or
9386       // SELECT_CC, record them for truncation.
9387       if (User->getOpcode() == ISD::SELECT) {
9388         if (User->getOperand(0) == Inputs[i])
9389           SelectTruncOp[0].insert(std::make_pair(User,
9390                                     User->getOperand(0).getValueType()));
9391       } else if (User->getOpcode() == ISD::SELECT_CC) {
9392         if (User->getOperand(0) == Inputs[i])
9393           SelectTruncOp[0].insert(std::make_pair(User,
9394                                     User->getOperand(0).getValueType()));
9395         if (User->getOperand(1) == Inputs[i])
9396           SelectTruncOp[1].insert(std::make_pair(User,
9397                                     User->getOperand(1).getValueType()));
9398       }
9399     }
9400   }
9401
9402   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9403     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9404                               UE = PromOps[i].getNode()->use_end();
9405          UI != UE; ++UI) {
9406       SDNode *User = *UI;
9407       if (User != N && !Visited.count(User))
9408         return SDValue();
9409
9410       // If we're going to promote the non-output-value operand(s) or SELECT or
9411       // SELECT_CC, record them for truncation.
9412       if (User->getOpcode() == ISD::SELECT) {
9413         if (User->getOperand(0) == PromOps[i])
9414           SelectTruncOp[0].insert(std::make_pair(User,
9415                                     User->getOperand(0).getValueType()));
9416       } else if (User->getOpcode() == ISD::SELECT_CC) {
9417         if (User->getOperand(0) == PromOps[i])
9418           SelectTruncOp[0].insert(std::make_pair(User,
9419                                     User->getOperand(0).getValueType()));
9420         if (User->getOperand(1) == PromOps[i])
9421           SelectTruncOp[1].insert(std::make_pair(User,
9422                                     User->getOperand(1).getValueType()));
9423       }
9424     }
9425   }
9426
9427   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9428   bool ReallyNeedsExt = false;
9429   if (N->getOpcode() != ISD::ANY_EXTEND) {
9430     // If all of the inputs are not already sign/zero extended, then
9431     // we'll still need to do that at the end.
9432     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9433       if (isa<ConstantSDNode>(Inputs[i]))
9434         continue;
9435
9436       unsigned OpBits =
9437         Inputs[i].getOperand(0).getValueSizeInBits();
9438       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9439
9440       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9441            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9442                                   APInt::getHighBitsSet(OpBits,
9443                                                         OpBits-PromBits))) ||
9444           (N->getOpcode() == ISD::SIGN_EXTEND &&
9445            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9446              (OpBits-(PromBits-1)))) {
9447         ReallyNeedsExt = true;
9448         break;
9449       }
9450     }
9451   }
9452
9453   // Replace all inputs, either with the truncation operand, or a
9454   // truncation or extension to the final output type.
9455   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9456     // Constant inputs need to be replaced with the to-be-promoted nodes that
9457     // use them because they might have users outside of the cluster of
9458     // promoted nodes.
9459     if (isa<ConstantSDNode>(Inputs[i]))
9460       continue;
9461
9462     SDValue InSrc = Inputs[i].getOperand(0);
9463     if (Inputs[i].getValueType() == N->getValueType(0))
9464       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9465     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9466       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9467         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9468     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9469       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9470         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9471     else
9472       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9473         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9474   }
9475
9476   // Replace all operations (these are all the same, but have a different
9477   // (promoted) return type). DAG.getNode will validate that the types of
9478   // a binary operator match, so go through the list in reverse so that
9479   // we've likely promoted both operands first.
9480   while (!PromOps.empty()) {
9481     SDValue PromOp = PromOps.back();
9482     PromOps.pop_back();
9483
9484     unsigned C;
9485     switch (PromOp.getOpcode()) {
9486     default:             C = 0; break;
9487     case ISD::SELECT:    C = 1; break;
9488     case ISD::SELECT_CC: C = 2; break;
9489     }
9490
9491     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9492          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9493         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9494          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9495       // The to-be-promoted operands of this node have not yet been
9496       // promoted (this should be rare because we're going through the
9497       // list backward, but if one of the operands has several users in
9498       // this cluster of to-be-promoted nodes, it is possible).
9499       PromOps.insert(PromOps.begin(), PromOp);
9500       continue;
9501     }
9502
9503     // For SELECT and SELECT_CC nodes, we do a similar check for any
9504     // to-be-promoted comparison inputs.
9505     if (PromOp.getOpcode() == ISD::SELECT ||
9506         PromOp.getOpcode() == ISD::SELECT_CC) {
9507       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9508            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9509           (SelectTruncOp[1].count(PromOp.getNode()) &&
9510            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9511         PromOps.insert(PromOps.begin(), PromOp);
9512         continue;
9513       }
9514     }
9515
9516     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9517                                 PromOp.getNode()->op_end());
9518
9519     // If this node has constant inputs, then they'll need to be promoted here.
9520     for (unsigned i = 0; i < 2; ++i) {
9521       if (!isa<ConstantSDNode>(Ops[C+i]))
9522         continue;
9523       if (Ops[C+i].getValueType() == N->getValueType(0))
9524         continue;
9525
9526       if (N->getOpcode() == ISD::SIGN_EXTEND)
9527         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9528       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9529         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9530       else
9531         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9532     }
9533
9534     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9535     // truncate them again to the original value type.
9536     if (PromOp.getOpcode() == ISD::SELECT ||
9537         PromOp.getOpcode() == ISD::SELECT_CC) {
9538       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9539       if (SI0 != SelectTruncOp[0].end())
9540         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9541       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9542       if (SI1 != SelectTruncOp[1].end())
9543         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9544     }
9545
9546     DAG.ReplaceAllUsesOfValueWith(PromOp,
9547       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9548   }
9549
9550   // Now we're left with the initial extension itself.
9551   if (!ReallyNeedsExt)
9552     return N->getOperand(0);
9553
9554   // To zero extend, just mask off everything except for the first bit (in the
9555   // i1 case).
9556   if (N->getOpcode() == ISD::ZERO_EXTEND)
9557     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9558                        DAG.getConstant(APInt::getLowBitsSet(
9559                                          N->getValueSizeInBits(0), PromBits),
9560                                        N->getValueType(0)));
9561
9562   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9563          "Invalid extension type");
9564   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9565   SDValue ShiftCst =
9566     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9567   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9568                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9569                                  N->getOperand(0), ShiftCst), ShiftCst);
9570 }
9571
9572 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9573                                               DAGCombinerInfo &DCI) const {
9574   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9575           N->getOpcode() == ISD::UINT_TO_FP) &&
9576          "Need an int -> FP conversion node here");
9577
9578   if (!Subtarget.has64BitSupport())
9579     return SDValue();
9580
9581   SelectionDAG &DAG = DCI.DAG;
9582   SDLoc dl(N);
9583   SDValue Op(N, 0);
9584
9585   // Don't handle ppc_fp128 here or i1 conversions.
9586   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9587     return SDValue();
9588   if (Op.getOperand(0).getValueType() == MVT::i1)
9589     return SDValue();
9590
9591   // For i32 intermediate values, unfortunately, the conversion functions
9592   // leave the upper 32 bits of the value are undefined. Within the set of
9593   // scalar instructions, we have no method for zero- or sign-extending the
9594   // value. Thus, we cannot handle i32 intermediate values here.
9595   if (Op.getOperand(0).getValueType() == MVT::i32)
9596     return SDValue();
9597
9598   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9599          "UINT_TO_FP is supported only with FPCVT");
9600
9601   // If we have FCFIDS, then use it when converting to single-precision.
9602   // Otherwise, convert to double-precision and then round.
9603   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9604                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9605                                                             : PPCISD::FCFIDS)
9606                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9607                                                             : PPCISD::FCFID);
9608   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9609                   ? MVT::f32
9610                   : MVT::f64;
9611
9612   // If we're converting from a float, to an int, and back to a float again,
9613   // then we don't need the store/load pair at all.
9614   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9615        Subtarget.hasFPCVT()) ||
9616       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9617     SDValue Src = Op.getOperand(0).getOperand(0);
9618     if (Src.getValueType() == MVT::f32) {
9619       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9620       DCI.AddToWorklist(Src.getNode());
9621     }
9622
9623     unsigned FCTOp =
9624       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9625                                                         PPCISD::FCTIDUZ;
9626
9627     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9628     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9629
9630     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9631       FP = DAG.getNode(ISD::FP_ROUND, dl,
9632                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9633       DCI.AddToWorklist(FP.getNode());
9634     }
9635
9636     return FP;
9637   }
9638
9639   return SDValue();
9640 }
9641
9642 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9643 // builtins) into loads with swaps.
9644 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9645                                               DAGCombinerInfo &DCI) const {
9646   SelectionDAG &DAG = DCI.DAG;
9647   SDLoc dl(N);
9648   SDValue Chain;
9649   SDValue Base;
9650   MachineMemOperand *MMO;
9651
9652   switch (N->getOpcode()) {
9653   default:
9654     llvm_unreachable("Unexpected opcode for little endian VSX load");
9655   case ISD::LOAD: {
9656     LoadSDNode *LD = cast<LoadSDNode>(N);
9657     Chain = LD->getChain();
9658     Base = LD->getBasePtr();
9659     MMO = LD->getMemOperand();
9660     // If the MMO suggests this isn't a load of a full vector, leave
9661     // things alone.  For a built-in, we have to make the change for
9662     // correctness, so if there is a size problem that will be a bug.
9663     if (MMO->getSize() < 16)
9664       return SDValue();
9665     break;
9666   }
9667   case ISD::INTRINSIC_W_CHAIN: {
9668     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9669     Chain = Intrin->getChain();
9670     Base = Intrin->getBasePtr();
9671     MMO = Intrin->getMemOperand();
9672     break;
9673   }
9674   }
9675
9676   MVT VecTy = N->getValueType(0).getSimpleVT();
9677   SDValue LoadOps[] = { Chain, Base };
9678   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9679                                          DAG.getVTList(VecTy, MVT::Other),
9680                                          LoadOps, VecTy, MMO);
9681   DCI.AddToWorklist(Load.getNode());
9682   Chain = Load.getValue(1);
9683   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9684                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9685   DCI.AddToWorklist(Swap.getNode());
9686   return Swap;
9687 }
9688
9689 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9690 // builtins) into stores with swaps.
9691 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9692                                                DAGCombinerInfo &DCI) const {
9693   SelectionDAG &DAG = DCI.DAG;
9694   SDLoc dl(N);
9695   SDValue Chain;
9696   SDValue Base;
9697   unsigned SrcOpnd;
9698   MachineMemOperand *MMO;
9699
9700   switch (N->getOpcode()) {
9701   default:
9702     llvm_unreachable("Unexpected opcode for little endian VSX store");
9703   case ISD::STORE: {
9704     StoreSDNode *ST = cast<StoreSDNode>(N);
9705     Chain = ST->getChain();
9706     Base = ST->getBasePtr();
9707     MMO = ST->getMemOperand();
9708     SrcOpnd = 1;
9709     // If the MMO suggests this isn't a store of a full vector, leave
9710     // things alone.  For a built-in, we have to make the change for
9711     // correctness, so if there is a size problem that will be a bug.
9712     if (MMO->getSize() < 16)
9713       return SDValue();
9714     break;
9715   }
9716   case ISD::INTRINSIC_VOID: {
9717     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9718     Chain = Intrin->getChain();
9719     // Intrin->getBasePtr() oddly does not get what we want.
9720     Base = Intrin->getOperand(3);
9721     MMO = Intrin->getMemOperand();
9722     SrcOpnd = 2;
9723     break;
9724   }
9725   }
9726
9727   SDValue Src = N->getOperand(SrcOpnd);
9728   MVT VecTy = Src.getValueType().getSimpleVT();
9729   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9730                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9731   DCI.AddToWorklist(Swap.getNode());
9732   Chain = Swap.getValue(1);
9733   SDValue StoreOps[] = { Chain, Swap, Base };
9734   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9735                                           DAG.getVTList(MVT::Other),
9736                                           StoreOps, VecTy, MMO);
9737   DCI.AddToWorklist(Store.getNode());
9738   return Store;
9739 }
9740
9741 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9742                                              DAGCombinerInfo &DCI) const {
9743   SelectionDAG &DAG = DCI.DAG;
9744   SDLoc dl(N);
9745   switch (N->getOpcode()) {
9746   default: break;
9747   case PPCISD::SHL:
9748     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9749       if (C->isNullValue())   // 0 << V -> 0.
9750         return N->getOperand(0);
9751     }
9752     break;
9753   case PPCISD::SRL:
9754     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9755       if (C->isNullValue())   // 0 >>u V -> 0.
9756         return N->getOperand(0);
9757     }
9758     break;
9759   case PPCISD::SRA:
9760     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9761       if (C->isNullValue() ||   //  0 >>s V -> 0.
9762           C->isAllOnesValue())    // -1 >>s V -> -1.
9763         return N->getOperand(0);
9764     }
9765     break;
9766   case ISD::SIGN_EXTEND:
9767   case ISD::ZERO_EXTEND:
9768   case ISD::ANY_EXTEND: 
9769     return DAGCombineExtBoolTrunc(N, DCI);
9770   case ISD::TRUNCATE:
9771   case ISD::SETCC:
9772   case ISD::SELECT_CC:
9773     return DAGCombineTruncBoolExt(N, DCI);
9774   case ISD::SINT_TO_FP:
9775   case ISD::UINT_TO_FP:
9776     return combineFPToIntToFP(N, DCI);
9777   case ISD::STORE: {
9778     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9779     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9780         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9781         N->getOperand(1).getValueType() == MVT::i32 &&
9782         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9783       SDValue Val = N->getOperand(1).getOperand(0);
9784       if (Val.getValueType() == MVT::f32) {
9785         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9786         DCI.AddToWorklist(Val.getNode());
9787       }
9788       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9789       DCI.AddToWorklist(Val.getNode());
9790
9791       SDValue Ops[] = {
9792         N->getOperand(0), Val, N->getOperand(2),
9793         DAG.getValueType(N->getOperand(1).getValueType())
9794       };
9795
9796       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9797               DAG.getVTList(MVT::Other), Ops,
9798               cast<StoreSDNode>(N)->getMemoryVT(),
9799               cast<StoreSDNode>(N)->getMemOperand());
9800       DCI.AddToWorklist(Val.getNode());
9801       return Val;
9802     }
9803
9804     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9805     if (cast<StoreSDNode>(N)->isUnindexed() &&
9806         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9807         N->getOperand(1).getNode()->hasOneUse() &&
9808         (N->getOperand(1).getValueType() == MVT::i32 ||
9809          N->getOperand(1).getValueType() == MVT::i16 ||
9810          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9811           N->getOperand(1).getValueType() == MVT::i64))) {
9812       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9813       // Do an any-extend to 32-bits if this is a half-word input.
9814       if (BSwapOp.getValueType() == MVT::i16)
9815         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9816
9817       SDValue Ops[] = {
9818         N->getOperand(0), BSwapOp, N->getOperand(2),
9819         DAG.getValueType(N->getOperand(1).getValueType())
9820       };
9821       return
9822         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9823                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9824                                 cast<StoreSDNode>(N)->getMemOperand());
9825     }
9826
9827     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9828     EVT VT = N->getOperand(1).getValueType();
9829     if (VT.isSimple()) {
9830       MVT StoreVT = VT.getSimpleVT();
9831       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9832           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9833            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9834         return expandVSXStoreForLE(N, DCI);
9835     }
9836     break;
9837   }
9838   case ISD::LOAD: {
9839     LoadSDNode *LD = cast<LoadSDNode>(N);
9840     EVT VT = LD->getValueType(0);
9841
9842     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9843     if (VT.isSimple()) {
9844       MVT LoadVT = VT.getSimpleVT();
9845       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9846           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9847            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9848         return expandVSXLoadForLE(N, DCI);
9849     }
9850
9851     EVT MemVT = LD->getMemoryVT();
9852     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9853     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9854     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9855     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9856     if (LD->isUnindexed() && VT.isVector() &&
9857         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9858           // P8 and later hardware should just use LOAD.
9859           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9860                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9861          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9862           LD->getAlignment() >= ScalarABIAlignment)) &&
9863         LD->getAlignment() < ABIAlignment) {
9864       // This is a type-legal unaligned Altivec or QPX load.
9865       SDValue Chain = LD->getChain();
9866       SDValue Ptr = LD->getBasePtr();
9867       bool isLittleEndian = Subtarget.isLittleEndian();
9868
9869       // This implements the loading of unaligned vectors as described in
9870       // the venerable Apple Velocity Engine overview. Specifically:
9871       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9872       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9873       //
9874       // The general idea is to expand a sequence of one or more unaligned
9875       // loads into an alignment-based permutation-control instruction (lvsl
9876       // or lvsr), a series of regular vector loads (which always truncate
9877       // their input address to an aligned address), and a series of
9878       // permutations.  The results of these permutations are the requested
9879       // loaded values.  The trick is that the last "extra" load is not taken
9880       // from the address you might suspect (sizeof(vector) bytes after the
9881       // last requested load), but rather sizeof(vector) - 1 bytes after the
9882       // last requested vector. The point of this is to avoid a page fault if
9883       // the base address happened to be aligned. This works because if the
9884       // base address is aligned, then adding less than a full vector length
9885       // will cause the last vector in the sequence to be (re)loaded.
9886       // Otherwise, the next vector will be fetched as you might suspect was
9887       // necessary.
9888
9889       // We might be able to reuse the permutation generation from
9890       // a different base address offset from this one by an aligned amount.
9891       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9892       // optimization later.
9893       Intrinsic::ID Intr, IntrLD, IntrPerm;
9894       MVT PermCntlTy, PermTy, LDTy;
9895       if (Subtarget.hasAltivec()) {
9896         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
9897                                  Intrinsic::ppc_altivec_lvsl;
9898         IntrLD = Intrinsic::ppc_altivec_lvx;
9899         IntrPerm = Intrinsic::ppc_altivec_vperm;
9900         PermCntlTy = MVT::v16i8;
9901         PermTy = MVT::v4i32;
9902         LDTy = MVT::v4i32;
9903       } else {
9904         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9905                                        Intrinsic::ppc_qpx_qvlpcls;
9906         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9907                                        Intrinsic::ppc_qpx_qvlfs;
9908         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9909         PermCntlTy = MVT::v4f64;
9910         PermTy = MVT::v4f64;
9911         LDTy = MemVT.getSimpleVT();
9912       }
9913
9914       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9915
9916       // Create the new MMO for the new base load. It is like the original MMO,
9917       // but represents an area in memory almost twice the vector size centered
9918       // on the original address. If the address is unaligned, we might start
9919       // reading up to (sizeof(vector)-1) bytes below the address of the
9920       // original unaligned load.
9921       MachineFunction &MF = DAG.getMachineFunction();
9922       MachineMemOperand *BaseMMO =
9923         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9924                                 2*MemVT.getStoreSize()-1);
9925
9926       // Create the new base load.
9927       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9928       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9929       SDValue BaseLoad =
9930         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9931                                 DAG.getVTList(PermTy, MVT::Other),
9932                                 BaseLoadOps, LDTy, BaseMMO);
9933
9934       // Note that the value of IncOffset (which is provided to the next
9935       // load's pointer info offset value, and thus used to calculate the
9936       // alignment), and the value of IncValue (which is actually used to
9937       // increment the pointer value) are different! This is because we
9938       // require the next load to appear to be aligned, even though it
9939       // is actually offset from the base pointer by a lesser amount.
9940       int IncOffset = VT.getSizeInBits() / 8;
9941       int IncValue = IncOffset;
9942
9943       // Walk (both up and down) the chain looking for another load at the real
9944       // (aligned) offset (the alignment of the other load does not matter in
9945       // this case). If found, then do not use the offset reduction trick, as
9946       // that will prevent the loads from being later combined (as they would
9947       // otherwise be duplicates).
9948       if (!findConsecutiveLoad(LD, DAG))
9949         --IncValue;
9950
9951       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9952       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9953
9954       MachineMemOperand *ExtraMMO =
9955         MF.getMachineMemOperand(LD->getMemOperand(),
9956                                 1, 2*MemVT.getStoreSize()-1);
9957       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9958       SDValue ExtraLoad =
9959         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9960                                 DAG.getVTList(PermTy, MVT::Other),
9961                                 ExtraLoadOps, LDTy, ExtraMMO);
9962
9963       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9964         BaseLoad.getValue(1), ExtraLoad.getValue(1));
9965
9966       // Because vperm has a big-endian bias, we must reverse the order
9967       // of the input vectors and complement the permute control vector
9968       // when generating little endian code.  We have already handled the
9969       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9970       // and ExtraLoad here.
9971       SDValue Perm;
9972       if (isLittleEndian)
9973         Perm = BuildIntrinsicOp(IntrPerm,
9974                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9975       else
9976         Perm = BuildIntrinsicOp(IntrPerm,
9977                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9978
9979       if (VT != PermTy)
9980         Perm = Subtarget.hasAltivec() ?
9981                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
9982                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
9983                                DAG.getTargetConstant(1, MVT::i64));
9984                                // second argument is 1 because this rounding
9985                                // is always exact.
9986
9987       // The output of the permutation is our loaded result, the TokenFactor is
9988       // our new chain.
9989       DCI.CombineTo(N, Perm, TF);
9990       return SDValue(N, 0);
9991     }
9992     }
9993     break;
9994     case ISD::INTRINSIC_WO_CHAIN: {
9995       bool isLittleEndian = Subtarget.isLittleEndian();
9996       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9997       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9998                                            : Intrinsic::ppc_altivec_lvsl);
9999       if ((IID == Intr ||
10000            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10001            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10002         N->getOperand(1)->getOpcode() == ISD::ADD) {
10003         SDValue Add = N->getOperand(1);
10004
10005         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10006                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10007
10008         if (DAG.MaskedValueIsZero(
10009                 Add->getOperand(1),
10010                 APInt::getAllOnesValue(Bits /* alignment */)
10011                     .zext(
10012                         Add.getValueType().getScalarType().getSizeInBits()))) {
10013           SDNode *BasePtr = Add->getOperand(0).getNode();
10014           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10015                                     UE = BasePtr->use_end();
10016                UI != UE; ++UI) {
10017             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10018                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10019               // We've found another LVSL/LVSR, and this address is an aligned
10020               // multiple of that one. The results will be the same, so use the
10021               // one we've just found instead.
10022
10023               return SDValue(*UI, 0);
10024             }
10025           }
10026         }
10027
10028         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10029           SDNode *BasePtr = Add->getOperand(0).getNode();
10030           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10031                UE = BasePtr->use_end(); UI != UE; ++UI) {
10032             if (UI->getOpcode() == ISD::ADD &&
10033                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10034                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10035                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10036                 (1ULL << Bits) == 0) {
10037               SDNode *OtherAdd = *UI;
10038               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10039                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10040                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10041                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10042                   return SDValue(*VI, 0);
10043                 }
10044               }
10045             }
10046           }
10047         }
10048       }
10049     }
10050
10051     break;
10052   case ISD::INTRINSIC_W_CHAIN: {
10053     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10054     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10055       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10056       default:
10057         break;
10058       case Intrinsic::ppc_vsx_lxvw4x:
10059       case Intrinsic::ppc_vsx_lxvd2x:
10060         return expandVSXLoadForLE(N, DCI);
10061       }
10062     }
10063     break;
10064   }
10065   case ISD::INTRINSIC_VOID: {
10066     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10067     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10068       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10069       default:
10070         break;
10071       case Intrinsic::ppc_vsx_stxvw4x:
10072       case Intrinsic::ppc_vsx_stxvd2x:
10073         return expandVSXStoreForLE(N, DCI);
10074       }
10075     }
10076     break;
10077   }
10078   case ISD::BSWAP:
10079     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10080     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10081         N->getOperand(0).hasOneUse() &&
10082         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10083          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10084           N->getValueType(0) == MVT::i64))) {
10085       SDValue Load = N->getOperand(0);
10086       LoadSDNode *LD = cast<LoadSDNode>(Load);
10087       // Create the byte-swapping load.
10088       SDValue Ops[] = {
10089         LD->getChain(),    // Chain
10090         LD->getBasePtr(),  // Ptr
10091         DAG.getValueType(N->getValueType(0)) // VT
10092       };
10093       SDValue BSLoad =
10094         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10095                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10096                                               MVT::i64 : MVT::i32, MVT::Other),
10097                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10098
10099       // If this is an i16 load, insert the truncate.
10100       SDValue ResVal = BSLoad;
10101       if (N->getValueType(0) == MVT::i16)
10102         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10103
10104       // First, combine the bswap away.  This makes the value produced by the
10105       // load dead.
10106       DCI.CombineTo(N, ResVal);
10107
10108       // Next, combine the load away, we give it a bogus result value but a real
10109       // chain result.  The result value is dead because the bswap is dead.
10110       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10111
10112       // Return N so it doesn't get rechecked!
10113       return SDValue(N, 0);
10114     }
10115
10116     break;
10117   case PPCISD::VCMP: {
10118     // If a VCMPo node already exists with exactly the same operands as this
10119     // node, use its result instead of this node (VCMPo computes both a CR6 and
10120     // a normal output).
10121     //
10122     if (!N->getOperand(0).hasOneUse() &&
10123         !N->getOperand(1).hasOneUse() &&
10124         !N->getOperand(2).hasOneUse()) {
10125
10126       // Scan all of the users of the LHS, looking for VCMPo's that match.
10127       SDNode *VCMPoNode = nullptr;
10128
10129       SDNode *LHSN = N->getOperand(0).getNode();
10130       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10131            UI != E; ++UI)
10132         if (UI->getOpcode() == PPCISD::VCMPo &&
10133             UI->getOperand(1) == N->getOperand(1) &&
10134             UI->getOperand(2) == N->getOperand(2) &&
10135             UI->getOperand(0) == N->getOperand(0)) {
10136           VCMPoNode = *UI;
10137           break;
10138         }
10139
10140       // If there is no VCMPo node, or if the flag value has a single use, don't
10141       // transform this.
10142       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10143         break;
10144
10145       // Look at the (necessarily single) use of the flag value.  If it has a
10146       // chain, this transformation is more complex.  Note that multiple things
10147       // could use the value result, which we should ignore.
10148       SDNode *FlagUser = nullptr;
10149       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10150            FlagUser == nullptr; ++UI) {
10151         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10152         SDNode *User = *UI;
10153         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10154           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10155             FlagUser = User;
10156             break;
10157           }
10158         }
10159       }
10160
10161       // If the user is a MFOCRF instruction, we know this is safe.
10162       // Otherwise we give up for right now.
10163       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10164         return SDValue(VCMPoNode, 0);
10165     }
10166     break;
10167   }
10168   case ISD::BRCOND: {
10169     SDValue Cond = N->getOperand(1);
10170     SDValue Target = N->getOperand(2);
10171  
10172     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10173         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10174           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10175
10176       // We now need to make the intrinsic dead (it cannot be instruction
10177       // selected).
10178       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10179       assert(Cond.getNode()->hasOneUse() &&
10180              "Counter decrement has more than one use");
10181
10182       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10183                          N->getOperand(0), Target);
10184     }
10185   }
10186   break;
10187   case ISD::BR_CC: {
10188     // If this is a branch on an altivec predicate comparison, lower this so
10189     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10190     // lowering is done pre-legalize, because the legalizer lowers the predicate
10191     // compare down to code that is difficult to reassemble.
10192     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10193     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10194
10195     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10196     // value. If so, pass-through the AND to get to the intrinsic.
10197     if (LHS.getOpcode() == ISD::AND &&
10198         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10199         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10200           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10201         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10202         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10203           isZero())
10204       LHS = LHS.getOperand(0);
10205
10206     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10207         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10208           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10209         isa<ConstantSDNode>(RHS)) {
10210       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10211              "Counter decrement comparison is not EQ or NE");
10212
10213       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10214       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10215                     (CC == ISD::SETNE && !Val);
10216
10217       // We now need to make the intrinsic dead (it cannot be instruction
10218       // selected).
10219       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10220       assert(LHS.getNode()->hasOneUse() &&
10221              "Counter decrement has more than one use");
10222
10223       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10224                          N->getOperand(0), N->getOperand(4));
10225     }
10226
10227     int CompareOpc;
10228     bool isDot;
10229
10230     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10231         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10232         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10233       assert(isDot && "Can't compare against a vector result!");
10234
10235       // If this is a comparison against something other than 0/1, then we know
10236       // that the condition is never/always true.
10237       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10238       if (Val != 0 && Val != 1) {
10239         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10240           return N->getOperand(0);
10241         // Always !=, turn it into an unconditional branch.
10242         return DAG.getNode(ISD::BR, dl, MVT::Other,
10243                            N->getOperand(0), N->getOperand(4));
10244       }
10245
10246       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10247
10248       // Create the PPCISD altivec 'dot' comparison node.
10249       SDValue Ops[] = {
10250         LHS.getOperand(2),  // LHS of compare
10251         LHS.getOperand(3),  // RHS of compare
10252         DAG.getConstant(CompareOpc, MVT::i32)
10253       };
10254       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10255       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10256
10257       // Unpack the result based on how the target uses it.
10258       PPC::Predicate CompOpc;
10259       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10260       default:  // Can't happen, don't crash on invalid number though.
10261       case 0:   // Branch on the value of the EQ bit of CR6.
10262         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10263         break;
10264       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10265         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10266         break;
10267       case 2:   // Branch on the value of the LT bit of CR6.
10268         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10269         break;
10270       case 3:   // Branch on the inverted value of the LT bit of CR6.
10271         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10272         break;
10273       }
10274
10275       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10276                          DAG.getConstant(CompOpc, MVT::i32),
10277                          DAG.getRegister(PPC::CR6, MVT::i32),
10278                          N->getOperand(4), CompNode.getValue(1));
10279     }
10280     break;
10281   }
10282   }
10283
10284   return SDValue();
10285 }
10286
10287 SDValue
10288 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10289                                   SelectionDAG &DAG,
10290                                   std::vector<SDNode *> *Created) const {
10291   // fold (sdiv X, pow2)
10292   EVT VT = N->getValueType(0);
10293   if (VT == MVT::i64 && !Subtarget.isPPC64())
10294     return SDValue();
10295   if ((VT != MVT::i32 && VT != MVT::i64) ||
10296       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10297     return SDValue();
10298
10299   SDLoc DL(N);
10300   SDValue N0 = N->getOperand(0);
10301
10302   bool IsNegPow2 = (-Divisor).isPowerOf2();
10303   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10304   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10305
10306   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10307   if (Created)
10308     Created->push_back(Op.getNode());
10309
10310   if (IsNegPow2) {
10311     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10312     if (Created)
10313       Created->push_back(Op.getNode());
10314   }
10315
10316   return Op;
10317 }
10318
10319 //===----------------------------------------------------------------------===//
10320 // Inline Assembly Support
10321 //===----------------------------------------------------------------------===//
10322
10323 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10324                                                       APInt &KnownZero,
10325                                                       APInt &KnownOne,
10326                                                       const SelectionDAG &DAG,
10327                                                       unsigned Depth) const {
10328   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10329   switch (Op.getOpcode()) {
10330   default: break;
10331   case PPCISD::LBRX: {
10332     // lhbrx is known to have the top bits cleared out.
10333     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10334       KnownZero = 0xFFFF0000;
10335     break;
10336   }
10337   case ISD::INTRINSIC_WO_CHAIN: {
10338     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10339     default: break;
10340     case Intrinsic::ppc_altivec_vcmpbfp_p:
10341     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10342     case Intrinsic::ppc_altivec_vcmpequb_p:
10343     case Intrinsic::ppc_altivec_vcmpequh_p:
10344     case Intrinsic::ppc_altivec_vcmpequw_p:
10345     case Intrinsic::ppc_altivec_vcmpequd_p:
10346     case Intrinsic::ppc_altivec_vcmpgefp_p:
10347     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10348     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10349     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10350     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10351     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10352     case Intrinsic::ppc_altivec_vcmpgtub_p:
10353     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10354     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10355     case Intrinsic::ppc_altivec_vcmpgtud_p:
10356       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10357       break;
10358     }
10359   }
10360   }
10361 }
10362
10363 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10364   switch (Subtarget.getDarwinDirective()) {
10365   default: break;
10366   case PPC::DIR_970:
10367   case PPC::DIR_PWR4:
10368   case PPC::DIR_PWR5:
10369   case PPC::DIR_PWR5X:
10370   case PPC::DIR_PWR6:
10371   case PPC::DIR_PWR6X:
10372   case PPC::DIR_PWR7:
10373   case PPC::DIR_PWR8: {
10374     if (!ML)
10375       break;
10376
10377     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10378
10379     // For small loops (between 5 and 8 instructions), align to a 32-byte
10380     // boundary so that the entire loop fits in one instruction-cache line.
10381     uint64_t LoopSize = 0;
10382     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10383       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10384         LoopSize += TII->GetInstSizeInBytes(J);
10385
10386     if (LoopSize > 16 && LoopSize <= 32)
10387       return 5;
10388
10389     break;
10390   }
10391   }
10392
10393   return TargetLowering::getPrefLoopAlignment(ML);
10394 }
10395
10396 /// getConstraintType - Given a constraint, return the type of
10397 /// constraint it is for this target.
10398 PPCTargetLowering::ConstraintType
10399 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10400   if (Constraint.size() == 1) {
10401     switch (Constraint[0]) {
10402     default: break;
10403     case 'b':
10404     case 'r':
10405     case 'f':
10406     case 'v':
10407     case 'y':
10408       return C_RegisterClass;
10409     case 'Z':
10410       // FIXME: While Z does indicate a memory constraint, it specifically
10411       // indicates an r+r address (used in conjunction with the 'y' modifier
10412       // in the replacement string). Currently, we're forcing the base
10413       // register to be r0 in the asm printer (which is interpreted as zero)
10414       // and forming the complete address in the second register. This is
10415       // suboptimal.
10416       return C_Memory;
10417     }
10418   } else if (Constraint == "wc") { // individual CR bits.
10419     return C_RegisterClass;
10420   } else if (Constraint == "wa" || Constraint == "wd" ||
10421              Constraint == "wf" || Constraint == "ws") {
10422     return C_RegisterClass; // VSX registers.
10423   }
10424   return TargetLowering::getConstraintType(Constraint);
10425 }
10426
10427 /// Examine constraint type and operand type and determine a weight value.
10428 /// This object must already have been set up with the operand type
10429 /// and the current alternative constraint selected.
10430 TargetLowering::ConstraintWeight
10431 PPCTargetLowering::getSingleConstraintMatchWeight(
10432     AsmOperandInfo &info, const char *constraint) const {
10433   ConstraintWeight weight = CW_Invalid;
10434   Value *CallOperandVal = info.CallOperandVal;
10435     // If we don't have a value, we can't do a match,
10436     // but allow it at the lowest weight.
10437   if (!CallOperandVal)
10438     return CW_Default;
10439   Type *type = CallOperandVal->getType();
10440
10441   // Look at the constraint type.
10442   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10443     return CW_Register; // an individual CR bit.
10444   else if ((StringRef(constraint) == "wa" ||
10445             StringRef(constraint) == "wd" ||
10446             StringRef(constraint) == "wf") &&
10447            type->isVectorTy())
10448     return CW_Register;
10449   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10450     return CW_Register;
10451
10452   switch (*constraint) {
10453   default:
10454     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10455     break;
10456   case 'b':
10457     if (type->isIntegerTy())
10458       weight = CW_Register;
10459     break;
10460   case 'f':
10461     if (type->isFloatTy())
10462       weight = CW_Register;
10463     break;
10464   case 'd':
10465     if (type->isDoubleTy())
10466       weight = CW_Register;
10467     break;
10468   case 'v':
10469     if (type->isVectorTy())
10470       weight = CW_Register;
10471     break;
10472   case 'y':
10473     weight = CW_Register;
10474     break;
10475   case 'Z':
10476     weight = CW_Memory;
10477     break;
10478   }
10479   return weight;
10480 }
10481
10482 std::pair<unsigned, const TargetRegisterClass *>
10483 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10484                                                 const std::string &Constraint,
10485                                                 MVT VT) const {
10486   if (Constraint.size() == 1) {
10487     // GCC RS6000 Constraint Letters
10488     switch (Constraint[0]) {
10489     case 'b':   // R1-R31
10490       if (VT == MVT::i64 && Subtarget.isPPC64())
10491         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10492       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10493     case 'r':   // R0-R31
10494       if (VT == MVT::i64 && Subtarget.isPPC64())
10495         return std::make_pair(0U, &PPC::G8RCRegClass);
10496       return std::make_pair(0U, &PPC::GPRCRegClass);
10497     case 'f':
10498       if (VT == MVT::f32 || VT == MVT::i32)
10499         return std::make_pair(0U, &PPC::F4RCRegClass);
10500       if (VT == MVT::f64 || VT == MVT::i64)
10501         return std::make_pair(0U, &PPC::F8RCRegClass);
10502       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10503         return std::make_pair(0U, &PPC::QFRCRegClass);
10504       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10505         return std::make_pair(0U, &PPC::QSRCRegClass);
10506       break;
10507     case 'v':
10508       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10509         return std::make_pair(0U, &PPC::QFRCRegClass);
10510       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10511         return std::make_pair(0U, &PPC::QSRCRegClass);
10512       return std::make_pair(0U, &PPC::VRRCRegClass);
10513     case 'y':   // crrc
10514       return std::make_pair(0U, &PPC::CRRCRegClass);
10515     }
10516   } else if (Constraint == "wc") { // an individual CR bit.
10517     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10518   } else if (Constraint == "wa" || Constraint == "wd" ||
10519              Constraint == "wf") {
10520     return std::make_pair(0U, &PPC::VSRCRegClass);
10521   } else if (Constraint == "ws") {
10522     return std::make_pair(0U, &PPC::VSFRCRegClass);
10523   }
10524
10525   std::pair<unsigned, const TargetRegisterClass *> R =
10526       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10527
10528   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10529   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10530   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10531   // register.
10532   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10533   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10534   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10535       PPC::GPRCRegClass.contains(R.first))
10536     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10537                             PPC::sub_32, &PPC::G8RCRegClass),
10538                           &PPC::G8RCRegClass);
10539
10540   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10541   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10542     R.first = PPC::CR0;
10543     R.second = &PPC::CRRCRegClass;
10544   }
10545
10546   return R;
10547 }
10548
10549
10550 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10551 /// vector.  If it is invalid, don't add anything to Ops.
10552 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10553                                                      std::string &Constraint,
10554                                                      std::vector<SDValue>&Ops,
10555                                                      SelectionDAG &DAG) const {
10556   SDValue Result;
10557
10558   // Only support length 1 constraints.
10559   if (Constraint.length() > 1) return;
10560
10561   char Letter = Constraint[0];
10562   switch (Letter) {
10563   default: break;
10564   case 'I':
10565   case 'J':
10566   case 'K':
10567   case 'L':
10568   case 'M':
10569   case 'N':
10570   case 'O':
10571   case 'P': {
10572     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10573     if (!CST) return; // Must be an immediate to match.
10574     int64_t Value = CST->getSExtValue();
10575     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10576                          // numbers are printed as such.
10577     switch (Letter) {
10578     default: llvm_unreachable("Unknown constraint letter!");
10579     case 'I':  // "I" is a signed 16-bit constant.
10580       if (isInt<16>(Value))
10581         Result = DAG.getTargetConstant(Value, TCVT);
10582       break;
10583     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10584       if (isShiftedUInt<16, 16>(Value))
10585         Result = DAG.getTargetConstant(Value, TCVT);
10586       break;
10587     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10588       if (isShiftedInt<16, 16>(Value))
10589         Result = DAG.getTargetConstant(Value, TCVT);
10590       break;
10591     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10592       if (isUInt<16>(Value))
10593         Result = DAG.getTargetConstant(Value, TCVT);
10594       break;
10595     case 'M':  // "M" is a constant that is greater than 31.
10596       if (Value > 31)
10597         Result = DAG.getTargetConstant(Value, TCVT);
10598       break;
10599     case 'N':  // "N" is a positive constant that is an exact power of two.
10600       if (Value > 0 && isPowerOf2_64(Value))
10601         Result = DAG.getTargetConstant(Value, TCVT);
10602       break;
10603     case 'O':  // "O" is the constant zero.
10604       if (Value == 0)
10605         Result = DAG.getTargetConstant(Value, TCVT);
10606       break;
10607     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10608       if (isInt<16>(-Value))
10609         Result = DAG.getTargetConstant(Value, TCVT);
10610       break;
10611     }
10612     break;
10613   }
10614   }
10615
10616   if (Result.getNode()) {
10617     Ops.push_back(Result);
10618     return;
10619   }
10620
10621   // Handle standard constraint letters.
10622   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10623 }
10624
10625 // isLegalAddressingMode - Return true if the addressing mode represented
10626 // by AM is legal for this target, for a load/store of the specified type.
10627 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10628                                               Type *Ty) const {
10629   // PPC does not allow r+i addressing modes for vectors!
10630   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10631     return false;
10632
10633   // PPC allows a sign-extended 16-bit immediate field.
10634   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10635     return false;
10636
10637   // No global is ever allowed as a base.
10638   if (AM.BaseGV)
10639     return false;
10640
10641   // PPC only support r+r,
10642   switch (AM.Scale) {
10643   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10644     break;
10645   case 1:
10646     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10647       return false;
10648     // Otherwise we have r+r or r+i.
10649     break;
10650   case 2:
10651     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10652       return false;
10653     // Allow 2*r as r+r.
10654     break;
10655   default:
10656     // No other scales are supported.
10657     return false;
10658   }
10659
10660   return true;
10661 }
10662
10663 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10664                                            SelectionDAG &DAG) const {
10665   MachineFunction &MF = DAG.getMachineFunction();
10666   MachineFrameInfo *MFI = MF.getFrameInfo();
10667   MFI->setReturnAddressIsTaken(true);
10668
10669   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10670     return SDValue();
10671
10672   SDLoc dl(Op);
10673   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10674
10675   // Make sure the function does not optimize away the store of the RA to
10676   // the stack.
10677   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10678   FuncInfo->setLRStoreRequired();
10679   bool isPPC64 = Subtarget.isPPC64();
10680
10681   if (Depth > 0) {
10682     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10683     SDValue Offset =
10684         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10685                         isPPC64 ? MVT::i64 : MVT::i32);
10686     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10687                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10688                                    FrameAddr, Offset),
10689                        MachinePointerInfo(), false, false, false, 0);
10690   }
10691
10692   // Just load the return address off the stack.
10693   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10694   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10695                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10696 }
10697
10698 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10699                                           SelectionDAG &DAG) const {
10700   SDLoc dl(Op);
10701   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10702
10703   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10704   bool isPPC64 = PtrVT == MVT::i64;
10705
10706   MachineFunction &MF = DAG.getMachineFunction();
10707   MachineFrameInfo *MFI = MF.getFrameInfo();
10708   MFI->setFrameAddressIsTaken(true);
10709
10710   // Naked functions never have a frame pointer, and so we use r1. For all
10711   // other functions, this decision must be delayed until during PEI.
10712   unsigned FrameReg;
10713   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10714     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10715   else
10716     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10717
10718   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10719                                          PtrVT);
10720   while (Depth--)
10721     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10722                             FrameAddr, MachinePointerInfo(), false, false,
10723                             false, 0);
10724   return FrameAddr;
10725 }
10726
10727 // FIXME? Maybe this could be a TableGen attribute on some registers and
10728 // this table could be generated automatically from RegInfo.
10729 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10730                                               EVT VT) const {
10731   bool isPPC64 = Subtarget.isPPC64();
10732   bool isDarwinABI = Subtarget.isDarwinABI();
10733
10734   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10735       (!isPPC64 && VT != MVT::i32))
10736     report_fatal_error("Invalid register global variable type");
10737
10738   bool is64Bit = isPPC64 && VT == MVT::i64;
10739   unsigned Reg = StringSwitch<unsigned>(RegName)
10740                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10741                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10742                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10743                                   (is64Bit ? PPC::X13 : PPC::R13))
10744                    .Default(0);
10745
10746   if (Reg)
10747     return Reg;
10748   report_fatal_error("Invalid register name global variable");
10749 }
10750
10751 bool
10752 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10753   // The PowerPC target isn't yet aware of offsets.
10754   return false;
10755 }
10756
10757 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10758                                            const CallInst &I,
10759                                            unsigned Intrinsic) const {
10760
10761   switch (Intrinsic) {
10762   case Intrinsic::ppc_qpx_qvlfd:
10763   case Intrinsic::ppc_qpx_qvlfs:
10764   case Intrinsic::ppc_qpx_qvlfcd:
10765   case Intrinsic::ppc_qpx_qvlfcs:
10766   case Intrinsic::ppc_qpx_qvlfiwa:
10767   case Intrinsic::ppc_qpx_qvlfiwz:
10768   case Intrinsic::ppc_altivec_lvx:
10769   case Intrinsic::ppc_altivec_lvxl:
10770   case Intrinsic::ppc_altivec_lvebx:
10771   case Intrinsic::ppc_altivec_lvehx:
10772   case Intrinsic::ppc_altivec_lvewx:
10773   case Intrinsic::ppc_vsx_lxvd2x:
10774   case Intrinsic::ppc_vsx_lxvw4x: {
10775     EVT VT;
10776     switch (Intrinsic) {
10777     case Intrinsic::ppc_altivec_lvebx:
10778       VT = MVT::i8;
10779       break;
10780     case Intrinsic::ppc_altivec_lvehx:
10781       VT = MVT::i16;
10782       break;
10783     case Intrinsic::ppc_altivec_lvewx:
10784       VT = MVT::i32;
10785       break;
10786     case Intrinsic::ppc_vsx_lxvd2x:
10787       VT = MVT::v2f64;
10788       break;
10789     case Intrinsic::ppc_qpx_qvlfd:
10790       VT = MVT::v4f64;
10791       break;
10792     case Intrinsic::ppc_qpx_qvlfs:
10793       VT = MVT::v4f32;
10794       break;
10795     case Intrinsic::ppc_qpx_qvlfcd:
10796       VT = MVT::v2f64;
10797       break;
10798     case Intrinsic::ppc_qpx_qvlfcs:
10799       VT = MVT::v2f32;
10800       break;
10801     default:
10802       VT = MVT::v4i32;
10803       break;
10804     }
10805
10806     Info.opc = ISD::INTRINSIC_W_CHAIN;
10807     Info.memVT = VT;
10808     Info.ptrVal = I.getArgOperand(0);
10809     Info.offset = -VT.getStoreSize()+1;
10810     Info.size = 2*VT.getStoreSize()-1;
10811     Info.align = 1;
10812     Info.vol = false;
10813     Info.readMem = true;
10814     Info.writeMem = false;
10815     return true;
10816   }
10817   case Intrinsic::ppc_qpx_qvlfda:
10818   case Intrinsic::ppc_qpx_qvlfsa:
10819   case Intrinsic::ppc_qpx_qvlfcda:
10820   case Intrinsic::ppc_qpx_qvlfcsa:
10821   case Intrinsic::ppc_qpx_qvlfiwaa:
10822   case Intrinsic::ppc_qpx_qvlfiwza: {
10823     EVT VT;
10824     switch (Intrinsic) {
10825     case Intrinsic::ppc_qpx_qvlfda:
10826       VT = MVT::v4f64;
10827       break;
10828     case Intrinsic::ppc_qpx_qvlfsa:
10829       VT = MVT::v4f32;
10830       break;
10831     case Intrinsic::ppc_qpx_qvlfcda:
10832       VT = MVT::v2f64;
10833       break;
10834     case Intrinsic::ppc_qpx_qvlfcsa:
10835       VT = MVT::v2f32;
10836       break;
10837     default:
10838       VT = MVT::v4i32;
10839       break;
10840     }
10841
10842     Info.opc = ISD::INTRINSIC_W_CHAIN;
10843     Info.memVT = VT;
10844     Info.ptrVal = I.getArgOperand(0);
10845     Info.offset = 0;
10846     Info.size = VT.getStoreSize();
10847     Info.align = 1;
10848     Info.vol = false;
10849     Info.readMem = true;
10850     Info.writeMem = false;
10851     return true;
10852   }
10853   case Intrinsic::ppc_qpx_qvstfd:
10854   case Intrinsic::ppc_qpx_qvstfs:
10855   case Intrinsic::ppc_qpx_qvstfcd:
10856   case Intrinsic::ppc_qpx_qvstfcs:
10857   case Intrinsic::ppc_qpx_qvstfiw:
10858   case Intrinsic::ppc_altivec_stvx:
10859   case Intrinsic::ppc_altivec_stvxl:
10860   case Intrinsic::ppc_altivec_stvebx:
10861   case Intrinsic::ppc_altivec_stvehx:
10862   case Intrinsic::ppc_altivec_stvewx:
10863   case Intrinsic::ppc_vsx_stxvd2x:
10864   case Intrinsic::ppc_vsx_stxvw4x: {
10865     EVT VT;
10866     switch (Intrinsic) {
10867     case Intrinsic::ppc_altivec_stvebx:
10868       VT = MVT::i8;
10869       break;
10870     case Intrinsic::ppc_altivec_stvehx:
10871       VT = MVT::i16;
10872       break;
10873     case Intrinsic::ppc_altivec_stvewx:
10874       VT = MVT::i32;
10875       break;
10876     case Intrinsic::ppc_vsx_stxvd2x:
10877       VT = MVT::v2f64;
10878       break;
10879     case Intrinsic::ppc_qpx_qvstfd:
10880       VT = MVT::v4f64;
10881       break;
10882     case Intrinsic::ppc_qpx_qvstfs:
10883       VT = MVT::v4f32;
10884       break;
10885     case Intrinsic::ppc_qpx_qvstfcd:
10886       VT = MVT::v2f64;
10887       break;
10888     case Intrinsic::ppc_qpx_qvstfcs:
10889       VT = MVT::v2f32;
10890       break;
10891     default:
10892       VT = MVT::v4i32;
10893       break;
10894     }
10895
10896     Info.opc = ISD::INTRINSIC_VOID;
10897     Info.memVT = VT;
10898     Info.ptrVal = I.getArgOperand(1);
10899     Info.offset = -VT.getStoreSize()+1;
10900     Info.size = 2*VT.getStoreSize()-1;
10901     Info.align = 1;
10902     Info.vol = false;
10903     Info.readMem = false;
10904     Info.writeMem = true;
10905     return true;
10906   }
10907   case Intrinsic::ppc_qpx_qvstfda:
10908   case Intrinsic::ppc_qpx_qvstfsa:
10909   case Intrinsic::ppc_qpx_qvstfcda:
10910   case Intrinsic::ppc_qpx_qvstfcsa:
10911   case Intrinsic::ppc_qpx_qvstfiwa: {
10912     EVT VT;
10913     switch (Intrinsic) {
10914     case Intrinsic::ppc_qpx_qvstfda:
10915       VT = MVT::v4f64;
10916       break;
10917     case Intrinsic::ppc_qpx_qvstfsa:
10918       VT = MVT::v4f32;
10919       break;
10920     case Intrinsic::ppc_qpx_qvstfcda:
10921       VT = MVT::v2f64;
10922       break;
10923     case Intrinsic::ppc_qpx_qvstfcsa:
10924       VT = MVT::v2f32;
10925       break;
10926     default:
10927       VT = MVT::v4i32;
10928       break;
10929     }
10930
10931     Info.opc = ISD::INTRINSIC_VOID;
10932     Info.memVT = VT;
10933     Info.ptrVal = I.getArgOperand(1);
10934     Info.offset = 0;
10935     Info.size = VT.getStoreSize();
10936     Info.align = 1;
10937     Info.vol = false;
10938     Info.readMem = false;
10939     Info.writeMem = true;
10940     return true;
10941   }
10942   default:
10943     break;
10944   }
10945
10946   return false;
10947 }
10948
10949 /// getOptimalMemOpType - Returns the target specific optimal type for load
10950 /// and store operations as a result of memset, memcpy, and memmove
10951 /// lowering. If DstAlign is zero that means it's safe to destination
10952 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
10953 /// means there isn't a need to check it against alignment requirement,
10954 /// probably because the source does not need to be loaded. If 'IsMemset' is
10955 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
10956 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
10957 /// source is constant so it does not need to be loaded.
10958 /// It returns EVT::Other if the type should be determined using generic
10959 /// target-independent logic.
10960 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
10961                                            unsigned DstAlign, unsigned SrcAlign,
10962                                            bool IsMemset, bool ZeroMemset,
10963                                            bool MemcpyStrSrc,
10964                                            MachineFunction &MF) const {
10965   const Function *F = MF.getFunction();
10966   // When expanding a memset, require at least two QPX instructions to cover
10967   // the cost of loading the value to be stored from the constant pool.
10968   if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
10969      (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
10970       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10971     return MVT::v4f64;
10972   }
10973
10974   // We should use Altivec/VSX loads and stores when available. For unaligned
10975   // addresses, unaligned VSX loads are only fast starting with the P8.
10976   if (Subtarget.hasAltivec() && Size >= 16 &&
10977       (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
10978        ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
10979     return MVT::v4i32;
10980
10981   if (Subtarget.isPPC64()) {
10982     return MVT::i64;
10983   }
10984
10985   return MVT::i32;
10986 }
10987
10988 /// \brief Returns true if it is beneficial to convert a load of a constant
10989 /// to just the constant itself.
10990 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10991                                                           Type *Ty) const {
10992   assert(Ty->isIntegerTy());
10993
10994   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10995   if (BitSize == 0 || BitSize > 64)
10996     return false;
10997   return true;
10998 }
10999
11000 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11001   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11002     return false;
11003   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11004   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11005   return NumBits1 == 64 && NumBits2 == 32;
11006 }
11007
11008 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11009   if (!VT1.isInteger() || !VT2.isInteger())
11010     return false;
11011   unsigned NumBits1 = VT1.getSizeInBits();
11012   unsigned NumBits2 = VT2.getSizeInBits();
11013   return NumBits1 == 64 && NumBits2 == 32;
11014 }
11015
11016 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11017   // Generally speaking, zexts are not free, but they are free when they can be
11018   // folded with other operations.
11019   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11020     EVT MemVT = LD->getMemoryVT();
11021     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11022          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11023         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11024          LD->getExtensionType() == ISD::ZEXTLOAD))
11025       return true;
11026   }
11027
11028   // FIXME: Add other cases...
11029   //  - 32-bit shifts with a zext to i64
11030   //  - zext after ctlz, bswap, etc.
11031   //  - zext after and by a constant mask
11032
11033   return TargetLowering::isZExtFree(Val, VT2);
11034 }
11035
11036 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11037   assert(VT.isFloatingPoint());
11038   return true;
11039 }
11040
11041 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11042   return isInt<16>(Imm) || isUInt<16>(Imm);
11043 }
11044
11045 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11046   return isInt<16>(Imm) || isUInt<16>(Imm);
11047 }
11048
11049 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11050                                                        unsigned,
11051                                                        unsigned,
11052                                                        bool *Fast) const {
11053   if (DisablePPCUnaligned)
11054     return false;
11055
11056   // PowerPC supports unaligned memory access for simple non-vector types.
11057   // Although accessing unaligned addresses is not as efficient as accessing
11058   // aligned addresses, it is generally more efficient than manual expansion,
11059   // and generally only traps for software emulation when crossing page
11060   // boundaries.
11061
11062   if (!VT.isSimple())
11063     return false;
11064
11065   if (VT.getSimpleVT().isVector()) {
11066     if (Subtarget.hasVSX()) {
11067       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11068           VT != MVT::v4f32 && VT != MVT::v4i32)
11069         return false;
11070     } else {
11071       return false;
11072     }
11073   }
11074
11075   if (VT == MVT::ppcf128)
11076     return false;
11077
11078   if (Fast)
11079     *Fast = true;
11080
11081   return true;
11082 }
11083
11084 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11085   VT = VT.getScalarType();
11086
11087   if (!VT.isSimple())
11088     return false;
11089
11090   switch (VT.getSimpleVT().SimpleTy) {
11091   case MVT::f32:
11092   case MVT::f64:
11093     return true;
11094   default:
11095     break;
11096   }
11097
11098   return false;
11099 }
11100
11101 const MCPhysReg *
11102 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11103   // LR is a callee-save register, but we must treat it as clobbered by any call
11104   // site. Hence we include LR in the scratch registers, which are in turn added
11105   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11106   // to CTR, which is used by any indirect call.
11107   static const MCPhysReg ScratchRegs[] = {
11108     PPC::X12, PPC::LR8, PPC::CTR8, 0
11109   };
11110
11111   return ScratchRegs;
11112 }
11113
11114 bool
11115 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11116                      EVT VT , unsigned DefinedValues) const {
11117   if (VT == MVT::v2i64)
11118     return false;
11119
11120   if (Subtarget.hasQPX()) {
11121     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11122       return true;
11123   }
11124
11125   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11126 }
11127
11128 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11129   if (DisableILPPref || Subtarget.enableMachineScheduler())
11130     return TargetLowering::getSchedulingPreference(N);
11131
11132   return Sched::ILP;
11133 }
11134
11135 // Create a fast isel object.
11136 FastISel *
11137 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11138                                   const TargetLibraryInfo *LibInfo) const {
11139   return PPC::createFastISel(FuncInfo, LibInfo);
11140 }