[PowerPC] Use vector types for memcpy and friends (sometimes)
[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       // VSX v2i64 only supports non-arithmetic operations.
578       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
579       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
580
581       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
582       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
583       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
584
585       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
586
587       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
588       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
589       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
590       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
591
592       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
593
594       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
595       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
596       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
597       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
598
599       // Vector operation legalization checks the result type of
600       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
601       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
602       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
603       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
604       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
605
606       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
607     }
608
609     if (Subtarget.hasP8Altivec()) 
610       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
611   }
612
613   if (Subtarget.hasQPX()) {
614     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
615     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
616     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
617     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
618
619     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
620     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
621
622     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
623     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
624
625     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
626     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
627
628     if (!Subtarget.useCRBits())
629       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
630     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
631
632     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
633     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
634     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
635     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
636     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
637     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
638     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
639
640     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
641     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
642
643     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
644     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
645     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
646
647     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
648     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
649     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
650     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
651     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
652     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
653     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
654     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
655     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
656     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
657     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
658
659     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
660     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
661
662     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
663     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
664
665     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
666
667     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
668     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
669     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
670     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
671
672     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
673     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
674
675     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
676     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
677
678     if (!Subtarget.useCRBits())
679       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
680     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
681
682     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
683     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
684     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
687     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
688     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
689
690     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
691     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
692
693     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
694     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
695     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
696     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
697     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
698     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
699     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
700     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
701     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
702     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
703     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
704
705     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
706     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
707
708     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
709     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
710
711     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
712
713     setOperationAction(ISD::AND , MVT::v4i1, Legal);
714     setOperationAction(ISD::OR , MVT::v4i1, Legal);
715     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
716
717     if (!Subtarget.useCRBits())
718       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
719     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
720
721     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
722     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
723
724     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
725     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
726     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
727     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
728     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
729     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
730     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
731
732     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
733     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
734
735     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
736
737     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
738     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
739     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
740     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
741
742     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
743     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
744     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
745     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
746
747     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
748     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
749
750     // These need to set FE_INEXACT, and so cannot be vectorized here.
751     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
752     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
753
754     if (TM.Options.UnsafeFPMath) {
755       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
756       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
757
758       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
759       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
760     } else {
761       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
762       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
763
764       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
765       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
766     }
767   }
768
769   if (Subtarget.has64BitSupport())
770     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
771
772   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
773
774   if (!isPPC64) {
775     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
776     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
777   }
778
779   setBooleanContents(ZeroOrOneBooleanContent);
780
781   if (Subtarget.hasAltivec()) {
782     // Altivec instructions set fields to all zeros or all ones.
783     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
784   }
785
786   if (!isPPC64) {
787     // These libcalls are not available in 32-bit.
788     setLibcallName(RTLIB::SHL_I128, nullptr);
789     setLibcallName(RTLIB::SRL_I128, nullptr);
790     setLibcallName(RTLIB::SRA_I128, nullptr);
791   }
792
793   if (isPPC64) {
794     setStackPointerRegisterToSaveRestore(PPC::X1);
795     setExceptionPointerRegister(PPC::X3);
796     setExceptionSelectorRegister(PPC::X4);
797   } else {
798     setStackPointerRegisterToSaveRestore(PPC::R1);
799     setExceptionPointerRegister(PPC::R3);
800     setExceptionSelectorRegister(PPC::R4);
801   }
802
803   // We have target-specific dag combine patterns for the following nodes:
804   setTargetDAGCombine(ISD::SINT_TO_FP);
805   if (Subtarget.hasFPCVT())
806     setTargetDAGCombine(ISD::UINT_TO_FP);
807   setTargetDAGCombine(ISD::LOAD);
808   setTargetDAGCombine(ISD::STORE);
809   setTargetDAGCombine(ISD::BR_CC);
810   if (Subtarget.useCRBits())
811     setTargetDAGCombine(ISD::BRCOND);
812   setTargetDAGCombine(ISD::BSWAP);
813   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
814   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
815   setTargetDAGCombine(ISD::INTRINSIC_VOID);
816
817   setTargetDAGCombine(ISD::SIGN_EXTEND);
818   setTargetDAGCombine(ISD::ZERO_EXTEND);
819   setTargetDAGCombine(ISD::ANY_EXTEND);
820
821   if (Subtarget.useCRBits()) {
822     setTargetDAGCombine(ISD::TRUNCATE);
823     setTargetDAGCombine(ISD::SETCC);
824     setTargetDAGCombine(ISD::SELECT_CC);
825   }
826
827   // Use reciprocal estimates.
828   if (TM.Options.UnsafeFPMath) {
829     setTargetDAGCombine(ISD::FDIV);
830     setTargetDAGCombine(ISD::FSQRT);
831   }
832
833   // Darwin long double math library functions have $LDBL128 appended.
834   if (Subtarget.isDarwin()) {
835     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
836     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
837     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
838     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
839     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
840     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
841     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
842     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
843     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
844     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
845   }
846
847   // With 32 condition bits, we don't need to sink (and duplicate) compares
848   // aggressively in CodeGenPrep.
849   if (Subtarget.useCRBits()) {
850     setHasMultipleConditionRegisters();
851     setJumpIsExpensive();
852   }
853
854   setMinFunctionAlignment(2);
855   if (Subtarget.isDarwin())
856     setPrefFunctionAlignment(4);
857
858   switch (Subtarget.getDarwinDirective()) {
859   default: break;
860   case PPC::DIR_970:
861   case PPC::DIR_A2:
862   case PPC::DIR_E500mc:
863   case PPC::DIR_E5500:
864   case PPC::DIR_PWR4:
865   case PPC::DIR_PWR5:
866   case PPC::DIR_PWR5X:
867   case PPC::DIR_PWR6:
868   case PPC::DIR_PWR6X:
869   case PPC::DIR_PWR7:
870   case PPC::DIR_PWR8:
871     setPrefFunctionAlignment(4);
872     setPrefLoopAlignment(4);
873     break;
874   }
875
876   setInsertFencesForAtomic(true);
877
878   if (Subtarget.enableMachineScheduler())
879     setSchedulingPreference(Sched::Source);
880   else
881     setSchedulingPreference(Sched::Hybrid);
882
883   computeRegisterProperties(STI.getRegisterInfo());
884
885   // The Freescale cores do better with aggressive inlining of memcpy and
886   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
887   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
888       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
889     MaxStoresPerMemset = 32;
890     MaxStoresPerMemsetOptSize = 16;
891     MaxStoresPerMemcpy = 32;
892     MaxStoresPerMemcpyOptSize = 8;
893     MaxStoresPerMemmove = 32;
894     MaxStoresPerMemmoveOptSize = 8;
895   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
896     // The A2 also benefits from (very) aggressive inlining of memcpy and
897     // friends. The overhead of a the function call, even when warm, can be
898     // over one hundred cycles.
899     MaxStoresPerMemset = 128;
900     MaxStoresPerMemcpy = 128;
901     MaxStoresPerMemmove = 128;
902   }
903 }
904
905 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
906 /// the desired ByVal argument alignment.
907 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
908                              unsigned MaxMaxAlign) {
909   if (MaxAlign == MaxMaxAlign)
910     return;
911   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
912     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
913       MaxAlign = 32;
914     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
915       MaxAlign = 16;
916   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
917     unsigned EltAlign = 0;
918     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
919     if (EltAlign > MaxAlign)
920       MaxAlign = EltAlign;
921   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
922     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
923       unsigned EltAlign = 0;
924       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
925       if (EltAlign > MaxAlign)
926         MaxAlign = EltAlign;
927       if (MaxAlign == MaxMaxAlign)
928         break;
929     }
930   }
931 }
932
933 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
934 /// function arguments in the caller parameter area.
935 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
936   // Darwin passes everything on 4 byte boundary.
937   if (Subtarget.isDarwin())
938     return 4;
939
940   // 16byte and wider vectors are passed on 16byte boundary.
941   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
942   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
943   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
944     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
945   return Align;
946 }
947
948 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
949   switch (Opcode) {
950   default: return nullptr;
951   case PPCISD::FSEL:            return "PPCISD::FSEL";
952   case PPCISD::FCFID:           return "PPCISD::FCFID";
953   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
954   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
955   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
956   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
957   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
958   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
959   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
960   case PPCISD::FRE:             return "PPCISD::FRE";
961   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
962   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
963   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
964   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
965   case PPCISD::VPERM:           return "PPCISD::VPERM";
966   case PPCISD::CMPB:            return "PPCISD::CMPB";
967   case PPCISD::Hi:              return "PPCISD::Hi";
968   case PPCISD::Lo:              return "PPCISD::Lo";
969   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
970   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
971   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
972   case PPCISD::SRL:             return "PPCISD::SRL";
973   case PPCISD::SRA:             return "PPCISD::SRA";
974   case PPCISD::SHL:             return "PPCISD::SHL";
975   case PPCISD::CALL:            return "PPCISD::CALL";
976   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
977   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
978   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
979   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
980   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
981   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
982   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
983   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
984   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
985   case PPCISD::VCMP:            return "PPCISD::VCMP";
986   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
987   case PPCISD::LBRX:            return "PPCISD::LBRX";
988   case PPCISD::STBRX:           return "PPCISD::STBRX";
989   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
990   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
991   case PPCISD::LARX:            return "PPCISD::LARX";
992   case PPCISD::STCX:            return "PPCISD::STCX";
993   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
994   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
995   case PPCISD::BDZ:             return "PPCISD::BDZ";
996   case PPCISD::MFFS:            return "PPCISD::MFFS";
997   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
998   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
999   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1000   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1001   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1002   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1003   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1004   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1005   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1006   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1007   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1008   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1009   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1010   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1011   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1012   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1013   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1014   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1015   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1016   case PPCISD::SC:              return "PPCISD::SC";
1017   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1018   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1019   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1020   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1021   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1022   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1023   }
1024 }
1025
1026 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1027   if (!VT.isVector())
1028     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1029
1030   if (Subtarget.hasQPX())
1031     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1032
1033   return VT.changeVectorElementTypeToInteger();
1034 }
1035
1036 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1037   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1038   return true;
1039 }
1040
1041 //===----------------------------------------------------------------------===//
1042 // Node matching predicates, for use by the tblgen matching code.
1043 //===----------------------------------------------------------------------===//
1044
1045 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1046 static bool isFloatingPointZero(SDValue Op) {
1047   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1048     return CFP->getValueAPF().isZero();
1049   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1050     // Maybe this has already been legalized into the constant pool?
1051     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1052       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1053         return CFP->getValueAPF().isZero();
1054   }
1055   return false;
1056 }
1057
1058 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1059 /// true if Op is undef or if it matches the specified value.
1060 static bool isConstantOrUndef(int Op, int Val) {
1061   return Op < 0 || Op == Val;
1062 }
1063
1064 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1065 /// VPKUHUM instruction.
1066 /// The ShuffleKind distinguishes between big-endian operations with
1067 /// two different inputs (0), either-endian operations with two identical
1068 /// inputs (1), and little-endian operantion with two different inputs (2).
1069 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1070 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1071                                SelectionDAG &DAG) {
1072   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1073   if (ShuffleKind == 0) {
1074     if (IsLE)
1075       return false;
1076     for (unsigned i = 0; i != 16; ++i)
1077       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1078         return false;
1079   } else if (ShuffleKind == 2) {
1080     if (!IsLE)
1081       return false;
1082     for (unsigned i = 0; i != 16; ++i)
1083       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1084         return false;
1085   } else if (ShuffleKind == 1) {
1086     unsigned j = IsLE ? 0 : 1;
1087     for (unsigned i = 0; i != 8; ++i)
1088       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1089           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1090         return false;
1091   }
1092   return true;
1093 }
1094
1095 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1096 /// VPKUWUM instruction.
1097 /// The ShuffleKind distinguishes between big-endian operations with
1098 /// two different inputs (0), either-endian operations with two identical
1099 /// inputs (1), and little-endian operantion with two different inputs (2).
1100 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1101 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1102                                SelectionDAG &DAG) {
1103   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1104   if (ShuffleKind == 0) {
1105     if (IsLE)
1106       return false;
1107     for (unsigned i = 0; i != 16; i += 2)
1108       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1109           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1110         return false;
1111   } else if (ShuffleKind == 2) {
1112     if (!IsLE)
1113       return false;
1114     for (unsigned i = 0; i != 16; i += 2)
1115       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1116           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1117         return false;
1118   } else if (ShuffleKind == 1) {
1119     unsigned j = IsLE ? 0 : 2;
1120     for (unsigned i = 0; i != 8; i += 2)
1121       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1122           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1123           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1124           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1125         return false;
1126   }
1127   return true;
1128 }
1129
1130 /// isVMerge - Common function, used to match vmrg* shuffles.
1131 ///
1132 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1133                      unsigned LHSStart, unsigned RHSStart) {
1134   if (N->getValueType(0) != MVT::v16i8)
1135     return false;
1136   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1137          "Unsupported merge size!");
1138
1139   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1140     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1141       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1142                              LHSStart+j+i*UnitSize) ||
1143           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1144                              RHSStart+j+i*UnitSize))
1145         return false;
1146     }
1147   return true;
1148 }
1149
1150 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1151 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1152 /// The ShuffleKind distinguishes between big-endian merges with two 
1153 /// different inputs (0), either-endian merges with two identical inputs (1),
1154 /// and little-endian merges with two different inputs (2).  For the latter,
1155 /// the input operands are swapped (see PPCInstrAltivec.td).
1156 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1157                              unsigned ShuffleKind, SelectionDAG &DAG) {
1158   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1159     if (ShuffleKind == 1) // unary
1160       return isVMerge(N, UnitSize, 0, 0);
1161     else if (ShuffleKind == 2) // swapped
1162       return isVMerge(N, UnitSize, 0, 16);
1163     else
1164       return false;
1165   } else {
1166     if (ShuffleKind == 1) // unary
1167       return isVMerge(N, UnitSize, 8, 8);
1168     else if (ShuffleKind == 0) // normal
1169       return isVMerge(N, UnitSize, 8, 24);
1170     else
1171       return false;
1172   }
1173 }
1174
1175 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1176 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1177 /// The ShuffleKind distinguishes between big-endian merges with two 
1178 /// different inputs (0), either-endian merges with two identical inputs (1),
1179 /// and little-endian merges with two different inputs (2).  For the latter,
1180 /// the input operands are swapped (see PPCInstrAltivec.td).
1181 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1182                              unsigned ShuffleKind, SelectionDAG &DAG) {
1183   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1184     if (ShuffleKind == 1) // unary
1185       return isVMerge(N, UnitSize, 8, 8);
1186     else if (ShuffleKind == 2) // swapped
1187       return isVMerge(N, UnitSize, 8, 24);
1188     else
1189       return false;
1190   } else {
1191     if (ShuffleKind == 1) // unary
1192       return isVMerge(N, UnitSize, 0, 0);
1193     else if (ShuffleKind == 0) // normal
1194       return isVMerge(N, UnitSize, 0, 16);
1195     else
1196       return false;
1197   }
1198 }
1199
1200
1201 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1202 /// amount, otherwise return -1.
1203 /// The ShuffleKind distinguishes between big-endian operations with two 
1204 /// different inputs (0), either-endian operations with two identical inputs
1205 /// (1), and little-endian operations with two different inputs (2).  For the
1206 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1207 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1208                              SelectionDAG &DAG) {
1209   if (N->getValueType(0) != MVT::v16i8)
1210     return -1;
1211
1212   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1213
1214   // Find the first non-undef value in the shuffle mask.
1215   unsigned i;
1216   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1217     /*search*/;
1218
1219   if (i == 16) return -1;  // all undef.
1220
1221   // Otherwise, check to see if the rest of the elements are consecutively
1222   // numbered from this value.
1223   unsigned ShiftAmt = SVOp->getMaskElt(i);
1224   if (ShiftAmt < i) return -1;
1225
1226   ShiftAmt -= i;
1227   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1228
1229   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1230     // Check the rest of the elements to see if they are consecutive.
1231     for (++i; i != 16; ++i)
1232       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1233         return -1;
1234   } else if (ShuffleKind == 1) {
1235     // Check the rest of the elements to see if they are consecutive.
1236     for (++i; i != 16; ++i)
1237       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1238         return -1;
1239   } else
1240     return -1;
1241
1242   if (ShuffleKind == 2 && isLE)
1243     ShiftAmt = 16 - ShiftAmt;
1244
1245   return ShiftAmt;
1246 }
1247
1248 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1249 /// specifies a splat of a single element that is suitable for input to
1250 /// VSPLTB/VSPLTH/VSPLTW.
1251 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1252   assert(N->getValueType(0) == MVT::v16i8 &&
1253          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1254
1255   // This is a splat operation if each element of the permute is the same, and
1256   // if the value doesn't reference the second vector.
1257   unsigned ElementBase = N->getMaskElt(0);
1258
1259   // FIXME: Handle UNDEF elements too!
1260   if (ElementBase >= 16)
1261     return false;
1262
1263   // Check that the indices are consecutive, in the case of a multi-byte element
1264   // splatted with a v16i8 mask.
1265   for (unsigned i = 1; i != EltSize; ++i)
1266     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1267       return false;
1268
1269   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1270     if (N->getMaskElt(i) < 0) continue;
1271     for (unsigned j = 0; j != EltSize; ++j)
1272       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1273         return false;
1274   }
1275   return true;
1276 }
1277
1278 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1279 /// are -0.0.
1280 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1281   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1282
1283   APInt APVal, APUndef;
1284   unsigned BitSize;
1285   bool HasAnyUndefs;
1286
1287   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1288     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1289       return CFP->getValueAPF().isNegZero();
1290
1291   return false;
1292 }
1293
1294 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1295 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1296 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1297                                 SelectionDAG &DAG) {
1298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1299   assert(isSplatShuffleMask(SVOp, EltSize));
1300   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1301     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1302   else
1303     return SVOp->getMaskElt(0) / EltSize;
1304 }
1305
1306 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1307 /// by using a vspltis[bhw] instruction of the specified element size, return
1308 /// the constant being splatted.  The ByteSize field indicates the number of
1309 /// bytes of each element [124] -> [bhw].
1310 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1311   SDValue OpVal(nullptr, 0);
1312
1313   // If ByteSize of the splat is bigger than the element size of the
1314   // build_vector, then we have a case where we are checking for a splat where
1315   // multiple elements of the buildvector are folded together into a single
1316   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1317   unsigned EltSize = 16/N->getNumOperands();
1318   if (EltSize < ByteSize) {
1319     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1320     SDValue UniquedVals[4];
1321     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1322
1323     // See if all of the elements in the buildvector agree across.
1324     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1325       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1326       // If the element isn't a constant, bail fully out.
1327       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1328
1329
1330       if (!UniquedVals[i&(Multiple-1)].getNode())
1331         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1332       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1333         return SDValue();  // no match.
1334     }
1335
1336     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1337     // either constant or undef values that are identical for each chunk.  See
1338     // if these chunks can form into a larger vspltis*.
1339
1340     // Check to see if all of the leading entries are either 0 or -1.  If
1341     // neither, then this won't fit into the immediate field.
1342     bool LeadingZero = true;
1343     bool LeadingOnes = true;
1344     for (unsigned i = 0; i != Multiple-1; ++i) {
1345       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1346
1347       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1348       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1349     }
1350     // Finally, check the least significant entry.
1351     if (LeadingZero) {
1352       if (!UniquedVals[Multiple-1].getNode())
1353         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1354       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1355       if (Val < 16)
1356         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1357     }
1358     if (LeadingOnes) {
1359       if (!UniquedVals[Multiple-1].getNode())
1360         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1361       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1362       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1363         return DAG.getTargetConstant(Val, MVT::i32);
1364     }
1365
1366     return SDValue();
1367   }
1368
1369   // Check to see if this buildvec has a single non-undef value in its elements.
1370   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1371     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1372     if (!OpVal.getNode())
1373       OpVal = N->getOperand(i);
1374     else if (OpVal != N->getOperand(i))
1375       return SDValue();
1376   }
1377
1378   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1379
1380   unsigned ValSizeInBytes = EltSize;
1381   uint64_t Value = 0;
1382   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1383     Value = CN->getZExtValue();
1384   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1385     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1386     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1387   }
1388
1389   // If the splat value is larger than the element value, then we can never do
1390   // this splat.  The only case that we could fit the replicated bits into our
1391   // immediate field for would be zero, and we prefer to use vxor for it.
1392   if (ValSizeInBytes < ByteSize) return SDValue();
1393
1394   // If the element value is larger than the splat value, cut it in half and
1395   // check to see if the two halves are equal.  Continue doing this until we
1396   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1397   while (ValSizeInBytes > ByteSize) {
1398     ValSizeInBytes >>= 1;
1399
1400     // If the top half equals the bottom half, we're still ok.
1401     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1402          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1403       return SDValue();
1404   }
1405
1406   // Properly sign extend the value.
1407   int MaskVal = SignExtend32(Value, ByteSize * 8);
1408
1409   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1410   if (MaskVal == 0) return SDValue();
1411
1412   // Finally, if this value fits in a 5 bit sext field, return it
1413   if (SignExtend32<5>(MaskVal) == MaskVal)
1414     return DAG.getTargetConstant(MaskVal, MVT::i32);
1415   return SDValue();
1416 }
1417
1418 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1419 /// amount, otherwise return -1.
1420 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1421   EVT VT = N->getValueType(0);
1422   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1423     return -1;
1424
1425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1426
1427   // Find the first non-undef value in the shuffle mask.
1428   unsigned i;
1429   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1430     /*search*/;
1431
1432   if (i == 4) return -1;  // all undef.
1433
1434   // Otherwise, check to see if the rest of the elements are consecutively
1435   // numbered from this value.
1436   unsigned ShiftAmt = SVOp->getMaskElt(i);
1437   if (ShiftAmt < i) return -1;
1438   ShiftAmt -= i;
1439
1440   // Check the rest of the elements to see if they are consecutive.
1441   for (++i; i != 4; ++i)
1442     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1443       return -1;
1444
1445   return ShiftAmt;
1446 }
1447
1448 //===----------------------------------------------------------------------===//
1449 //  Addressing Mode Selection
1450 //===----------------------------------------------------------------------===//
1451
1452 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1453 /// or 64-bit immediate, and if the value can be accurately represented as a
1454 /// sign extension from a 16-bit value.  If so, this returns true and the
1455 /// immediate.
1456 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1457   if (!isa<ConstantSDNode>(N))
1458     return false;
1459
1460   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1461   if (N->getValueType(0) == MVT::i32)
1462     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1463   else
1464     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1465 }
1466 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1467   return isIntS16Immediate(Op.getNode(), Imm);
1468 }
1469
1470
1471 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1472 /// can be represented as an indexed [r+r] operation.  Returns false if it
1473 /// can be more efficiently represented with [r+imm].
1474 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1475                                             SDValue &Index,
1476                                             SelectionDAG &DAG) const {
1477   short imm = 0;
1478   if (N.getOpcode() == ISD::ADD) {
1479     if (isIntS16Immediate(N.getOperand(1), imm))
1480       return false;    // r+i
1481     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1482       return false;    // r+i
1483
1484     Base = N.getOperand(0);
1485     Index = N.getOperand(1);
1486     return true;
1487   } else if (N.getOpcode() == ISD::OR) {
1488     if (isIntS16Immediate(N.getOperand(1), imm))
1489       return false;    // r+i can fold it if we can.
1490
1491     // If this is an or of disjoint bitfields, we can codegen this as an add
1492     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1493     // disjoint.
1494     APInt LHSKnownZero, LHSKnownOne;
1495     APInt RHSKnownZero, RHSKnownOne;
1496     DAG.computeKnownBits(N.getOperand(0),
1497                          LHSKnownZero, LHSKnownOne);
1498
1499     if (LHSKnownZero.getBoolValue()) {
1500       DAG.computeKnownBits(N.getOperand(1),
1501                            RHSKnownZero, RHSKnownOne);
1502       // If all of the bits are known zero on the LHS or RHS, the add won't
1503       // carry.
1504       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1505         Base = N.getOperand(0);
1506         Index = N.getOperand(1);
1507         return true;
1508       }
1509     }
1510   }
1511
1512   return false;
1513 }
1514
1515 // If we happen to be doing an i64 load or store into a stack slot that has
1516 // less than a 4-byte alignment, then the frame-index elimination may need to
1517 // use an indexed load or store instruction (because the offset may not be a
1518 // multiple of 4). The extra register needed to hold the offset comes from the
1519 // register scavenger, and it is possible that the scavenger will need to use
1520 // an emergency spill slot. As a result, we need to make sure that a spill slot
1521 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1522 // stack slot.
1523 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1524   // FIXME: This does not handle the LWA case.
1525   if (VT != MVT::i64)
1526     return;
1527
1528   // NOTE: We'll exclude negative FIs here, which come from argument
1529   // lowering, because there are no known test cases triggering this problem
1530   // using packed structures (or similar). We can remove this exclusion if
1531   // we find such a test case. The reason why this is so test-case driven is
1532   // because this entire 'fixup' is only to prevent crashes (from the
1533   // register scavenger) on not-really-valid inputs. For example, if we have:
1534   //   %a = alloca i1
1535   //   %b = bitcast i1* %a to i64*
1536   //   store i64* a, i64 b
1537   // then the store should really be marked as 'align 1', but is not. If it
1538   // were marked as 'align 1' then the indexed form would have been
1539   // instruction-selected initially, and the problem this 'fixup' is preventing
1540   // won't happen regardless.
1541   if (FrameIdx < 0)
1542     return;
1543
1544   MachineFunction &MF = DAG.getMachineFunction();
1545   MachineFrameInfo *MFI = MF.getFrameInfo();
1546
1547   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1548   if (Align >= 4)
1549     return;
1550
1551   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1552   FuncInfo->setHasNonRISpills();
1553 }
1554
1555 /// Returns true if the address N can be represented by a base register plus
1556 /// a signed 16-bit displacement [r+imm], and if it is not better
1557 /// represented as reg+reg.  If Aligned is true, only accept displacements
1558 /// suitable for STD and friends, i.e. multiples of 4.
1559 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1560                                             SDValue &Base,
1561                                             SelectionDAG &DAG,
1562                                             bool Aligned) const {
1563   // FIXME dl should come from parent load or store, not from address
1564   SDLoc dl(N);
1565   // If this can be more profitably realized as r+r, fail.
1566   if (SelectAddressRegReg(N, Disp, Base, DAG))
1567     return false;
1568
1569   if (N.getOpcode() == ISD::ADD) {
1570     short imm = 0;
1571     if (isIntS16Immediate(N.getOperand(1), imm) &&
1572         (!Aligned || (imm & 3) == 0)) {
1573       Disp = DAG.getTargetConstant(imm, N.getValueType());
1574       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1575         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1576         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1577       } else {
1578         Base = N.getOperand(0);
1579       }
1580       return true; // [r+i]
1581     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1582       // Match LOAD (ADD (X, Lo(G))).
1583       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1584              && "Cannot handle constant offsets yet!");
1585       Disp = N.getOperand(1).getOperand(0);  // The global address.
1586       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1587              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1588              Disp.getOpcode() == ISD::TargetConstantPool ||
1589              Disp.getOpcode() == ISD::TargetJumpTable);
1590       Base = N.getOperand(0);
1591       return true;  // [&g+r]
1592     }
1593   } else if (N.getOpcode() == ISD::OR) {
1594     short imm = 0;
1595     if (isIntS16Immediate(N.getOperand(1), imm) &&
1596         (!Aligned || (imm & 3) == 0)) {
1597       // If this is an or of disjoint bitfields, we can codegen this as an add
1598       // (for better address arithmetic) if the LHS and RHS of the OR are
1599       // provably disjoint.
1600       APInt LHSKnownZero, LHSKnownOne;
1601       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1602
1603       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1604         // If all of the bits are known zero on the LHS or RHS, the add won't
1605         // carry.
1606         if (FrameIndexSDNode *FI =
1607               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1608           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1609           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1610         } else {
1611           Base = N.getOperand(0);
1612         }
1613         Disp = DAG.getTargetConstant(imm, N.getValueType());
1614         return true;
1615       }
1616     }
1617   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1618     // Loading from a constant address.
1619
1620     // If this address fits entirely in a 16-bit sext immediate field, codegen
1621     // this as "d, 0"
1622     short Imm;
1623     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1624       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1625       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1626                              CN->getValueType(0));
1627       return true;
1628     }
1629
1630     // Handle 32-bit sext immediates with LIS + addr mode.
1631     if ((CN->getValueType(0) == MVT::i32 ||
1632          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1633         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1634       int Addr = (int)CN->getZExtValue();
1635
1636       // Otherwise, break this down into an LIS + disp.
1637       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1638
1639       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1640       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1641       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1642       return true;
1643     }
1644   }
1645
1646   Disp = DAG.getTargetConstant(0, getPointerTy());
1647   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1648     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1649     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1650   } else
1651     Base = N;
1652   return true;      // [r+0]
1653 }
1654
1655 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1656 /// represented as an indexed [r+r] operation.
1657 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1658                                                 SDValue &Index,
1659                                                 SelectionDAG &DAG) const {
1660   // Check to see if we can easily represent this as an [r+r] address.  This
1661   // will fail if it thinks that the address is more profitably represented as
1662   // reg+imm, e.g. where imm = 0.
1663   if (SelectAddressRegReg(N, Base, Index, DAG))
1664     return true;
1665
1666   // If the operand is an addition, always emit this as [r+r], since this is
1667   // better (for code size, and execution, as the memop does the add for free)
1668   // than emitting an explicit add.
1669   if (N.getOpcode() == ISD::ADD) {
1670     Base = N.getOperand(0);
1671     Index = N.getOperand(1);
1672     return true;
1673   }
1674
1675   // Otherwise, do it the hard way, using R0 as the base register.
1676   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1677                          N.getValueType());
1678   Index = N;
1679   return true;
1680 }
1681
1682 /// getPreIndexedAddressParts - returns true by value, base pointer and
1683 /// offset pointer and addressing mode by reference if the node's address
1684 /// can be legally represented as pre-indexed load / store address.
1685 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1686                                                   SDValue &Offset,
1687                                                   ISD::MemIndexedMode &AM,
1688                                                   SelectionDAG &DAG) const {
1689   if (DisablePPCPreinc) return false;
1690
1691   bool isLoad = true;
1692   SDValue Ptr;
1693   EVT VT;
1694   unsigned Alignment;
1695   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1696     Ptr = LD->getBasePtr();
1697     VT = LD->getMemoryVT();
1698     Alignment = LD->getAlignment();
1699   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1700     Ptr = ST->getBasePtr();
1701     VT  = ST->getMemoryVT();
1702     Alignment = ST->getAlignment();
1703     isLoad = false;
1704   } else
1705     return false;
1706
1707   // PowerPC doesn't have preinc load/store instructions for vectors (except
1708   // for QPX, which does have preinc r+r forms).
1709   if (VT.isVector()) {
1710     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1711       return false;
1712     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1713       AM = ISD::PRE_INC;
1714       return true;
1715     }
1716   }
1717
1718   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1719
1720     // Common code will reject creating a pre-inc form if the base pointer
1721     // is a frame index, or if N is a store and the base pointer is either
1722     // the same as or a predecessor of the value being stored.  Check for
1723     // those situations here, and try with swapped Base/Offset instead.
1724     bool Swap = false;
1725
1726     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1727       Swap = true;
1728     else if (!isLoad) {
1729       SDValue Val = cast<StoreSDNode>(N)->getValue();
1730       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1731         Swap = true;
1732     }
1733
1734     if (Swap)
1735       std::swap(Base, Offset);
1736
1737     AM = ISD::PRE_INC;
1738     return true;
1739   }
1740
1741   // LDU/STU can only handle immediates that are a multiple of 4.
1742   if (VT != MVT::i64) {
1743     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1744       return false;
1745   } else {
1746     // LDU/STU need an address with at least 4-byte alignment.
1747     if (Alignment < 4)
1748       return false;
1749
1750     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1751       return false;
1752   }
1753
1754   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1755     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1756     // sext i32 to i64 when addr mode is r+i.
1757     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1758         LD->getExtensionType() == ISD::SEXTLOAD &&
1759         isa<ConstantSDNode>(Offset))
1760       return false;
1761   }
1762
1763   AM = ISD::PRE_INC;
1764   return true;
1765 }
1766
1767 //===----------------------------------------------------------------------===//
1768 //  LowerOperation implementation
1769 //===----------------------------------------------------------------------===//
1770
1771 /// GetLabelAccessInfo - Return true if we should reference labels using a
1772 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1773 static bool GetLabelAccessInfo(const TargetMachine &TM,
1774                                const PPCSubtarget &Subtarget,
1775                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1776                                const GlobalValue *GV = nullptr) {
1777   HiOpFlags = PPCII::MO_HA;
1778   LoOpFlags = PPCII::MO_LO;
1779
1780   // Don't use the pic base if not in PIC relocation model.
1781   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1782
1783   if (isPIC) {
1784     HiOpFlags |= PPCII::MO_PIC_FLAG;
1785     LoOpFlags |= PPCII::MO_PIC_FLAG;
1786   }
1787
1788   // If this is a reference to a global value that requires a non-lazy-ptr, make
1789   // sure that instruction lowering adds it.
1790   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1791     HiOpFlags |= PPCII::MO_NLP_FLAG;
1792     LoOpFlags |= PPCII::MO_NLP_FLAG;
1793
1794     if (GV->hasHiddenVisibility()) {
1795       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1796       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1797     }
1798   }
1799
1800   return isPIC;
1801 }
1802
1803 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1804                              SelectionDAG &DAG) {
1805   EVT PtrVT = HiPart.getValueType();
1806   SDValue Zero = DAG.getConstant(0, PtrVT);
1807   SDLoc DL(HiPart);
1808
1809   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1810   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1811
1812   // With PIC, the first instruction is actually "GR+hi(&G)".
1813   if (isPIC)
1814     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1815                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1816
1817   // Generate non-pic code that has direct accesses to the constant pool.
1818   // The address of the global is just (hi(&g)+lo(&g)).
1819   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1820 }
1821
1822 static void setUsesTOCBasePtr(MachineFunction &MF) {
1823   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1824   FuncInfo->setUsesTOCBasePtr();
1825 }
1826
1827 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1828   setUsesTOCBasePtr(DAG.getMachineFunction());
1829 }
1830
1831 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1832                            SDValue GA) {
1833   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1834   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1835                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1836
1837   SDValue Ops[] = { GA, Reg };
1838   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1839                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1840                                  MachinePointerInfo::getGOT(), 0, false, true,
1841                                  false, 0);
1842 }
1843
1844 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1845                                              SelectionDAG &DAG) const {
1846   EVT PtrVT = Op.getValueType();
1847   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1848   const Constant *C = CP->getConstVal();
1849
1850   // 64-bit SVR4 ABI code is always position-independent.
1851   // The actual address of the GlobalValue is stored in the TOC.
1852   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1853     setUsesTOCBasePtr(DAG);
1854     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1855     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1856   }
1857
1858   unsigned MOHiFlag, MOLoFlag;
1859   bool isPIC =
1860       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1861
1862   if (isPIC && Subtarget.isSVR4ABI()) {
1863     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1864                                            PPCII::MO_PIC_FLAG);
1865     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1866   }
1867
1868   SDValue CPIHi =
1869     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1870   SDValue CPILo =
1871     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1872   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1873 }
1874
1875 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1876   EVT PtrVT = Op.getValueType();
1877   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1878
1879   // 64-bit SVR4 ABI code is always position-independent.
1880   // The actual address of the GlobalValue is stored in the TOC.
1881   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1882     setUsesTOCBasePtr(DAG);
1883     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1884     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1885   }
1886
1887   unsigned MOHiFlag, MOLoFlag;
1888   bool isPIC =
1889       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1890
1891   if (isPIC && Subtarget.isSVR4ABI()) {
1892     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1893                                         PPCII::MO_PIC_FLAG);
1894     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1895   }
1896
1897   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1898   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1899   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1900 }
1901
1902 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1903                                              SelectionDAG &DAG) const {
1904   EVT PtrVT = Op.getValueType();
1905   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1906   const BlockAddress *BA = BASDN->getBlockAddress();
1907
1908   // 64-bit SVR4 ABI code is always position-independent.
1909   // The actual BlockAddress is stored in the TOC.
1910   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1911     setUsesTOCBasePtr(DAG);
1912     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1913     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1914   }
1915
1916   unsigned MOHiFlag, MOLoFlag;
1917   bool isPIC =
1918       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1919   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1920   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1921   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1922 }
1923
1924 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1925                                               SelectionDAG &DAG) const {
1926
1927   // FIXME: TLS addresses currently use medium model code sequences,
1928   // which is the most useful form.  Eventually support for small and
1929   // large models could be added if users need it, at the cost of
1930   // additional complexity.
1931   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1932   SDLoc dl(GA);
1933   const GlobalValue *GV = GA->getGlobal();
1934   EVT PtrVT = getPointerTy();
1935   bool is64bit = Subtarget.isPPC64();
1936   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1937   PICLevel::Level picLevel = M->getPICLevel();
1938
1939   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1940
1941   if (Model == TLSModel::LocalExec) {
1942     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1943                                                PPCII::MO_TPREL_HA);
1944     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1945                                                PPCII::MO_TPREL_LO);
1946     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1947                                      is64bit ? MVT::i64 : MVT::i32);
1948     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1949     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1950   }
1951
1952   if (Model == TLSModel::InitialExec) {
1953     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1954     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1955                                                 PPCII::MO_TLS);
1956     SDValue GOTPtr;
1957     if (is64bit) {
1958       setUsesTOCBasePtr(DAG);
1959       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1960       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1961                            PtrVT, GOTReg, TGA);
1962     } else
1963       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1964     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1965                                    PtrVT, TGA, GOTPtr);
1966     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1967   }
1968
1969   if (Model == TLSModel::GeneralDynamic) {
1970     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1971     SDValue GOTPtr;
1972     if (is64bit) {
1973       setUsesTOCBasePtr(DAG);
1974       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1975       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1976                                    GOTReg, TGA);
1977     } else {
1978       if (picLevel == PICLevel::Small)
1979         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1980       else
1981         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1982     }
1983     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1984                        GOTPtr, TGA, TGA);
1985   }
1986
1987   if (Model == TLSModel::LocalDynamic) {
1988     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1989     SDValue GOTPtr;
1990     if (is64bit) {
1991       setUsesTOCBasePtr(DAG);
1992       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1993       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1994                            GOTReg, TGA);
1995     } else {
1996       if (picLevel == PICLevel::Small)
1997         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1998       else
1999         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2000     }
2001     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2002                                   PtrVT, GOTPtr, TGA, TGA);
2003     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2004                                       PtrVT, TLSAddr, TGA);
2005     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2006   }
2007
2008   llvm_unreachable("Unknown TLS model!");
2009 }
2010
2011 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2012                                               SelectionDAG &DAG) const {
2013   EVT PtrVT = Op.getValueType();
2014   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2015   SDLoc DL(GSDN);
2016   const GlobalValue *GV = GSDN->getGlobal();
2017
2018   // 64-bit SVR4 ABI code is always position-independent.
2019   // The actual address of the GlobalValue is stored in the TOC.
2020   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2021     setUsesTOCBasePtr(DAG);
2022     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2023     return getTOCEntry(DAG, DL, true, GA);
2024   }
2025
2026   unsigned MOHiFlag, MOLoFlag;
2027   bool isPIC =
2028       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2029
2030   if (isPIC && Subtarget.isSVR4ABI()) {
2031     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2032                                             GSDN->getOffset(),
2033                                             PPCII::MO_PIC_FLAG);
2034     return getTOCEntry(DAG, DL, false, GA);
2035   }
2036
2037   SDValue GAHi =
2038     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2039   SDValue GALo =
2040     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2041
2042   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2043
2044   // If the global reference is actually to a non-lazy-pointer, we have to do an
2045   // extra load to get the address of the global.
2046   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2047     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2048                       false, false, false, 0);
2049   return Ptr;
2050 }
2051
2052 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2053   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2054   SDLoc dl(Op);
2055
2056   if (Op.getValueType() == MVT::v2i64) {
2057     // When the operands themselves are v2i64 values, we need to do something
2058     // special because VSX has no underlying comparison operations for these.
2059     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2060       // Equality can be handled by casting to the legal type for Altivec
2061       // comparisons, everything else needs to be expanded.
2062       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2063         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2064                  DAG.getSetCC(dl, MVT::v4i32,
2065                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2066                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2067                    CC));
2068       }
2069
2070       return SDValue();
2071     }
2072
2073     // We handle most of these in the usual way.
2074     return Op;
2075   }
2076
2077   // If we're comparing for equality to zero, expose the fact that this is
2078   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2079   // fold the new nodes.
2080   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2081     if (C->isNullValue() && CC == ISD::SETEQ) {
2082       EVT VT = Op.getOperand(0).getValueType();
2083       SDValue Zext = Op.getOperand(0);
2084       if (VT.bitsLT(MVT::i32)) {
2085         VT = MVT::i32;
2086         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2087       }
2088       unsigned Log2b = Log2_32(VT.getSizeInBits());
2089       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2090       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2091                                 DAG.getConstant(Log2b, MVT::i32));
2092       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2093     }
2094     // Leave comparisons against 0 and -1 alone for now, since they're usually
2095     // optimized.  FIXME: revisit this when we can custom lower all setcc
2096     // optimizations.
2097     if (C->isAllOnesValue() || C->isNullValue())
2098       return SDValue();
2099   }
2100
2101   // If we have an integer seteq/setne, turn it into a compare against zero
2102   // by xor'ing the rhs with the lhs, which is faster than setting a
2103   // condition register, reading it back out, and masking the correct bit.  The
2104   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2105   // the result to other bit-twiddling opportunities.
2106   EVT LHSVT = Op.getOperand(0).getValueType();
2107   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2108     EVT VT = Op.getValueType();
2109     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2110                                 Op.getOperand(1));
2111     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2112   }
2113   return SDValue();
2114 }
2115
2116 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2117                                       const PPCSubtarget &Subtarget) const {
2118   SDNode *Node = Op.getNode();
2119   EVT VT = Node->getValueType(0);
2120   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2121   SDValue InChain = Node->getOperand(0);
2122   SDValue VAListPtr = Node->getOperand(1);
2123   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2124   SDLoc dl(Node);
2125
2126   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2127
2128   // gpr_index
2129   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2130                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2131                                     false, false, false, 0);
2132   InChain = GprIndex.getValue(1);
2133
2134   if (VT == MVT::i64) {
2135     // Check if GprIndex is even
2136     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2137                                  DAG.getConstant(1, MVT::i32));
2138     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2139                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2140     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2141                                           DAG.getConstant(1, MVT::i32));
2142     // Align GprIndex to be even if it isn't
2143     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2144                            GprIndex);
2145   }
2146
2147   // fpr index is 1 byte after gpr
2148   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2149                                DAG.getConstant(1, MVT::i32));
2150
2151   // fpr
2152   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2153                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2154                                     false, false, false, 0);
2155   InChain = FprIndex.getValue(1);
2156
2157   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2158                                        DAG.getConstant(8, MVT::i32));
2159
2160   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2161                                         DAG.getConstant(4, MVT::i32));
2162
2163   // areas
2164   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2165                                      MachinePointerInfo(), false, false,
2166                                      false, 0);
2167   InChain = OverflowArea.getValue(1);
2168
2169   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2170                                     MachinePointerInfo(), false, false,
2171                                     false, 0);
2172   InChain = RegSaveArea.getValue(1);
2173
2174   // select overflow_area if index > 8
2175   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2176                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2177
2178   // adjustment constant gpr_index * 4/8
2179   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2180                                     VT.isInteger() ? GprIndex : FprIndex,
2181                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2182                                                     MVT::i32));
2183
2184   // OurReg = RegSaveArea + RegConstant
2185   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2186                                RegConstant);
2187
2188   // Floating types are 32 bytes into RegSaveArea
2189   if (VT.isFloatingPoint())
2190     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2191                          DAG.getConstant(32, MVT::i32));
2192
2193   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2194   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2195                                    VT.isInteger() ? GprIndex : FprIndex,
2196                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2197                                                    MVT::i32));
2198
2199   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2200                               VT.isInteger() ? VAListPtr : FprPtr,
2201                               MachinePointerInfo(SV),
2202                               MVT::i8, false, false, 0);
2203
2204   // determine if we should load from reg_save_area or overflow_area
2205   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2206
2207   // increase overflow_area by 4/8 if gpr/fpr > 8
2208   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2209                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2210                                           MVT::i32));
2211
2212   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2213                              OverflowAreaPlusN);
2214
2215   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2216                               OverflowAreaPtr,
2217                               MachinePointerInfo(),
2218                               MVT::i32, false, false, 0);
2219
2220   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2221                      false, false, false, 0);
2222 }
2223
2224 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2225                                        const PPCSubtarget &Subtarget) const {
2226   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2227
2228   // We have to copy the entire va_list struct:
2229   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2230   return DAG.getMemcpy(Op.getOperand(0), Op,
2231                        Op.getOperand(1), Op.getOperand(2),
2232                        DAG.getConstant(12, MVT::i32), 8, false, true,
2233                        MachinePointerInfo(), MachinePointerInfo());
2234 }
2235
2236 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2237                                                   SelectionDAG &DAG) const {
2238   return Op.getOperand(0);
2239 }
2240
2241 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2242                                                 SelectionDAG &DAG) const {
2243   SDValue Chain = Op.getOperand(0);
2244   SDValue Trmp = Op.getOperand(1); // trampoline
2245   SDValue FPtr = Op.getOperand(2); // nested function
2246   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2247   SDLoc dl(Op);
2248
2249   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2250   bool isPPC64 = (PtrVT == MVT::i64);
2251   Type *IntPtrTy =
2252     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2253                                                              *DAG.getContext());
2254
2255   TargetLowering::ArgListTy Args;
2256   TargetLowering::ArgListEntry Entry;
2257
2258   Entry.Ty = IntPtrTy;
2259   Entry.Node = Trmp; Args.push_back(Entry);
2260
2261   // TrampSize == (isPPC64 ? 48 : 40);
2262   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2263                                isPPC64 ? MVT::i64 : MVT::i32);
2264   Args.push_back(Entry);
2265
2266   Entry.Node = FPtr; Args.push_back(Entry);
2267   Entry.Node = Nest; Args.push_back(Entry);
2268
2269   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2270   TargetLowering::CallLoweringInfo CLI(DAG);
2271   CLI.setDebugLoc(dl).setChain(Chain)
2272     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2273                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2274                std::move(Args), 0);
2275
2276   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2277   return CallResult.second;
2278 }
2279
2280 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2281                                         const PPCSubtarget &Subtarget) const {
2282   MachineFunction &MF = DAG.getMachineFunction();
2283   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2284
2285   SDLoc dl(Op);
2286
2287   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2288     // vastart just stores the address of the VarArgsFrameIndex slot into the
2289     // memory location argument.
2290     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2291     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2292     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2293     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2294                         MachinePointerInfo(SV),
2295                         false, false, 0);
2296   }
2297
2298   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2299   // We suppose the given va_list is already allocated.
2300   //
2301   // typedef struct {
2302   //  char gpr;     /* index into the array of 8 GPRs
2303   //                 * stored in the register save area
2304   //                 * gpr=0 corresponds to r3,
2305   //                 * gpr=1 to r4, etc.
2306   //                 */
2307   //  char fpr;     /* index into the array of 8 FPRs
2308   //                 * stored in the register save area
2309   //                 * fpr=0 corresponds to f1,
2310   //                 * fpr=1 to f2, etc.
2311   //                 */
2312   //  char *overflow_arg_area;
2313   //                /* location on stack that holds
2314   //                 * the next overflow argument
2315   //                 */
2316   //  char *reg_save_area;
2317   //               /* where r3:r10 and f1:f8 (if saved)
2318   //                * are stored
2319   //                */
2320   // } va_list[1];
2321
2322
2323   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2324   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2325
2326
2327   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2328
2329   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2330                                             PtrVT);
2331   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2332                                  PtrVT);
2333
2334   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2335   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2336
2337   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2338   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2339
2340   uint64_t FPROffset = 1;
2341   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2342
2343   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2344
2345   // Store first byte : number of int regs
2346   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2347                                          Op.getOperand(1),
2348                                          MachinePointerInfo(SV),
2349                                          MVT::i8, false, false, 0);
2350   uint64_t nextOffset = FPROffset;
2351   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2352                                   ConstFPROffset);
2353
2354   // Store second byte : number of float regs
2355   SDValue secondStore =
2356     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2357                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2358                       false, false, 0);
2359   nextOffset += StackOffset;
2360   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2361
2362   // Store second word : arguments given on stack
2363   SDValue thirdStore =
2364     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2365                  MachinePointerInfo(SV, nextOffset),
2366                  false, false, 0);
2367   nextOffset += FrameOffset;
2368   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2369
2370   // Store third word : arguments given in registers
2371   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2372                       MachinePointerInfo(SV, nextOffset),
2373                       false, false, 0);
2374
2375 }
2376
2377 #include "PPCGenCallingConv.inc"
2378
2379 // Function whose sole purpose is to kill compiler warnings 
2380 // stemming from unused functions included from PPCGenCallingConv.inc.
2381 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2382   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2383 }
2384
2385 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2386                                       CCValAssign::LocInfo &LocInfo,
2387                                       ISD::ArgFlagsTy &ArgFlags,
2388                                       CCState &State) {
2389   return true;
2390 }
2391
2392 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2393                                              MVT &LocVT,
2394                                              CCValAssign::LocInfo &LocInfo,
2395                                              ISD::ArgFlagsTy &ArgFlags,
2396                                              CCState &State) {
2397   static const MCPhysReg ArgRegs[] = {
2398     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2399     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2400   };
2401   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2402
2403   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2404
2405   // Skip one register if the first unallocated register has an even register
2406   // number and there are still argument registers available which have not been
2407   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2408   // need to skip a register if RegNum is odd.
2409   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2410     State.AllocateReg(ArgRegs[RegNum]);
2411   }
2412
2413   // Always return false here, as this function only makes sure that the first
2414   // unallocated register has an odd register number and does not actually
2415   // allocate a register for the current argument.
2416   return false;
2417 }
2418
2419 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2420                                                MVT &LocVT,
2421                                                CCValAssign::LocInfo &LocInfo,
2422                                                ISD::ArgFlagsTy &ArgFlags,
2423                                                CCState &State) {
2424   static const MCPhysReg ArgRegs[] = {
2425     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2426     PPC::F8
2427   };
2428
2429   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2430
2431   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2432
2433   // If there is only one Floating-point register left we need to put both f64
2434   // values of a split ppc_fp128 value on the stack.
2435   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2436     State.AllocateReg(ArgRegs[RegNum]);
2437   }
2438
2439   // Always return false here, as this function only makes sure that the two f64
2440   // values a ppc_fp128 value is split into are both passed in registers or both
2441   // passed on the stack and does not actually allocate a register for the
2442   // current argument.
2443   return false;
2444 }
2445
2446 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2447 /// on Darwin.
2448 static const MCPhysReg *GetFPR() {
2449   static const MCPhysReg FPR[] = {
2450     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2451     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2452   };
2453
2454   return FPR;
2455 }
2456
2457 /// GetQFPR - Get the set of QPX registers that should be allocated for
2458 /// arguments.
2459 static const MCPhysReg *GetQFPR() {
2460   static const MCPhysReg QFPR[] = {
2461     PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2462     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13
2463   };
2464
2465   return QFPR;
2466 }
2467
2468 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2469 /// the stack.
2470 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2471                                        unsigned PtrByteSize) {
2472   unsigned ArgSize = ArgVT.getStoreSize();
2473   if (Flags.isByVal())
2474     ArgSize = Flags.getByValSize();
2475
2476   // Round up to multiples of the pointer size, except for array members,
2477   // which are always packed.
2478   if (!Flags.isInConsecutiveRegs())
2479     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2480
2481   return ArgSize;
2482 }
2483
2484 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2485 /// on the stack.
2486 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2487                                             ISD::ArgFlagsTy Flags,
2488                                             unsigned PtrByteSize) {
2489   unsigned Align = PtrByteSize;
2490
2491   // Altivec parameters are padded to a 16 byte boundary.
2492   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2493       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2494       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2495     Align = 16;
2496   // QPX vector types stored in double-precision are padded to a 32 byte
2497   // boundary.
2498   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2499     Align = 32;
2500
2501   // ByVal parameters are aligned as requested.
2502   if (Flags.isByVal()) {
2503     unsigned BVAlign = Flags.getByValAlign();
2504     if (BVAlign > PtrByteSize) {
2505       if (BVAlign % PtrByteSize != 0)
2506           llvm_unreachable(
2507             "ByVal alignment is not a multiple of the pointer size");
2508
2509       Align = BVAlign;
2510     }
2511   }
2512
2513   // Array members are always packed to their original alignment.
2514   if (Flags.isInConsecutiveRegs()) {
2515     // If the array member was split into multiple registers, the first
2516     // needs to be aligned to the size of the full type.  (Except for
2517     // ppcf128, which is only aligned as its f64 components.)
2518     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2519       Align = OrigVT.getStoreSize();
2520     else
2521       Align = ArgVT.getStoreSize();
2522   }
2523
2524   return Align;
2525 }
2526
2527 /// CalculateStackSlotUsed - Return whether this argument will use its
2528 /// stack slot (instead of being passed in registers).  ArgOffset,
2529 /// AvailableFPRs, and AvailableVRs must hold the current argument
2530 /// position, and will be updated to account for this argument.
2531 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2532                                    ISD::ArgFlagsTy Flags,
2533                                    unsigned PtrByteSize,
2534                                    unsigned LinkageSize,
2535                                    unsigned ParamAreaSize,
2536                                    unsigned &ArgOffset,
2537                                    unsigned &AvailableFPRs,
2538                                    unsigned &AvailableVRs, bool HasQPX) {
2539   bool UseMemory = false;
2540
2541   // Respect alignment of argument on the stack.
2542   unsigned Align =
2543     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2544   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2545   // If there's no space left in the argument save area, we must
2546   // use memory (this check also catches zero-sized arguments).
2547   if (ArgOffset >= LinkageSize + ParamAreaSize)
2548     UseMemory = true;
2549
2550   // Allocate argument on the stack.
2551   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2552   if (Flags.isInConsecutiveRegsLast())
2553     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2554   // If we overran the argument save area, we must use memory
2555   // (this check catches arguments passed partially in memory)
2556   if (ArgOffset > LinkageSize + ParamAreaSize)
2557     UseMemory = true;
2558
2559   // However, if the argument is actually passed in an FPR or a VR,
2560   // we don't use memory after all.
2561   if (!Flags.isByVal()) {
2562     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2563         // QPX registers overlap with the scalar FP registers.
2564         (HasQPX && (ArgVT == MVT::v4f32 ||
2565                     ArgVT == MVT::v4f64 ||
2566                     ArgVT == MVT::v4i1)))
2567       if (AvailableFPRs > 0) {
2568         --AvailableFPRs;
2569         return false;
2570       }
2571     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2572         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2573         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2574       if (AvailableVRs > 0) {
2575         --AvailableVRs;
2576         return false;
2577       }
2578   }
2579
2580   return UseMemory;
2581 }
2582
2583 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2584 /// ensure minimum alignment required for target.
2585 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2586                                      unsigned NumBytes) {
2587   unsigned TargetAlign = Lowering->getStackAlignment();
2588   unsigned AlignMask = TargetAlign - 1;
2589   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2590   return NumBytes;
2591 }
2592
2593 SDValue
2594 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2595                                         CallingConv::ID CallConv, bool isVarArg,
2596                                         const SmallVectorImpl<ISD::InputArg>
2597                                           &Ins,
2598                                         SDLoc dl, SelectionDAG &DAG,
2599                                         SmallVectorImpl<SDValue> &InVals)
2600                                           const {
2601   if (Subtarget.isSVR4ABI()) {
2602     if (Subtarget.isPPC64())
2603       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2604                                          dl, DAG, InVals);
2605     else
2606       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2607                                          dl, DAG, InVals);
2608   } else {
2609     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2610                                        dl, DAG, InVals);
2611   }
2612 }
2613
2614 SDValue
2615 PPCTargetLowering::LowerFormalArguments_32SVR4(
2616                                       SDValue Chain,
2617                                       CallingConv::ID CallConv, bool isVarArg,
2618                                       const SmallVectorImpl<ISD::InputArg>
2619                                         &Ins,
2620                                       SDLoc dl, SelectionDAG &DAG,
2621                                       SmallVectorImpl<SDValue> &InVals) const {
2622
2623   // 32-bit SVR4 ABI Stack Frame Layout:
2624   //              +-----------------------------------+
2625   //        +-->  |            Back chain             |
2626   //        |     +-----------------------------------+
2627   //        |     | Floating-point register save area |
2628   //        |     +-----------------------------------+
2629   //        |     |    General register save area     |
2630   //        |     +-----------------------------------+
2631   //        |     |          CR save word             |
2632   //        |     +-----------------------------------+
2633   //        |     |         VRSAVE save word          |
2634   //        |     +-----------------------------------+
2635   //        |     |         Alignment padding         |
2636   //        |     +-----------------------------------+
2637   //        |     |     Vector register save area     |
2638   //        |     +-----------------------------------+
2639   //        |     |       Local variable space        |
2640   //        |     +-----------------------------------+
2641   //        |     |        Parameter list area        |
2642   //        |     +-----------------------------------+
2643   //        |     |           LR save word            |
2644   //        |     +-----------------------------------+
2645   // SP-->  +---  |            Back chain             |
2646   //              +-----------------------------------+
2647   //
2648   // Specifications:
2649   //   System V Application Binary Interface PowerPC Processor Supplement
2650   //   AltiVec Technology Programming Interface Manual
2651
2652   MachineFunction &MF = DAG.getMachineFunction();
2653   MachineFrameInfo *MFI = MF.getFrameInfo();
2654   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2655
2656   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2657   // Potential tail calls could cause overwriting of argument stack slots.
2658   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2659                        (CallConv == CallingConv::Fast));
2660   unsigned PtrByteSize = 4;
2661
2662   // Assign locations to all of the incoming arguments.
2663   SmallVector<CCValAssign, 16> ArgLocs;
2664   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2665                  *DAG.getContext());
2666
2667   // Reserve space for the linkage area on the stack.
2668   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2669   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2670
2671   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2672
2673   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2674     CCValAssign &VA = ArgLocs[i];
2675
2676     // Arguments stored in registers.
2677     if (VA.isRegLoc()) {
2678       const TargetRegisterClass *RC;
2679       EVT ValVT = VA.getValVT();
2680
2681       switch (ValVT.getSimpleVT().SimpleTy) {
2682         default:
2683           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2684         case MVT::i1:
2685         case MVT::i32:
2686           RC = &PPC::GPRCRegClass;
2687           break;
2688         case MVT::f32:
2689           RC = &PPC::F4RCRegClass;
2690           break;
2691         case MVT::f64:
2692           if (Subtarget.hasVSX())
2693             RC = &PPC::VSFRCRegClass;
2694           else
2695             RC = &PPC::F8RCRegClass;
2696           break;
2697         case MVT::v16i8:
2698         case MVT::v8i16:
2699         case MVT::v4i32:
2700           RC = &PPC::VRRCRegClass;
2701           break;
2702         case MVT::v4f32:
2703           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2704           break;
2705         case MVT::v2f64:
2706         case MVT::v2i64:
2707           RC = &PPC::VSHRCRegClass;
2708           break;
2709         case MVT::v4f64:
2710           RC = &PPC::QFRCRegClass;
2711           break;
2712         case MVT::v4i1:
2713           RC = &PPC::QBRCRegClass;
2714           break;
2715       }
2716
2717       // Transform the arguments stored in physical registers into virtual ones.
2718       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2719       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2720                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2721
2722       if (ValVT == MVT::i1)
2723         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2724
2725       InVals.push_back(ArgValue);
2726     } else {
2727       // Argument stored in memory.
2728       assert(VA.isMemLoc());
2729
2730       unsigned ArgSize = VA.getLocVT().getStoreSize();
2731       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2732                                       isImmutable);
2733
2734       // Create load nodes to retrieve arguments from the stack.
2735       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2736       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2737                                    MachinePointerInfo(),
2738                                    false, false, false, 0));
2739     }
2740   }
2741
2742   // Assign locations to all of the incoming aggregate by value arguments.
2743   // Aggregates passed by value are stored in the local variable space of the
2744   // caller's stack frame, right above the parameter list area.
2745   SmallVector<CCValAssign, 16> ByValArgLocs;
2746   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2747                       ByValArgLocs, *DAG.getContext());
2748
2749   // Reserve stack space for the allocations in CCInfo.
2750   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2751
2752   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2753
2754   // Area that is at least reserved in the caller of this function.
2755   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2756   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2757
2758   // Set the size that is at least reserved in caller of this function.  Tail
2759   // call optimized function's reserved stack space needs to be aligned so that
2760   // taking the difference between two stack areas will result in an aligned
2761   // stack.
2762   MinReservedArea =
2763       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2764   FuncInfo->setMinReservedArea(MinReservedArea);
2765
2766   SmallVector<SDValue, 8> MemOps;
2767
2768   // If the function takes variable number of arguments, make a frame index for
2769   // the start of the first vararg value... for expansion of llvm.va_start.
2770   if (isVarArg) {
2771     static const MCPhysReg GPArgRegs[] = {
2772       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2773       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2774     };
2775     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2776
2777     static const MCPhysReg FPArgRegs[] = {
2778       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2779       PPC::F8
2780     };
2781     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2782     if (DisablePPCFloatInVariadic)
2783       NumFPArgRegs = 0;
2784
2785     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2786     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2787
2788     // Make room for NumGPArgRegs and NumFPArgRegs.
2789     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2790                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2791
2792     FuncInfo->setVarArgsStackOffset(
2793       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2794                              CCInfo.getNextStackOffset(), true));
2795
2796     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2797     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2798
2799     // The fixed integer arguments of a variadic function are stored to the
2800     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2801     // the result of va_next.
2802     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2803       // Get an existing live-in vreg, or add a new one.
2804       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2805       if (!VReg)
2806         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2807
2808       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2809       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2810                                    MachinePointerInfo(), false, false, 0);
2811       MemOps.push_back(Store);
2812       // Increment the address by four for the next argument to store
2813       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2814       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2815     }
2816
2817     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2818     // is set.
2819     // The double arguments are stored to the VarArgsFrameIndex
2820     // on the stack.
2821     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2822       // Get an existing live-in vreg, or add a new one.
2823       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2824       if (!VReg)
2825         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2826
2827       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2828       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2829                                    MachinePointerInfo(), false, false, 0);
2830       MemOps.push_back(Store);
2831       // Increment the address by eight for the next argument to store
2832       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2833                                          PtrVT);
2834       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2835     }
2836   }
2837
2838   if (!MemOps.empty())
2839     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2840
2841   return Chain;
2842 }
2843
2844 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2845 // value to MVT::i64 and then truncate to the correct register size.
2846 SDValue
2847 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2848                                      SelectionDAG &DAG, SDValue ArgVal,
2849                                      SDLoc dl) const {
2850   if (Flags.isSExt())
2851     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2852                          DAG.getValueType(ObjectVT));
2853   else if (Flags.isZExt())
2854     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2855                          DAG.getValueType(ObjectVT));
2856
2857   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2858 }
2859
2860 SDValue
2861 PPCTargetLowering::LowerFormalArguments_64SVR4(
2862                                       SDValue Chain,
2863                                       CallingConv::ID CallConv, bool isVarArg,
2864                                       const SmallVectorImpl<ISD::InputArg>
2865                                         &Ins,
2866                                       SDLoc dl, SelectionDAG &DAG,
2867                                       SmallVectorImpl<SDValue> &InVals) const {
2868   // TODO: add description of PPC stack frame format, or at least some docs.
2869   //
2870   bool isELFv2ABI = Subtarget.isELFv2ABI();
2871   bool isLittleEndian = Subtarget.isLittleEndian();
2872   MachineFunction &MF = DAG.getMachineFunction();
2873   MachineFrameInfo *MFI = MF.getFrameInfo();
2874   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2875
2876   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2877          "fastcc not supported on varargs functions");
2878
2879   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2880   // Potential tail calls could cause overwriting of argument stack slots.
2881   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2882                        (CallConv == CallingConv::Fast));
2883   unsigned PtrByteSize = 8;
2884   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2885
2886   static const MCPhysReg GPR[] = {
2887     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2888     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2889   };
2890
2891   static const MCPhysReg *FPR = GetFPR();
2892
2893   static const MCPhysReg VR[] = {
2894     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2895     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2896   };
2897   static const MCPhysReg VSRH[] = {
2898     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2899     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2900   };
2901
2902   static const MCPhysReg *QFPR = GetQFPR();
2903
2904   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2905   const unsigned Num_FPR_Regs = 13;
2906   const unsigned Num_VR_Regs  = array_lengthof(VR);
2907   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2908
2909   // Do a first pass over the arguments to determine whether the ABI
2910   // guarantees that our caller has allocated the parameter save area
2911   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2912   // in the ELFv2 ABI, it is true if this is a vararg function or if
2913   // any parameter is located in a stack slot.
2914
2915   bool HasParameterArea = !isELFv2ABI || isVarArg;
2916   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2917   unsigned NumBytes = LinkageSize;
2918   unsigned AvailableFPRs = Num_FPR_Regs;
2919   unsigned AvailableVRs = Num_VR_Regs;
2920   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2921     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2922                                PtrByteSize, LinkageSize, ParamAreaSize,
2923                                NumBytes, AvailableFPRs, AvailableVRs,
2924                                Subtarget.hasQPX()))
2925       HasParameterArea = true;
2926
2927   // Add DAG nodes to load the arguments or copy them out of registers.  On
2928   // entry to a function on PPC, the arguments start after the linkage area,
2929   // although the first ones are often in registers.
2930
2931   unsigned ArgOffset = LinkageSize;
2932   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2933   unsigned &QFPR_idx = FPR_idx;
2934   SmallVector<SDValue, 8> MemOps;
2935   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2936   unsigned CurArgIdx = 0;
2937   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2938     SDValue ArgVal;
2939     bool needsLoad = false;
2940     EVT ObjectVT = Ins[ArgNo].VT;
2941     EVT OrigVT = Ins[ArgNo].ArgVT;
2942     unsigned ObjSize = ObjectVT.getStoreSize();
2943     unsigned ArgSize = ObjSize;
2944     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2945     if (Ins[ArgNo].isOrigArg()) {
2946       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2947       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2948     }
2949     // We re-align the argument offset for each argument, except when using the
2950     // fast calling convention, when we need to make sure we do that only when
2951     // we'll actually use a stack slot.
2952     unsigned CurArgOffset, Align;
2953     auto ComputeArgOffset = [&]() {
2954       /* Respect alignment of argument on the stack.  */
2955       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2956       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2957       CurArgOffset = ArgOffset;
2958     };
2959
2960     if (CallConv != CallingConv::Fast) {
2961       ComputeArgOffset();
2962
2963       /* Compute GPR index associated with argument offset.  */
2964       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2965       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2966     }
2967
2968     // FIXME the codegen can be much improved in some cases.
2969     // We do not have to keep everything in memory.
2970     if (Flags.isByVal()) {
2971       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2972
2973       if (CallConv == CallingConv::Fast)
2974         ComputeArgOffset();
2975
2976       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2977       ObjSize = Flags.getByValSize();
2978       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2979       // Empty aggregate parameters do not take up registers.  Examples:
2980       //   struct { } a;
2981       //   union  { } b;
2982       //   int c[0];
2983       // etc.  However, we have to provide a place-holder in InVals, so
2984       // pretend we have an 8-byte item at the current address for that
2985       // purpose.
2986       if (!ObjSize) {
2987         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2988         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2989         InVals.push_back(FIN);
2990         continue;
2991       }
2992
2993       // Create a stack object covering all stack doublewords occupied
2994       // by the argument.  If the argument is (fully or partially) on
2995       // the stack, or if the argument is fully in registers but the
2996       // caller has allocated the parameter save anyway, we can refer
2997       // directly to the caller's stack frame.  Otherwise, create a
2998       // local copy in our own frame.
2999       int FI;
3000       if (HasParameterArea ||
3001           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3002         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3003       else
3004         FI = MFI->CreateStackObject(ArgSize, Align, false);
3005       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3006
3007       // Handle aggregates smaller than 8 bytes.
3008       if (ObjSize < PtrByteSize) {
3009         // The value of the object is its address, which differs from the
3010         // address of the enclosing doubleword on big-endian systems.
3011         SDValue Arg = FIN;
3012         if (!isLittleEndian) {
3013           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3014           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3015         }
3016         InVals.push_back(Arg);
3017
3018         if (GPR_idx != Num_GPR_Regs) {
3019           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3020           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3021           SDValue Store;
3022
3023           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3024             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3025                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3026             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3027                                       MachinePointerInfo(FuncArg),
3028                                       ObjType, false, false, 0);
3029           } else {
3030             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3031             // store the whole register as-is to the parameter save area
3032             // slot.
3033             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3034                                  MachinePointerInfo(FuncArg),
3035                                  false, false, 0);
3036           }
3037
3038           MemOps.push_back(Store);
3039         }
3040         // Whether we copied from a register or not, advance the offset
3041         // into the parameter save area by a full doubleword.
3042         ArgOffset += PtrByteSize;
3043         continue;
3044       }
3045
3046       // The value of the object is its address, which is the address of
3047       // its first stack doubleword.
3048       InVals.push_back(FIN);
3049
3050       // Store whatever pieces of the object are in registers to memory.
3051       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3052         if (GPR_idx == Num_GPR_Regs)
3053           break;
3054
3055         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3056         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3057         SDValue Addr = FIN;
3058         if (j) {
3059           SDValue Off = DAG.getConstant(j, PtrVT);
3060           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3061         }
3062         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3063                                      MachinePointerInfo(FuncArg, j),
3064                                      false, false, 0);
3065         MemOps.push_back(Store);
3066         ++GPR_idx;
3067       }
3068       ArgOffset += ArgSize;
3069       continue;
3070     }
3071
3072     switch (ObjectVT.getSimpleVT().SimpleTy) {
3073     default: llvm_unreachable("Unhandled argument type!");
3074     case MVT::i1:
3075     case MVT::i32:
3076     case MVT::i64:
3077       // These can be scalar arguments or elements of an integer array type
3078       // passed directly.  Clang may use those instead of "byval" aggregate
3079       // types to avoid forcing arguments to memory unnecessarily.
3080       if (GPR_idx != Num_GPR_Regs) {
3081         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3082         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3083
3084         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3085           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3086           // value to MVT::i64 and then truncate to the correct register size.
3087           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3088       } else {
3089         if (CallConv == CallingConv::Fast)
3090           ComputeArgOffset();
3091
3092         needsLoad = true;
3093         ArgSize = PtrByteSize;
3094       }
3095       if (CallConv != CallingConv::Fast || needsLoad)
3096         ArgOffset += 8;
3097       break;
3098
3099     case MVT::f32:
3100     case MVT::f64:
3101       // These can be scalar arguments or elements of a float array type
3102       // passed directly.  The latter are used to implement ELFv2 homogenous
3103       // float aggregates.
3104       if (FPR_idx != Num_FPR_Regs) {
3105         unsigned VReg;
3106
3107         if (ObjectVT == MVT::f32)
3108           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3109         else
3110           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3111                                                 ? &PPC::VSFRCRegClass
3112                                                 : &PPC::F8RCRegClass);
3113
3114         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3115         ++FPR_idx;
3116       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3117         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3118         // once we support fp <-> gpr moves.
3119
3120         // This can only ever happen in the presence of f32 array types,
3121         // since otherwise we never run out of FPRs before running out
3122         // of GPRs.
3123         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3124         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3125
3126         if (ObjectVT == MVT::f32) {
3127           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3128             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3129                                  DAG.getConstant(32, MVT::i32));
3130           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3131         }
3132
3133         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3134       } else {
3135         if (CallConv == CallingConv::Fast)
3136           ComputeArgOffset();
3137
3138         needsLoad = true;
3139       }
3140
3141       // When passing an array of floats, the array occupies consecutive
3142       // space in the argument area; only round up to the next doubleword
3143       // at the end of the array.  Otherwise, each float takes 8 bytes.
3144       if (CallConv != CallingConv::Fast || needsLoad) {
3145         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3146         ArgOffset += ArgSize;
3147         if (Flags.isInConsecutiveRegsLast())
3148           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3149       }
3150       break;
3151     case MVT::v4f32:
3152     case MVT::v4i32:
3153     case MVT::v8i16:
3154     case MVT::v16i8:
3155     case MVT::v2f64:
3156     case MVT::v2i64:
3157       if (!Subtarget.hasQPX()) {
3158       // These can be scalar arguments or elements of a vector array type
3159       // passed directly.  The latter are used to implement ELFv2 homogenous
3160       // vector aggregates.
3161       if (VR_idx != Num_VR_Regs) {
3162         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3163                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3164                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3165         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3166         ++VR_idx;
3167       } else {
3168         if (CallConv == CallingConv::Fast)
3169           ComputeArgOffset();
3170
3171         needsLoad = true;
3172       }
3173       if (CallConv != CallingConv::Fast || needsLoad)
3174         ArgOffset += 16;
3175       break;
3176       } // not QPX
3177
3178       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3179              "Invalid QPX parameter type");
3180       /* fall through */
3181
3182     case MVT::v4f64:
3183     case MVT::v4i1:
3184       // QPX vectors are treated like their scalar floating-point subregisters
3185       // (except that they're larger).
3186       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3187       if (QFPR_idx != Num_QFPR_Regs) {
3188         const TargetRegisterClass *RC;
3189         switch (ObjectVT.getSimpleVT().SimpleTy) {
3190         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3191         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3192         default:         RC = &PPC::QBRCRegClass; break;
3193         }
3194
3195         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3196         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3197         ++QFPR_idx;
3198       } else {
3199         if (CallConv == CallingConv::Fast)
3200           ComputeArgOffset();
3201         needsLoad = true;
3202       }
3203       if (CallConv != CallingConv::Fast || needsLoad)
3204         ArgOffset += Sz;
3205       break;
3206     }
3207
3208     // We need to load the argument to a virtual register if we determined
3209     // above that we ran out of physical registers of the appropriate type.
3210     if (needsLoad) {
3211       if (ObjSize < ArgSize && !isLittleEndian)
3212         CurArgOffset += ArgSize - ObjSize;
3213       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3214       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3215       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3216                            false, false, false, 0);
3217     }
3218
3219     InVals.push_back(ArgVal);
3220   }
3221
3222   // Area that is at least reserved in the caller of this function.
3223   unsigned MinReservedArea;
3224   if (HasParameterArea)
3225     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3226   else
3227     MinReservedArea = LinkageSize;
3228
3229   // Set the size that is at least reserved in caller of this function.  Tail
3230   // call optimized functions' reserved stack space needs to be aligned so that
3231   // taking the difference between two stack areas will result in an aligned
3232   // stack.
3233   MinReservedArea =
3234       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3235   FuncInfo->setMinReservedArea(MinReservedArea);
3236
3237   // If the function takes variable number of arguments, make a frame index for
3238   // the start of the first vararg value... for expansion of llvm.va_start.
3239   if (isVarArg) {
3240     int Depth = ArgOffset;
3241
3242     FuncInfo->setVarArgsFrameIndex(
3243       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3244     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3245
3246     // If this function is vararg, store any remaining integer argument regs
3247     // to their spots on the stack so that they may be loaded by deferencing the
3248     // result of va_next.
3249     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3250          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3251       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3252       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3253       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3254                                    MachinePointerInfo(), false, false, 0);
3255       MemOps.push_back(Store);
3256       // Increment the address by four for the next argument to store
3257       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3258       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3259     }
3260   }
3261
3262   if (!MemOps.empty())
3263     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3264
3265   return Chain;
3266 }
3267
3268 SDValue
3269 PPCTargetLowering::LowerFormalArguments_Darwin(
3270                                       SDValue Chain,
3271                                       CallingConv::ID CallConv, bool isVarArg,
3272                                       const SmallVectorImpl<ISD::InputArg>
3273                                         &Ins,
3274                                       SDLoc dl, SelectionDAG &DAG,
3275                                       SmallVectorImpl<SDValue> &InVals) const {
3276   // TODO: add description of PPC stack frame format, or at least some docs.
3277   //
3278   MachineFunction &MF = DAG.getMachineFunction();
3279   MachineFrameInfo *MFI = MF.getFrameInfo();
3280   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3281
3282   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3283   bool isPPC64 = PtrVT == MVT::i64;
3284   // Potential tail calls could cause overwriting of argument stack slots.
3285   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3286                        (CallConv == CallingConv::Fast));
3287   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3288   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3289   unsigned ArgOffset = LinkageSize;
3290   // Area that is at least reserved in caller of this function.
3291   unsigned MinReservedArea = ArgOffset;
3292
3293   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3294     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3295     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3296   };
3297   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3298     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3299     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3300   };
3301
3302   static const MCPhysReg *FPR = GetFPR();
3303
3304   static const MCPhysReg VR[] = {
3305     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3306     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3307   };
3308
3309   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3310   const unsigned Num_FPR_Regs = 13;
3311   const unsigned Num_VR_Regs  = array_lengthof( VR);
3312
3313   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3314
3315   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3316
3317   // In 32-bit non-varargs functions, the stack space for vectors is after the
3318   // stack space for non-vectors.  We do not use this space unless we have
3319   // too many vectors to fit in registers, something that only occurs in
3320   // constructed examples:), but we have to walk the arglist to figure
3321   // that out...for the pathological case, compute VecArgOffset as the
3322   // start of the vector parameter area.  Computing VecArgOffset is the
3323   // entire point of the following loop.
3324   unsigned VecArgOffset = ArgOffset;
3325   if (!isVarArg && !isPPC64) {
3326     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3327          ++ArgNo) {
3328       EVT ObjectVT = Ins[ArgNo].VT;
3329       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3330
3331       if (Flags.isByVal()) {
3332         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3333         unsigned ObjSize = Flags.getByValSize();
3334         unsigned ArgSize =
3335                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3336         VecArgOffset += ArgSize;
3337         continue;
3338       }
3339
3340       switch(ObjectVT.getSimpleVT().SimpleTy) {
3341       default: llvm_unreachable("Unhandled argument type!");
3342       case MVT::i1:
3343       case MVT::i32:
3344       case MVT::f32:
3345         VecArgOffset += 4;
3346         break;
3347       case MVT::i64:  // PPC64
3348       case MVT::f64:
3349         // FIXME: We are guaranteed to be !isPPC64 at this point.
3350         // Does MVT::i64 apply?
3351         VecArgOffset += 8;
3352         break;
3353       case MVT::v4f32:
3354       case MVT::v4i32:
3355       case MVT::v8i16:
3356       case MVT::v16i8:
3357         // Nothing to do, we're only looking at Nonvector args here.
3358         break;
3359       }
3360     }
3361   }
3362   // We've found where the vector parameter area in memory is.  Skip the
3363   // first 12 parameters; these don't use that memory.
3364   VecArgOffset = ((VecArgOffset+15)/16)*16;
3365   VecArgOffset += 12*16;
3366
3367   // Add DAG nodes to load the arguments or copy them out of registers.  On
3368   // entry to a function on PPC, the arguments start after the linkage area,
3369   // although the first ones are often in registers.
3370
3371   SmallVector<SDValue, 8> MemOps;
3372   unsigned nAltivecParamsAtEnd = 0;
3373   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3374   unsigned CurArgIdx = 0;
3375   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3376     SDValue ArgVal;
3377     bool needsLoad = false;
3378     EVT ObjectVT = Ins[ArgNo].VT;
3379     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3380     unsigned ArgSize = ObjSize;
3381     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3382     if (Ins[ArgNo].isOrigArg()) {
3383       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3384       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3385     }
3386     unsigned CurArgOffset = ArgOffset;
3387
3388     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3389     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3390         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3391       if (isVarArg || isPPC64) {
3392         MinReservedArea = ((MinReservedArea+15)/16)*16;
3393         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3394                                                   Flags,
3395                                                   PtrByteSize);
3396       } else  nAltivecParamsAtEnd++;
3397     } else
3398       // Calculate min reserved area.
3399       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3400                                                 Flags,
3401                                                 PtrByteSize);
3402
3403     // FIXME the codegen can be much improved in some cases.
3404     // We do not have to keep everything in memory.
3405     if (Flags.isByVal()) {
3406       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3407
3408       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3409       ObjSize = Flags.getByValSize();
3410       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3411       // Objects of size 1 and 2 are right justified, everything else is
3412       // left justified.  This means the memory address is adjusted forwards.
3413       if (ObjSize==1 || ObjSize==2) {
3414         CurArgOffset = CurArgOffset + (4 - ObjSize);
3415       }
3416       // The value of the object is its address.
3417       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3418       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3419       InVals.push_back(FIN);
3420       if (ObjSize==1 || ObjSize==2) {
3421         if (GPR_idx != Num_GPR_Regs) {
3422           unsigned VReg;
3423           if (isPPC64)
3424             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3425           else
3426             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3427           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3428           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3429           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3430                                             MachinePointerInfo(FuncArg),
3431                                             ObjType, false, false, 0);
3432           MemOps.push_back(Store);
3433           ++GPR_idx;
3434         }
3435
3436         ArgOffset += PtrByteSize;
3437
3438         continue;
3439       }
3440       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3441         // Store whatever pieces of the object are in registers
3442         // to memory.  ArgOffset will be the address of the beginning
3443         // of the object.
3444         if (GPR_idx != Num_GPR_Regs) {
3445           unsigned VReg;
3446           if (isPPC64)
3447             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3448           else
3449             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3450           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3451           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3452           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3453           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3454                                        MachinePointerInfo(FuncArg, j),
3455                                        false, false, 0);
3456           MemOps.push_back(Store);
3457           ++GPR_idx;
3458           ArgOffset += PtrByteSize;
3459         } else {
3460           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3461           break;
3462         }
3463       }
3464       continue;
3465     }
3466
3467     switch (ObjectVT.getSimpleVT().SimpleTy) {
3468     default: llvm_unreachable("Unhandled argument type!");
3469     case MVT::i1:
3470     case MVT::i32:
3471       if (!isPPC64) {
3472         if (GPR_idx != Num_GPR_Regs) {
3473           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3474           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3475
3476           if (ObjectVT == MVT::i1)
3477             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3478
3479           ++GPR_idx;
3480         } else {
3481           needsLoad = true;
3482           ArgSize = PtrByteSize;
3483         }
3484         // All int arguments reserve stack space in the Darwin ABI.
3485         ArgOffset += PtrByteSize;
3486         break;
3487       }
3488       // FALLTHROUGH
3489     case MVT::i64:  // PPC64
3490       if (GPR_idx != Num_GPR_Regs) {
3491         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3492         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3493
3494         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3495           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3496           // value to MVT::i64 and then truncate to the correct register size.
3497           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3498
3499         ++GPR_idx;
3500       } else {
3501         needsLoad = true;
3502         ArgSize = PtrByteSize;
3503       }
3504       // All int arguments reserve stack space in the Darwin ABI.
3505       ArgOffset += 8;
3506       break;
3507
3508     case MVT::f32:
3509     case MVT::f64:
3510       // Every 4 bytes of argument space consumes one of the GPRs available for
3511       // argument passing.
3512       if (GPR_idx != Num_GPR_Regs) {
3513         ++GPR_idx;
3514         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3515           ++GPR_idx;
3516       }
3517       if (FPR_idx != Num_FPR_Regs) {
3518         unsigned VReg;
3519
3520         if (ObjectVT == MVT::f32)
3521           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3522         else
3523           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3524
3525         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3526         ++FPR_idx;
3527       } else {
3528         needsLoad = true;
3529       }
3530
3531       // All FP arguments reserve stack space in the Darwin ABI.
3532       ArgOffset += isPPC64 ? 8 : ObjSize;
3533       break;
3534     case MVT::v4f32:
3535     case MVT::v4i32:
3536     case MVT::v8i16:
3537     case MVT::v16i8:
3538       // Note that vector arguments in registers don't reserve stack space,
3539       // except in varargs functions.
3540       if (VR_idx != Num_VR_Regs) {
3541         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3542         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3543         if (isVarArg) {
3544           while ((ArgOffset % 16) != 0) {
3545             ArgOffset += PtrByteSize;
3546             if (GPR_idx != Num_GPR_Regs)
3547               GPR_idx++;
3548           }
3549           ArgOffset += 16;
3550           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3551         }
3552         ++VR_idx;
3553       } else {
3554         if (!isVarArg && !isPPC64) {
3555           // Vectors go after all the nonvectors.
3556           CurArgOffset = VecArgOffset;
3557           VecArgOffset += 16;
3558         } else {
3559           // Vectors are aligned.
3560           ArgOffset = ((ArgOffset+15)/16)*16;
3561           CurArgOffset = ArgOffset;
3562           ArgOffset += 16;
3563         }
3564         needsLoad = true;
3565       }
3566       break;
3567     }
3568
3569     // We need to load the argument to a virtual register if we determined above
3570     // that we ran out of physical registers of the appropriate type.
3571     if (needsLoad) {
3572       int FI = MFI->CreateFixedObject(ObjSize,
3573                                       CurArgOffset + (ArgSize - ObjSize),
3574                                       isImmutable);
3575       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3576       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3577                            false, false, false, 0);
3578     }
3579
3580     InVals.push_back(ArgVal);
3581   }
3582
3583   // Allow for Altivec parameters at the end, if needed.
3584   if (nAltivecParamsAtEnd) {
3585     MinReservedArea = ((MinReservedArea+15)/16)*16;
3586     MinReservedArea += 16*nAltivecParamsAtEnd;
3587   }
3588
3589   // Area that is at least reserved in the caller of this function.
3590   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3591
3592   // Set the size that is at least reserved in caller of this function.  Tail
3593   // call optimized functions' reserved stack space needs to be aligned so that
3594   // taking the difference between two stack areas will result in an aligned
3595   // stack.
3596   MinReservedArea =
3597       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3598   FuncInfo->setMinReservedArea(MinReservedArea);
3599
3600   // If the function takes variable number of arguments, make a frame index for
3601   // the start of the first vararg value... for expansion of llvm.va_start.
3602   if (isVarArg) {
3603     int Depth = ArgOffset;
3604
3605     FuncInfo->setVarArgsFrameIndex(
3606       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3607                              Depth, true));
3608     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3609
3610     // If this function is vararg, store any remaining integer argument regs
3611     // to their spots on the stack so that they may be loaded by deferencing the
3612     // result of va_next.
3613     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3614       unsigned VReg;
3615
3616       if (isPPC64)
3617         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3618       else
3619         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3620
3621       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3622       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3623                                    MachinePointerInfo(), false, false, 0);
3624       MemOps.push_back(Store);
3625       // Increment the address by four for the next argument to store
3626       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3627       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3628     }
3629   }
3630
3631   if (!MemOps.empty())
3632     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3633
3634   return Chain;
3635 }
3636
3637 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3638 /// adjusted to accommodate the arguments for the tailcall.
3639 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3640                                    unsigned ParamSize) {
3641
3642   if (!isTailCall) return 0;
3643
3644   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3645   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3646   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3647   // Remember only if the new adjustement is bigger.
3648   if (SPDiff < FI->getTailCallSPDelta())
3649     FI->setTailCallSPDelta(SPDiff);
3650
3651   return SPDiff;
3652 }
3653
3654 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3655 /// for tail call optimization. Targets which want to do tail call
3656 /// optimization should implement this function.
3657 bool
3658 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3659                                                      CallingConv::ID CalleeCC,
3660                                                      bool isVarArg,
3661                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3662                                                      SelectionDAG& DAG) const {
3663   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3664     return false;
3665
3666   // Variable argument functions are not supported.
3667   if (isVarArg)
3668     return false;
3669
3670   MachineFunction &MF = DAG.getMachineFunction();
3671   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3672   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3673     // Functions containing by val parameters are not supported.
3674     for (unsigned i = 0; i != Ins.size(); i++) {
3675        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3676        if (Flags.isByVal()) return false;
3677     }
3678
3679     // Non-PIC/GOT tail calls are supported.
3680     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3681       return true;
3682
3683     // At the moment we can only do local tail calls (in same module, hidden
3684     // or protected) if we are generating PIC.
3685     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3686       return G->getGlobal()->hasHiddenVisibility()
3687           || G->getGlobal()->hasProtectedVisibility();
3688   }
3689
3690   return false;
3691 }
3692
3693 /// isCallCompatibleAddress - Return the immediate to use if the specified
3694 /// 32-bit value is representable in the immediate field of a BxA instruction.
3695 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3696   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3697   if (!C) return nullptr;
3698
3699   int Addr = C->getZExtValue();
3700   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3701       SignExtend32<26>(Addr) != Addr)
3702     return nullptr;  // Top 6 bits have to be sext of immediate.
3703
3704   return DAG.getConstant((int)C->getZExtValue() >> 2,
3705                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3706 }
3707
3708 namespace {
3709
3710 struct TailCallArgumentInfo {
3711   SDValue Arg;
3712   SDValue FrameIdxOp;
3713   int       FrameIdx;
3714
3715   TailCallArgumentInfo() : FrameIdx(0) {}
3716 };
3717
3718 }
3719
3720 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3721 static void
3722 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3723                                            SDValue Chain,
3724                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3725                    SmallVectorImpl<SDValue> &MemOpChains,
3726                    SDLoc dl) {
3727   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3728     SDValue Arg = TailCallArgs[i].Arg;
3729     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3730     int FI = TailCallArgs[i].FrameIdx;
3731     // Store relative to framepointer.
3732     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3733                                        MachinePointerInfo::getFixedStack(FI),
3734                                        false, false, 0));
3735   }
3736 }
3737
3738 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3739 /// the appropriate stack slot for the tail call optimized function call.
3740 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3741                                                MachineFunction &MF,
3742                                                SDValue Chain,
3743                                                SDValue OldRetAddr,
3744                                                SDValue OldFP,
3745                                                int SPDiff,
3746                                                bool isPPC64,
3747                                                bool isDarwinABI,
3748                                                SDLoc dl) {
3749   if (SPDiff) {
3750     // Calculate the new stack slot for the return address.
3751     int SlotSize = isPPC64 ? 8 : 4;
3752     const PPCFrameLowering *FL =
3753         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3754     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3755     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3756                                                           NewRetAddrLoc, true);
3757     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3758     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3759     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3760                          MachinePointerInfo::getFixedStack(NewRetAddr),
3761                          false, false, 0);
3762
3763     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3764     // slot as the FP is never overwritten.
3765     if (isDarwinABI) {
3766       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3767       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3768                                                           true);
3769       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3770       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3771                            MachinePointerInfo::getFixedStack(NewFPIdx),
3772                            false, false, 0);
3773     }
3774   }
3775   return Chain;
3776 }
3777
3778 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3779 /// the position of the argument.
3780 static void
3781 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3782                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3783                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3784   int Offset = ArgOffset + SPDiff;
3785   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3786   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3787   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3788   SDValue FIN = DAG.getFrameIndex(FI, VT);
3789   TailCallArgumentInfo Info;
3790   Info.Arg = Arg;
3791   Info.FrameIdxOp = FIN;
3792   Info.FrameIdx = FI;
3793   TailCallArguments.push_back(Info);
3794 }
3795
3796 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3797 /// stack slot. Returns the chain as result and the loaded frame pointers in
3798 /// LROpOut/FPOpout. Used when tail calling.
3799 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3800                                                         int SPDiff,
3801                                                         SDValue Chain,
3802                                                         SDValue &LROpOut,
3803                                                         SDValue &FPOpOut,
3804                                                         bool isDarwinABI,
3805                                                         SDLoc dl) const {
3806   if (SPDiff) {
3807     // Load the LR and FP stack slot for later adjusting.
3808     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3809     LROpOut = getReturnAddrFrameIndex(DAG);
3810     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3811                           false, false, false, 0);
3812     Chain = SDValue(LROpOut.getNode(), 1);
3813
3814     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3815     // slot as the FP is never overwritten.
3816     if (isDarwinABI) {
3817       FPOpOut = getFramePointerFrameIndex(DAG);
3818       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3819                             false, false, false, 0);
3820       Chain = SDValue(FPOpOut.getNode(), 1);
3821     }
3822   }
3823   return Chain;
3824 }
3825
3826 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3827 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3828 /// specified by the specific parameter attribute. The copy will be passed as
3829 /// a byval function parameter.
3830 /// Sometimes what we are copying is the end of a larger object, the part that
3831 /// does not fit in registers.
3832 static SDValue
3833 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3834                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3835                           SDLoc dl) {
3836   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3837   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3838                        false, false, MachinePointerInfo(),
3839                        MachinePointerInfo());
3840 }
3841
3842 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3843 /// tail calls.
3844 static void
3845 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3846                  SDValue Arg, SDValue PtrOff, int SPDiff,
3847                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3848                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3849                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3850                  SDLoc dl) {
3851   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3852   if (!isTailCall) {
3853     if (isVector) {
3854       SDValue StackPtr;
3855       if (isPPC64)
3856         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3857       else
3858         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3859       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3860                            DAG.getConstant(ArgOffset, PtrVT));
3861     }
3862     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3863                                        MachinePointerInfo(), false, false, 0));
3864   // Calculate and remember argument location.
3865   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3866                                   TailCallArguments);
3867 }
3868
3869 static
3870 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3871                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3872                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3873                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3874   MachineFunction &MF = DAG.getMachineFunction();
3875
3876   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3877   // might overwrite each other in case of tail call optimization.
3878   SmallVector<SDValue, 8> MemOpChains2;
3879   // Do not flag preceding copytoreg stuff together with the following stuff.
3880   InFlag = SDValue();
3881   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3882                                     MemOpChains2, dl);
3883   if (!MemOpChains2.empty())
3884     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3885
3886   // Store the return address to the appropriate stack slot.
3887   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3888                                         isPPC64, isDarwinABI, dl);
3889
3890   // Emit callseq_end just before tailcall node.
3891   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3892                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3893   InFlag = Chain.getValue(1);
3894 }
3895
3896 // Is this global address that of a function that can be called by name? (as
3897 // opposed to something that must hold a descriptor for an indirect call).
3898 static bool isFunctionGlobalAddress(SDValue Callee) {
3899   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3900     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3901         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3902       return false;
3903
3904     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3905   }
3906
3907   return false;
3908 }
3909
3910 static
3911 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3912                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3913                      bool isTailCall, bool IsPatchPoint,
3914                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3915                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3916                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3917
3918   bool isPPC64 = Subtarget.isPPC64();
3919   bool isSVR4ABI = Subtarget.isSVR4ABI();
3920   bool isELFv2ABI = Subtarget.isELFv2ABI();
3921
3922   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3923   NodeTys.push_back(MVT::Other);   // Returns a chain
3924   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3925
3926   unsigned CallOpc = PPCISD::CALL;
3927
3928   bool needIndirectCall = true;
3929   if (!isSVR4ABI || !isPPC64)
3930     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3931       // If this is an absolute destination address, use the munged value.
3932       Callee = SDValue(Dest, 0);
3933       needIndirectCall = false;
3934     }
3935
3936   if (isFunctionGlobalAddress(Callee)) {
3937     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3938     // A call to a TLS address is actually an indirect call to a
3939     // thread-specific pointer.
3940     unsigned OpFlags = 0;
3941     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3942          (Subtarget.getTargetTriple().isMacOSX() &&
3943           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3944          (G->getGlobal()->isDeclaration() ||
3945           G->getGlobal()->isWeakForLinker())) ||
3946         (Subtarget.isTargetELF() && !isPPC64 &&
3947          !G->getGlobal()->hasLocalLinkage() &&
3948          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3949       // PC-relative references to external symbols should go through $stub,
3950       // unless we're building with the leopard linker or later, which
3951       // automatically synthesizes these stubs.
3952       OpFlags = PPCII::MO_PLT_OR_STUB;
3953     }
3954
3955     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3956     // every direct call is) turn it into a TargetGlobalAddress /
3957     // TargetExternalSymbol node so that legalize doesn't hack it.
3958     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3959                                         Callee.getValueType(), 0, OpFlags);
3960     needIndirectCall = false;
3961   }
3962
3963   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3964     unsigned char OpFlags = 0;
3965
3966     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3967          (Subtarget.getTargetTriple().isMacOSX() &&
3968           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3969         (Subtarget.isTargetELF() && !isPPC64 &&
3970          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3971       // PC-relative references to external symbols should go through $stub,
3972       // unless we're building with the leopard linker or later, which
3973       // automatically synthesizes these stubs.
3974       OpFlags = PPCII::MO_PLT_OR_STUB;
3975     }
3976
3977     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3978                                          OpFlags);
3979     needIndirectCall = false;
3980   }
3981
3982   if (IsPatchPoint) {
3983     // We'll form an invalid direct call when lowering a patchpoint; the full
3984     // sequence for an indirect call is complicated, and many of the
3985     // instructions introduced might have side effects (and, thus, can't be
3986     // removed later). The call itself will be removed as soon as the
3987     // argument/return lowering is complete, so the fact that it has the wrong
3988     // kind of operands should not really matter.
3989     needIndirectCall = false;
3990   }
3991
3992   if (needIndirectCall) {
3993     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3994     // to do the call, we can't use PPCISD::CALL.
3995     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3996
3997     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3998       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3999       // entry point, but to the function descriptor (the function entry point
4000       // address is part of the function descriptor though).
4001       // The function descriptor is a three doubleword structure with the
4002       // following fields: function entry point, TOC base address and
4003       // environment pointer.
4004       // Thus for a call through a function pointer, the following actions need
4005       // to be performed:
4006       //   1. Save the TOC of the caller in the TOC save area of its stack
4007       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4008       //   2. Load the address of the function entry point from the function
4009       //      descriptor.
4010       //   3. Load the TOC of the callee from the function descriptor into r2.
4011       //   4. Load the environment pointer from the function descriptor into
4012       //      r11.
4013       //   5. Branch to the function entry point address.
4014       //   6. On return of the callee, the TOC of the caller needs to be
4015       //      restored (this is done in FinishCall()).
4016       //
4017       // The loads are scheduled at the beginning of the call sequence, and the
4018       // register copies are flagged together to ensure that no other
4019       // operations can be scheduled in between. E.g. without flagging the
4020       // copies together, a TOC access in the caller could be scheduled between
4021       // the assignment of the callee TOC and the branch to the callee, which
4022       // results in the TOC access going through the TOC of the callee instead
4023       // of going through the TOC of the caller, which leads to incorrect code.
4024
4025       // Load the address of the function entry point from the function
4026       // descriptor.
4027       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4028       if (LDChain.getValueType() == MVT::Glue)
4029         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4030
4031       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4032
4033       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4034       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4035                                         false, false, LoadsInv, 8);
4036
4037       // Load environment pointer into r11.
4038       SDValue PtrOff = DAG.getIntPtrConstant(16);
4039       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4040       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4041                                        MPI.getWithOffset(16), false, false,
4042                                        LoadsInv, 8);
4043
4044       SDValue TOCOff = DAG.getIntPtrConstant(8);
4045       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4046       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4047                                    MPI.getWithOffset(8), false, false,
4048                                    LoadsInv, 8);
4049
4050       setUsesTOCBasePtr(DAG);
4051       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4052                                         InFlag);
4053       Chain = TOCVal.getValue(0);
4054       InFlag = TOCVal.getValue(1);
4055
4056       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4057                                         InFlag);
4058
4059       Chain = EnvVal.getValue(0);
4060       InFlag = EnvVal.getValue(1);
4061
4062       MTCTROps[0] = Chain;
4063       MTCTROps[1] = LoadFuncPtr;
4064       MTCTROps[2] = InFlag;
4065     }
4066
4067     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4068                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4069     InFlag = Chain.getValue(1);
4070
4071     NodeTys.clear();
4072     NodeTys.push_back(MVT::Other);
4073     NodeTys.push_back(MVT::Glue);
4074     Ops.push_back(Chain);
4075     CallOpc = PPCISD::BCTRL;
4076     Callee.setNode(nullptr);
4077     // Add use of X11 (holding environment pointer)
4078     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4079       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4080     // Add CTR register as callee so a bctr can be emitted later.
4081     if (isTailCall)
4082       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4083   }
4084
4085   // If this is a direct call, pass the chain and the callee.
4086   if (Callee.getNode()) {
4087     Ops.push_back(Chain);
4088     Ops.push_back(Callee);
4089   }
4090   // If this is a tail call add stack pointer delta.
4091   if (isTailCall)
4092     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4093
4094   // Add argument registers to the end of the list so that they are known live
4095   // into the call.
4096   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4097     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4098                                   RegsToPass[i].second.getValueType()));
4099
4100   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4101   // into the call.
4102   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4103     setUsesTOCBasePtr(DAG);
4104     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4105   }
4106
4107   return CallOpc;
4108 }
4109
4110 static
4111 bool isLocalCall(const SDValue &Callee)
4112 {
4113   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4114     return !G->getGlobal()->isDeclaration() &&
4115            !G->getGlobal()->isWeakForLinker();
4116   return false;
4117 }
4118
4119 SDValue
4120 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4121                                    CallingConv::ID CallConv, bool isVarArg,
4122                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4123                                    SDLoc dl, SelectionDAG &DAG,
4124                                    SmallVectorImpl<SDValue> &InVals) const {
4125
4126   SmallVector<CCValAssign, 16> RVLocs;
4127   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4128                     *DAG.getContext());
4129   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4130
4131   // Copy all of the result registers out of their specified physreg.
4132   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4133     CCValAssign &VA = RVLocs[i];
4134     assert(VA.isRegLoc() && "Can only return in registers!");
4135
4136     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4137                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4138     Chain = Val.getValue(1);
4139     InFlag = Val.getValue(2);
4140
4141     switch (VA.getLocInfo()) {
4142     default: llvm_unreachable("Unknown loc info!");
4143     case CCValAssign::Full: break;
4144     case CCValAssign::AExt:
4145       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4146       break;
4147     case CCValAssign::ZExt:
4148       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4149                         DAG.getValueType(VA.getValVT()));
4150       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4151       break;
4152     case CCValAssign::SExt:
4153       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4154                         DAG.getValueType(VA.getValVT()));
4155       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4156       break;
4157     }
4158
4159     InVals.push_back(Val);
4160   }
4161
4162   return Chain;
4163 }
4164
4165 SDValue
4166 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4167                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4168                               SelectionDAG &DAG,
4169                               SmallVector<std::pair<unsigned, SDValue>, 8>
4170                                 &RegsToPass,
4171                               SDValue InFlag, SDValue Chain,
4172                               SDValue CallSeqStart, SDValue &Callee,
4173                               int SPDiff, unsigned NumBytes,
4174                               const SmallVectorImpl<ISD::InputArg> &Ins,
4175                               SmallVectorImpl<SDValue> &InVals,
4176                               ImmutableCallSite *CS) const {
4177
4178   std::vector<EVT> NodeTys;
4179   SmallVector<SDValue, 8> Ops;
4180   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4181                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4182                                  Ops, NodeTys, CS, Subtarget);
4183
4184   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4185   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4186     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4187
4188   // When performing tail call optimization the callee pops its arguments off
4189   // the stack. Account for this here so these bytes can be pushed back on in
4190   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4191   int BytesCalleePops =
4192     (CallConv == CallingConv::Fast &&
4193      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4194
4195   // Add a register mask operand representing the call-preserved registers.
4196   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4197   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
4198   assert(Mask && "Missing call preserved mask for calling convention");
4199   Ops.push_back(DAG.getRegisterMask(Mask));
4200
4201   if (InFlag.getNode())
4202     Ops.push_back(InFlag);
4203
4204   // Emit tail call.
4205   if (isTailCall) {
4206     assert(((Callee.getOpcode() == ISD::Register &&
4207              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4208             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4209             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4210             isa<ConstantSDNode>(Callee)) &&
4211     "Expecting an global address, external symbol, absolute value or register");
4212
4213     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4214   }
4215
4216   // Add a NOP immediately after the branch instruction when using the 64-bit
4217   // SVR4 ABI. At link time, if caller and callee are in a different module and
4218   // thus have a different TOC, the call will be replaced with a call to a stub
4219   // function which saves the current TOC, loads the TOC of the callee and
4220   // branches to the callee. The NOP will be replaced with a load instruction
4221   // which restores the TOC of the caller from the TOC save slot of the current
4222   // stack frame. If caller and callee belong to the same module (and have the
4223   // same TOC), the NOP will remain unchanged.
4224
4225   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4226       !IsPatchPoint) {
4227     if (CallOpc == PPCISD::BCTRL) {
4228       // This is a call through a function pointer.
4229       // Restore the caller TOC from the save area into R2.
4230       // See PrepareCall() for more information about calls through function
4231       // pointers in the 64-bit SVR4 ABI.
4232       // We are using a target-specific load with r2 hard coded, because the
4233       // result of a target-independent load would never go directly into r2,
4234       // since r2 is a reserved register (which prevents the register allocator
4235       // from allocating it), resulting in an additional register being
4236       // allocated and an unnecessary move instruction being generated.
4237       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4238
4239       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4240       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4241       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4242       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4243       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4244
4245       // The address needs to go after the chain input but before the flag (or
4246       // any other variadic arguments).
4247       Ops.insert(std::next(Ops.begin()), AddTOC);
4248     } else if ((CallOpc == PPCISD::CALL) &&
4249                (!isLocalCall(Callee) ||
4250                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4251       // Otherwise insert NOP for non-local calls.
4252       CallOpc = PPCISD::CALL_NOP;
4253   }
4254
4255   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4256   InFlag = Chain.getValue(1);
4257
4258   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4259                              DAG.getIntPtrConstant(BytesCalleePops, true),
4260                              InFlag, dl);
4261   if (!Ins.empty())
4262     InFlag = Chain.getValue(1);
4263
4264   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4265                          Ins, dl, DAG, InVals);
4266 }
4267
4268 SDValue
4269 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4270                              SmallVectorImpl<SDValue> &InVals) const {
4271   SelectionDAG &DAG                     = CLI.DAG;
4272   SDLoc &dl                             = CLI.DL;
4273   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4274   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4275   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4276   SDValue Chain                         = CLI.Chain;
4277   SDValue Callee                        = CLI.Callee;
4278   bool &isTailCall                      = CLI.IsTailCall;
4279   CallingConv::ID CallConv              = CLI.CallConv;
4280   bool isVarArg                         = CLI.IsVarArg;
4281   bool IsPatchPoint                     = CLI.IsPatchPoint;
4282   ImmutableCallSite *CS                 = CLI.CS;
4283
4284   if (isTailCall)
4285     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4286                                                    Ins, DAG);
4287
4288   if (!isTailCall && CS && CS->isMustTailCall())
4289     report_fatal_error("failed to perform tail call elimination on a call "
4290                        "site marked musttail");
4291
4292   if (Subtarget.isSVR4ABI()) {
4293     if (Subtarget.isPPC64())
4294       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4295                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4296                               dl, DAG, InVals, CS);
4297     else
4298       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4299                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4300                               dl, DAG, InVals, CS);
4301   }
4302
4303   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4304                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4305                           dl, DAG, InVals, CS);
4306 }
4307
4308 SDValue
4309 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4310                                     CallingConv::ID CallConv, bool isVarArg,
4311                                     bool isTailCall, bool IsPatchPoint,
4312                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4313                                     const SmallVectorImpl<SDValue> &OutVals,
4314                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4315                                     SDLoc dl, SelectionDAG &DAG,
4316                                     SmallVectorImpl<SDValue> &InVals,
4317                                     ImmutableCallSite *CS) const {
4318   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4319   // of the 32-bit SVR4 ABI stack frame layout.
4320
4321   assert((CallConv == CallingConv::C ||
4322           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4323
4324   unsigned PtrByteSize = 4;
4325
4326   MachineFunction &MF = DAG.getMachineFunction();
4327
4328   // Mark this function as potentially containing a function that contains a
4329   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4330   // and restoring the callers stack pointer in this functions epilog. This is
4331   // done because by tail calling the called function might overwrite the value
4332   // in this function's (MF) stack pointer stack slot 0(SP).
4333   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4334       CallConv == CallingConv::Fast)
4335     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4336
4337   // Count how many bytes are to be pushed on the stack, including the linkage
4338   // area, parameter list area and the part of the local variable space which
4339   // contains copies of aggregates which are passed by value.
4340
4341   // Assign locations to all of the outgoing arguments.
4342   SmallVector<CCValAssign, 16> ArgLocs;
4343   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4344                  *DAG.getContext());
4345
4346   // Reserve space for the linkage area on the stack.
4347   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4348                        PtrByteSize);
4349
4350   if (isVarArg) {
4351     // Handle fixed and variable vector arguments differently.
4352     // Fixed vector arguments go into registers as long as registers are
4353     // available. Variable vector arguments always go into memory.
4354     unsigned NumArgs = Outs.size();
4355
4356     for (unsigned i = 0; i != NumArgs; ++i) {
4357       MVT ArgVT = Outs[i].VT;
4358       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4359       bool Result;
4360
4361       if (Outs[i].IsFixed) {
4362         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4363                                CCInfo);
4364       } else {
4365         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4366                                       ArgFlags, CCInfo);
4367       }
4368
4369       if (Result) {
4370 #ifndef NDEBUG
4371         errs() << "Call operand #" << i << " has unhandled type "
4372              << EVT(ArgVT).getEVTString() << "\n";
4373 #endif
4374         llvm_unreachable(nullptr);
4375       }
4376     }
4377   } else {
4378     // All arguments are treated the same.
4379     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4380   }
4381
4382   // Assign locations to all of the outgoing aggregate by value arguments.
4383   SmallVector<CCValAssign, 16> ByValArgLocs;
4384   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4385                       ByValArgLocs, *DAG.getContext());
4386
4387   // Reserve stack space for the allocations in CCInfo.
4388   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4389
4390   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4391
4392   // Size of the linkage area, parameter list area and the part of the local
4393   // space variable where copies of aggregates which are passed by value are
4394   // stored.
4395   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4396
4397   // Calculate by how many bytes the stack has to be adjusted in case of tail
4398   // call optimization.
4399   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4400
4401   // Adjust the stack pointer for the new arguments...
4402   // These operations are automatically eliminated by the prolog/epilog pass
4403   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4404                                dl);
4405   SDValue CallSeqStart = Chain;
4406
4407   // Load the return address and frame pointer so it can be moved somewhere else
4408   // later.
4409   SDValue LROp, FPOp;
4410   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4411                                        dl);
4412
4413   // Set up a copy of the stack pointer for use loading and storing any
4414   // arguments that may not fit in the registers available for argument
4415   // passing.
4416   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4417
4418   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4419   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4420   SmallVector<SDValue, 8> MemOpChains;
4421
4422   bool seenFloatArg = false;
4423   // Walk the register/memloc assignments, inserting copies/loads.
4424   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4425        i != e;
4426        ++i) {
4427     CCValAssign &VA = ArgLocs[i];
4428     SDValue Arg = OutVals[i];
4429     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4430
4431     if (Flags.isByVal()) {
4432       // Argument is an aggregate which is passed by value, thus we need to
4433       // create a copy of it in the local variable space of the current stack
4434       // frame (which is the stack frame of the caller) and pass the address of
4435       // this copy to the callee.
4436       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4437       CCValAssign &ByValVA = ByValArgLocs[j++];
4438       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4439
4440       // Memory reserved in the local variable space of the callers stack frame.
4441       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4442
4443       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4444       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4445
4446       // Create a copy of the argument in the local area of the current
4447       // stack frame.
4448       SDValue MemcpyCall =
4449         CreateCopyOfByValArgument(Arg, PtrOff,
4450                                   CallSeqStart.getNode()->getOperand(0),
4451                                   Flags, DAG, dl);
4452
4453       // This must go outside the CALLSEQ_START..END.
4454       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4455                            CallSeqStart.getNode()->getOperand(1),
4456                            SDLoc(MemcpyCall));
4457       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4458                              NewCallSeqStart.getNode());
4459       Chain = CallSeqStart = NewCallSeqStart;
4460
4461       // Pass the address of the aggregate copy on the stack either in a
4462       // physical register or in the parameter list area of the current stack
4463       // frame to the callee.
4464       Arg = PtrOff;
4465     }
4466
4467     if (VA.isRegLoc()) {
4468       if (Arg.getValueType() == MVT::i1)
4469         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4470
4471       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4472       // Put argument in a physical register.
4473       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4474     } else {
4475       // Put argument in the parameter list area of the current stack frame.
4476       assert(VA.isMemLoc());
4477       unsigned LocMemOffset = VA.getLocMemOffset();
4478
4479       if (!isTailCall) {
4480         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4481         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4482
4483         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4484                                            MachinePointerInfo(),
4485                                            false, false, 0));
4486       } else {
4487         // Calculate and remember argument location.
4488         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4489                                  TailCallArguments);
4490       }
4491     }
4492   }
4493
4494   if (!MemOpChains.empty())
4495     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4496
4497   // Build a sequence of copy-to-reg nodes chained together with token chain
4498   // and flag operands which copy the outgoing args into the appropriate regs.
4499   SDValue InFlag;
4500   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4501     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4502                              RegsToPass[i].second, InFlag);
4503     InFlag = Chain.getValue(1);
4504   }
4505
4506   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4507   // registers.
4508   if (isVarArg) {
4509     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4510     SDValue Ops[] = { Chain, InFlag };
4511
4512     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4513                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4514
4515     InFlag = Chain.getValue(1);
4516   }
4517
4518   if (isTailCall)
4519     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4520                     false, TailCallArguments);
4521
4522   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4523                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4524                     NumBytes, Ins, InVals, CS);
4525 }
4526
4527 // Copy an argument into memory, being careful to do this outside the
4528 // call sequence for the call to which the argument belongs.
4529 SDValue
4530 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4531                                               SDValue CallSeqStart,
4532                                               ISD::ArgFlagsTy Flags,
4533                                               SelectionDAG &DAG,
4534                                               SDLoc dl) const {
4535   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4536                         CallSeqStart.getNode()->getOperand(0),
4537                         Flags, DAG, dl);
4538   // The MEMCPY must go outside the CALLSEQ_START..END.
4539   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4540                              CallSeqStart.getNode()->getOperand(1),
4541                              SDLoc(MemcpyCall));
4542   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4543                          NewCallSeqStart.getNode());
4544   return NewCallSeqStart;
4545 }
4546
4547 SDValue
4548 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4549                                     CallingConv::ID CallConv, bool isVarArg,
4550                                     bool isTailCall, bool IsPatchPoint,
4551                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4552                                     const SmallVectorImpl<SDValue> &OutVals,
4553                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4554                                     SDLoc dl, SelectionDAG &DAG,
4555                                     SmallVectorImpl<SDValue> &InVals,
4556                                     ImmutableCallSite *CS) const {
4557
4558   bool isELFv2ABI = Subtarget.isELFv2ABI();
4559   bool isLittleEndian = Subtarget.isLittleEndian();
4560   unsigned NumOps = Outs.size();
4561
4562   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4563   unsigned PtrByteSize = 8;
4564
4565   MachineFunction &MF = DAG.getMachineFunction();
4566
4567   // Mark this function as potentially containing a function that contains a
4568   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4569   // and restoring the callers stack pointer in this functions epilog. This is
4570   // done because by tail calling the called function might overwrite the value
4571   // in this function's (MF) stack pointer stack slot 0(SP).
4572   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4573       CallConv == CallingConv::Fast)
4574     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4575
4576   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4577          "fastcc not supported on varargs functions");
4578
4579   // Count how many bytes are to be pushed on the stack, including the linkage
4580   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4581   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4582   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4583   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4584   unsigned NumBytes = LinkageSize;
4585   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4586   unsigned &QFPR_idx = FPR_idx;
4587
4588   static const MCPhysReg GPR[] = {
4589     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4590     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4591   };
4592   static const MCPhysReg *FPR = GetFPR();
4593
4594   static const MCPhysReg VR[] = {
4595     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4596     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4597   };
4598   static const MCPhysReg VSRH[] = {
4599     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4600     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4601   };
4602
4603   static const MCPhysReg *QFPR = GetQFPR();
4604
4605   const unsigned NumGPRs = array_lengthof(GPR);
4606   const unsigned NumFPRs = 13;
4607   const unsigned NumVRs  = array_lengthof(VR);
4608   const unsigned NumQFPRs = NumFPRs;
4609
4610   // When using the fast calling convention, we don't provide backing for
4611   // arguments that will be in registers.
4612   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4613
4614   // Add up all the space actually used.
4615   for (unsigned i = 0; i != NumOps; ++i) {
4616     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4617     EVT ArgVT = Outs[i].VT;
4618     EVT OrigVT = Outs[i].ArgVT;
4619
4620     if (CallConv == CallingConv::Fast) {
4621       if (Flags.isByVal())
4622         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4623       else
4624         switch (ArgVT.getSimpleVT().SimpleTy) {
4625         default: llvm_unreachable("Unexpected ValueType for argument!");
4626         case MVT::i1:
4627         case MVT::i32:
4628         case MVT::i64:
4629           if (++NumGPRsUsed <= NumGPRs)
4630             continue;
4631           break;
4632         case MVT::v4i32:
4633         case MVT::v8i16:
4634         case MVT::v16i8:
4635         case MVT::v2f64:
4636         case MVT::v2i64:
4637           if (++NumVRsUsed <= NumVRs)
4638             continue;
4639           break;
4640         case MVT::v4f32:
4641           // When using QPX, this is handled like a FP register, otherwise, it
4642           // is an Altivec register.
4643           if (Subtarget.hasQPX()) {
4644             if (++NumFPRsUsed <= NumFPRs)
4645               continue;
4646           } else {
4647             if (++NumVRsUsed <= NumVRs)
4648               continue;
4649           }
4650           break;
4651         case MVT::f32:
4652         case MVT::f64:
4653         case MVT::v4f64: // QPX
4654         case MVT::v4i1:  // QPX
4655           if (++NumFPRsUsed <= NumFPRs)
4656             continue;
4657           break;
4658         }
4659     }
4660
4661     /* Respect alignment of argument on the stack.  */
4662     unsigned Align =
4663       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4664     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4665
4666     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4667     if (Flags.isInConsecutiveRegsLast())
4668       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4669   }
4670
4671   unsigned NumBytesActuallyUsed = NumBytes;
4672
4673   // The prolog code of the callee may store up to 8 GPR argument registers to
4674   // the stack, allowing va_start to index over them in memory if its varargs.
4675   // Because we cannot tell if this is needed on the caller side, we have to
4676   // conservatively assume that it is needed.  As such, make sure we have at
4677   // least enough stack space for the caller to store the 8 GPRs.
4678   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4679   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4680
4681   // Tail call needs the stack to be aligned.
4682   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4683       CallConv == CallingConv::Fast)
4684     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4685
4686   // Calculate by how many bytes the stack has to be adjusted in case of tail
4687   // call optimization.
4688   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4689
4690   // To protect arguments on the stack from being clobbered in a tail call,
4691   // force all the loads to happen before doing any other lowering.
4692   if (isTailCall)
4693     Chain = DAG.getStackArgumentTokenFactor(Chain);
4694
4695   // Adjust the stack pointer for the new arguments...
4696   // These operations are automatically eliminated by the prolog/epilog pass
4697   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4698                                dl);
4699   SDValue CallSeqStart = Chain;
4700
4701   // Load the return address and frame pointer so it can be move somewhere else
4702   // later.
4703   SDValue LROp, FPOp;
4704   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4705                                        dl);
4706
4707   // Set up a copy of the stack pointer for use loading and storing any
4708   // arguments that may not fit in the registers available for argument
4709   // passing.
4710   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4711
4712   // Figure out which arguments are going to go in registers, and which in
4713   // memory.  Also, if this is a vararg function, floating point operations
4714   // must be stored to our stack, and loaded into integer regs as well, if
4715   // any integer regs are available for argument passing.
4716   unsigned ArgOffset = LinkageSize;
4717
4718   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4719   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4720
4721   SmallVector<SDValue, 8> MemOpChains;
4722   for (unsigned i = 0; i != NumOps; ++i) {
4723     SDValue Arg = OutVals[i];
4724     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4725     EVT ArgVT = Outs[i].VT;
4726     EVT OrigVT = Outs[i].ArgVT;
4727
4728     // PtrOff will be used to store the current argument to the stack if a
4729     // register cannot be found for it.
4730     SDValue PtrOff;
4731
4732     // We re-align the argument offset for each argument, except when using the
4733     // fast calling convention, when we need to make sure we do that only when
4734     // we'll actually use a stack slot.
4735     auto ComputePtrOff = [&]() {
4736       /* Respect alignment of argument on the stack.  */
4737       unsigned Align =
4738         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4739       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4740
4741       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4742
4743       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4744     };
4745
4746     if (CallConv != CallingConv::Fast) {
4747       ComputePtrOff();
4748
4749       /* Compute GPR index associated with argument offset.  */
4750       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4751       GPR_idx = std::min(GPR_idx, NumGPRs);
4752     }
4753
4754     // Promote integers to 64-bit values.
4755     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4756       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4757       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4758       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4759     }
4760
4761     // FIXME memcpy is used way more than necessary.  Correctness first.
4762     // Note: "by value" is code for passing a structure by value, not
4763     // basic types.
4764     if (Flags.isByVal()) {
4765       // Note: Size includes alignment padding, so
4766       //   struct x { short a; char b; }
4767       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4768       // These are the proper values we need for right-justifying the
4769       // aggregate in a parameter register.
4770       unsigned Size = Flags.getByValSize();
4771
4772       // An empty aggregate parameter takes up no storage and no
4773       // registers.
4774       if (Size == 0)
4775         continue;
4776
4777       if (CallConv == CallingConv::Fast)
4778         ComputePtrOff();
4779
4780       // All aggregates smaller than 8 bytes must be passed right-justified.
4781       if (Size==1 || Size==2 || Size==4) {
4782         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4783         if (GPR_idx != NumGPRs) {
4784           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4785                                         MachinePointerInfo(), VT,
4786                                         false, false, false, 0);
4787           MemOpChains.push_back(Load.getValue(1));
4788           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4789
4790           ArgOffset += PtrByteSize;
4791           continue;
4792         }
4793       }
4794
4795       if (GPR_idx == NumGPRs && Size < 8) {
4796         SDValue AddPtr = PtrOff;
4797         if (!isLittleEndian) {
4798           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4799                                           PtrOff.getValueType());
4800           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4801         }
4802         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4803                                                           CallSeqStart,
4804                                                           Flags, DAG, dl);
4805         ArgOffset += PtrByteSize;
4806         continue;
4807       }
4808       // Copy entire object into memory.  There are cases where gcc-generated
4809       // code assumes it is there, even if it could be put entirely into
4810       // registers.  (This is not what the doc says.)
4811
4812       // FIXME: The above statement is likely due to a misunderstanding of the
4813       // documents.  All arguments must be copied into the parameter area BY
4814       // THE CALLEE in the event that the callee takes the address of any
4815       // formal argument.  That has not yet been implemented.  However, it is
4816       // reasonable to use the stack area as a staging area for the register
4817       // load.
4818
4819       // Skip this for small aggregates, as we will use the same slot for a
4820       // right-justified copy, below.
4821       if (Size >= 8)
4822         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4823                                                           CallSeqStart,
4824                                                           Flags, DAG, dl);
4825
4826       // When a register is available, pass a small aggregate right-justified.
4827       if (Size < 8 && GPR_idx != NumGPRs) {
4828         // The easiest way to get this right-justified in a register
4829         // is to copy the structure into the rightmost portion of a
4830         // local variable slot, then load the whole slot into the
4831         // register.
4832         // FIXME: The memcpy seems to produce pretty awful code for
4833         // small aggregates, particularly for packed ones.
4834         // FIXME: It would be preferable to use the slot in the
4835         // parameter save area instead of a new local variable.
4836         SDValue AddPtr = PtrOff;
4837         if (!isLittleEndian) {
4838           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4839           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4840         }
4841         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4842                                                           CallSeqStart,
4843                                                           Flags, DAG, dl);
4844
4845         // Load the slot into the register.
4846         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4847                                    MachinePointerInfo(),
4848                                    false, false, false, 0);
4849         MemOpChains.push_back(Load.getValue(1));
4850         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4851
4852         // Done with this argument.
4853         ArgOffset += PtrByteSize;
4854         continue;
4855       }
4856
4857       // For aggregates larger than PtrByteSize, copy the pieces of the
4858       // object that fit into registers from the parameter save area.
4859       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4860         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4861         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4862         if (GPR_idx != NumGPRs) {
4863           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4864                                      MachinePointerInfo(),
4865                                      false, false, false, 0);
4866           MemOpChains.push_back(Load.getValue(1));
4867           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4868           ArgOffset += PtrByteSize;
4869         } else {
4870           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4871           break;
4872         }
4873       }
4874       continue;
4875     }
4876
4877     switch (Arg.getSimpleValueType().SimpleTy) {
4878     default: llvm_unreachable("Unexpected ValueType for argument!");
4879     case MVT::i1:
4880     case MVT::i32:
4881     case MVT::i64:
4882       // These can be scalar arguments or elements of an integer array type
4883       // passed directly.  Clang may use those instead of "byval" aggregate
4884       // types to avoid forcing arguments to memory unnecessarily.
4885       if (GPR_idx != NumGPRs) {
4886         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4887       } else {
4888         if (CallConv == CallingConv::Fast)
4889           ComputePtrOff();
4890
4891         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4892                          true, isTailCall, false, MemOpChains,
4893                          TailCallArguments, dl);
4894         if (CallConv == CallingConv::Fast)
4895           ArgOffset += PtrByteSize;
4896       }
4897       if (CallConv != CallingConv::Fast)
4898         ArgOffset += PtrByteSize;
4899       break;
4900     case MVT::f32:
4901     case MVT::f64: {
4902       // These can be scalar arguments or elements of a float array type
4903       // passed directly.  The latter are used to implement ELFv2 homogenous
4904       // float aggregates.
4905
4906       // Named arguments go into FPRs first, and once they overflow, the
4907       // remaining arguments go into GPRs and then the parameter save area.
4908       // Unnamed arguments for vararg functions always go to GPRs and
4909       // then the parameter save area.  For now, put all arguments to vararg
4910       // routines always in both locations (FPR *and* GPR or stack slot).
4911       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4912       bool NeededLoad = false;
4913
4914       // First load the argument into the next available FPR.
4915       if (FPR_idx != NumFPRs)
4916         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4917
4918       // Next, load the argument into GPR or stack slot if needed.
4919       if (!NeedGPROrStack)
4920         ;
4921       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4922         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4923         // once we support fp <-> gpr moves.
4924
4925         // In the non-vararg case, this can only ever happen in the
4926         // presence of f32 array types, since otherwise we never run
4927         // out of FPRs before running out of GPRs.
4928         SDValue ArgVal;
4929
4930         // Double values are always passed in a single GPR.
4931         if (Arg.getValueType() != MVT::f32) {
4932           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4933
4934         // Non-array float values are extended and passed in a GPR.
4935         } else if (!Flags.isInConsecutiveRegs()) {
4936           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4937           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4938
4939         // If we have an array of floats, we collect every odd element
4940         // together with its predecessor into one GPR.
4941         } else if (ArgOffset % PtrByteSize != 0) {
4942           SDValue Lo, Hi;
4943           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4944           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4945           if (!isLittleEndian)
4946             std::swap(Lo, Hi);
4947           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4948
4949         // The final element, if even, goes into the first half of a GPR.
4950         } else if (Flags.isInConsecutiveRegsLast()) {
4951           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4952           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4953           if (!isLittleEndian)
4954             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4955                                  DAG.getConstant(32, MVT::i32));
4956
4957         // Non-final even elements are skipped; they will be handled
4958         // together the with subsequent argument on the next go-around.
4959         } else
4960           ArgVal = SDValue();
4961
4962         if (ArgVal.getNode())
4963           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4964       } else {
4965         if (CallConv == CallingConv::Fast)
4966           ComputePtrOff();
4967
4968         // Single-precision floating-point values are mapped to the
4969         // second (rightmost) word of the stack doubleword.
4970         if (Arg.getValueType() == MVT::f32 &&
4971             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4972           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4973           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4974         }
4975
4976         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4977                          true, isTailCall, false, MemOpChains,
4978                          TailCallArguments, dl);
4979
4980         NeededLoad = true;
4981       }
4982       // When passing an array of floats, the array occupies consecutive
4983       // space in the argument area; only round up to the next doubleword
4984       // at the end of the array.  Otherwise, each float takes 8 bytes.
4985       if (CallConv != CallingConv::Fast || NeededLoad) {
4986         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4987                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4988         if (Flags.isInConsecutiveRegsLast())
4989           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4990       }
4991       break;
4992     }
4993     case MVT::v4f32:
4994     case MVT::v4i32:
4995     case MVT::v8i16:
4996     case MVT::v16i8:
4997     case MVT::v2f64:
4998     case MVT::v2i64:
4999       if (!Subtarget.hasQPX()) {
5000       // These can be scalar arguments or elements of a vector array type
5001       // passed directly.  The latter are used to implement ELFv2 homogenous
5002       // vector aggregates.
5003
5004       // For a varargs call, named arguments go into VRs or on the stack as
5005       // usual; unnamed arguments always go to the stack or the corresponding
5006       // GPRs when within range.  For now, we always put the value in both
5007       // locations (or even all three).
5008       if (isVarArg) {
5009         // We could elide this store in the case where the object fits
5010         // entirely in R registers.  Maybe later.
5011         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5012                                      MachinePointerInfo(), false, false, 0);
5013         MemOpChains.push_back(Store);
5014         if (VR_idx != NumVRs) {
5015           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5016                                      MachinePointerInfo(),
5017                                      false, false, false, 0);
5018           MemOpChains.push_back(Load.getValue(1));
5019
5020           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5021                            Arg.getSimpleValueType() == MVT::v2i64) ?
5022                           VSRH[VR_idx] : VR[VR_idx];
5023           ++VR_idx;
5024
5025           RegsToPass.push_back(std::make_pair(VReg, Load));
5026         }
5027         ArgOffset += 16;
5028         for (unsigned i=0; i<16; i+=PtrByteSize) {
5029           if (GPR_idx == NumGPRs)
5030             break;
5031           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5032                                   DAG.getConstant(i, PtrVT));
5033           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5034                                      false, false, false, 0);
5035           MemOpChains.push_back(Load.getValue(1));
5036           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5037         }
5038         break;
5039       }
5040
5041       // Non-varargs Altivec params go into VRs or on the stack.
5042       if (VR_idx != NumVRs) {
5043         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5044                          Arg.getSimpleValueType() == MVT::v2i64) ?
5045                         VSRH[VR_idx] : VR[VR_idx];
5046         ++VR_idx;
5047
5048         RegsToPass.push_back(std::make_pair(VReg, Arg));
5049       } else {
5050         if (CallConv == CallingConv::Fast)
5051           ComputePtrOff();
5052
5053         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5054                          true, isTailCall, true, MemOpChains,
5055                          TailCallArguments, dl);
5056         if (CallConv == CallingConv::Fast)
5057           ArgOffset += 16;
5058       }
5059
5060       if (CallConv != CallingConv::Fast)
5061         ArgOffset += 16;
5062       break;
5063       } // not QPX
5064
5065       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5066              "Invalid QPX parameter type");
5067
5068       /* fall through */
5069     case MVT::v4f64:
5070     case MVT::v4i1: {
5071       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5072       if (isVarArg) {
5073         // We could elide this store in the case where the object fits
5074         // entirely in R registers.  Maybe later.
5075         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5076                                      MachinePointerInfo(), false, false, 0);
5077         MemOpChains.push_back(Store);
5078         if (QFPR_idx != NumQFPRs) {
5079           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5080                                      Store, PtrOff, MachinePointerInfo(),
5081                                      false, false, false, 0);
5082           MemOpChains.push_back(Load.getValue(1));
5083           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5084         }
5085         ArgOffset += (IsF32 ? 16 : 32);
5086         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5087           if (GPR_idx == NumGPRs)
5088             break;
5089           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5090                                   DAG.getConstant(i, PtrVT));
5091           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5092                                      false, false, false, 0);
5093           MemOpChains.push_back(Load.getValue(1));
5094           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5095         }
5096         break;
5097       }
5098
5099       // Non-varargs QPX params go into registers or on the stack.
5100       if (QFPR_idx != NumQFPRs) {
5101         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5102       } else {
5103         if (CallConv == CallingConv::Fast)
5104           ComputePtrOff();
5105
5106         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5107                          true, isTailCall, true, MemOpChains,
5108                          TailCallArguments, dl);
5109         if (CallConv == CallingConv::Fast)
5110           ArgOffset += (IsF32 ? 16 : 32);
5111       }
5112
5113       if (CallConv != CallingConv::Fast)
5114         ArgOffset += (IsF32 ? 16 : 32);
5115       break;
5116       }
5117     }
5118   }
5119
5120   assert(NumBytesActuallyUsed == ArgOffset);
5121   (void)NumBytesActuallyUsed;
5122
5123   if (!MemOpChains.empty())
5124     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5125
5126   // Check if this is an indirect call (MTCTR/BCTRL).
5127   // See PrepareCall() for more information about calls through function
5128   // pointers in the 64-bit SVR4 ABI.
5129   if (!isTailCall && !IsPatchPoint &&
5130       !isFunctionGlobalAddress(Callee) &&
5131       !isa<ExternalSymbolSDNode>(Callee)) {
5132     // Load r2 into a virtual register and store it to the TOC save area.
5133     setUsesTOCBasePtr(DAG);
5134     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5135     // TOC save area offset.
5136     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5137     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5138     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5139     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5140                          MachinePointerInfo::getStack(TOCSaveOffset),
5141                          false, false, 0);
5142     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5143     // This does not mean the MTCTR instruction must use R12; it's easier
5144     // to model this as an extra parameter, so do that.
5145     if (isELFv2ABI && !IsPatchPoint)
5146       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5147   }
5148
5149   // Build a sequence of copy-to-reg nodes chained together with token chain
5150   // and flag operands which copy the outgoing args into the appropriate regs.
5151   SDValue InFlag;
5152   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5153     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5154                              RegsToPass[i].second, InFlag);
5155     InFlag = Chain.getValue(1);
5156   }
5157
5158   if (isTailCall)
5159     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5160                     FPOp, true, TailCallArguments);
5161
5162   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5163                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5164                     NumBytes, Ins, InVals, CS);
5165 }
5166
5167 SDValue
5168 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5169                                     CallingConv::ID CallConv, bool isVarArg,
5170                                     bool isTailCall, bool IsPatchPoint,
5171                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5172                                     const SmallVectorImpl<SDValue> &OutVals,
5173                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5174                                     SDLoc dl, SelectionDAG &DAG,
5175                                     SmallVectorImpl<SDValue> &InVals,
5176                                     ImmutableCallSite *CS) const {
5177
5178   unsigned NumOps = Outs.size();
5179
5180   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5181   bool isPPC64 = PtrVT == MVT::i64;
5182   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5183
5184   MachineFunction &MF = DAG.getMachineFunction();
5185
5186   // Mark this function as potentially containing a function that contains a
5187   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5188   // and restoring the callers stack pointer in this functions epilog. This is
5189   // done because by tail calling the called function might overwrite the value
5190   // in this function's (MF) stack pointer stack slot 0(SP).
5191   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5192       CallConv == CallingConv::Fast)
5193     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5194
5195   // Count how many bytes are to be pushed on the stack, including the linkage
5196   // area, and parameter passing area.  We start with 24/48 bytes, which is
5197   // prereserved space for [SP][CR][LR][3 x unused].
5198   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5199   unsigned NumBytes = LinkageSize;
5200
5201   // Add up all the space actually used.
5202   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5203   // they all go in registers, but we must reserve stack space for them for
5204   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5205   // assigned stack space in order, with padding so Altivec parameters are
5206   // 16-byte aligned.
5207   unsigned nAltivecParamsAtEnd = 0;
5208   for (unsigned i = 0; i != NumOps; ++i) {
5209     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5210     EVT ArgVT = Outs[i].VT;
5211     // Varargs Altivec parameters are padded to a 16 byte boundary.
5212     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5213         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5214         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5215       if (!isVarArg && !isPPC64) {
5216         // Non-varargs Altivec parameters go after all the non-Altivec
5217         // parameters; handle those later so we know how much padding we need.
5218         nAltivecParamsAtEnd++;
5219         continue;
5220       }
5221       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5222       NumBytes = ((NumBytes+15)/16)*16;
5223     }
5224     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5225   }
5226
5227   // Allow for Altivec parameters at the end, if needed.
5228   if (nAltivecParamsAtEnd) {
5229     NumBytes = ((NumBytes+15)/16)*16;
5230     NumBytes += 16*nAltivecParamsAtEnd;
5231   }
5232
5233   // The prolog code of the callee may store up to 8 GPR argument registers to
5234   // the stack, allowing va_start to index over them in memory if its varargs.
5235   // Because we cannot tell if this is needed on the caller side, we have to
5236   // conservatively assume that it is needed.  As such, make sure we have at
5237   // least enough stack space for the caller to store the 8 GPRs.
5238   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5239
5240   // Tail call needs the stack to be aligned.
5241   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5242       CallConv == CallingConv::Fast)
5243     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5244
5245   // Calculate by how many bytes the stack has to be adjusted in case of tail
5246   // call optimization.
5247   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5248
5249   // To protect arguments on the stack from being clobbered in a tail call,
5250   // force all the loads to happen before doing any other lowering.
5251   if (isTailCall)
5252     Chain = DAG.getStackArgumentTokenFactor(Chain);
5253
5254   // Adjust the stack pointer for the new arguments...
5255   // These operations are automatically eliminated by the prolog/epilog pass
5256   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5257                                dl);
5258   SDValue CallSeqStart = Chain;
5259
5260   // Load the return address and frame pointer so it can be move somewhere else
5261   // later.
5262   SDValue LROp, FPOp;
5263   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5264                                        dl);
5265
5266   // Set up a copy of the stack pointer for use loading and storing any
5267   // arguments that may not fit in the registers available for argument
5268   // passing.
5269   SDValue StackPtr;
5270   if (isPPC64)
5271     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5272   else
5273     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5274
5275   // Figure out which arguments are going to go in registers, and which in
5276   // memory.  Also, if this is a vararg function, floating point operations
5277   // must be stored to our stack, and loaded into integer regs as well, if
5278   // any integer regs are available for argument passing.
5279   unsigned ArgOffset = LinkageSize;
5280   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5281
5282   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5283     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5284     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5285   };
5286   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5287     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5288     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5289   };
5290   static const MCPhysReg *FPR = GetFPR();
5291
5292   static const MCPhysReg VR[] = {
5293     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5294     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5295   };
5296   const unsigned NumGPRs = array_lengthof(GPR_32);
5297   const unsigned NumFPRs = 13;
5298   const unsigned NumVRs  = array_lengthof(VR);
5299
5300   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5301
5302   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5303   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5304
5305   SmallVector<SDValue, 8> MemOpChains;
5306   for (unsigned i = 0; i != NumOps; ++i) {
5307     SDValue Arg = OutVals[i];
5308     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5309
5310     // PtrOff will be used to store the current argument to the stack if a
5311     // register cannot be found for it.
5312     SDValue PtrOff;
5313
5314     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5315
5316     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5317
5318     // On PPC64, promote integers to 64-bit values.
5319     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5320       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5321       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5322       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5323     }
5324
5325     // FIXME memcpy is used way more than necessary.  Correctness first.
5326     // Note: "by value" is code for passing a structure by value, not
5327     // basic types.
5328     if (Flags.isByVal()) {
5329       unsigned Size = Flags.getByValSize();
5330       // Very small objects are passed right-justified.  Everything else is
5331       // passed left-justified.
5332       if (Size==1 || Size==2) {
5333         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5334         if (GPR_idx != NumGPRs) {
5335           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5336                                         MachinePointerInfo(), VT,
5337                                         false, false, false, 0);
5338           MemOpChains.push_back(Load.getValue(1));
5339           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5340
5341           ArgOffset += PtrByteSize;
5342         } else {
5343           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5344                                           PtrOff.getValueType());
5345           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5346           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5347                                                             CallSeqStart,
5348                                                             Flags, DAG, dl);
5349           ArgOffset += PtrByteSize;
5350         }
5351         continue;
5352       }
5353       // Copy entire object into memory.  There are cases where gcc-generated
5354       // code assumes it is there, even if it could be put entirely into
5355       // registers.  (This is not what the doc says.)
5356       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5357                                                         CallSeqStart,
5358                                                         Flags, DAG, dl);
5359
5360       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5361       // copy the pieces of the object that fit into registers from the
5362       // parameter save area.
5363       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5364         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5365         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5366         if (GPR_idx != NumGPRs) {
5367           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5368                                      MachinePointerInfo(),
5369                                      false, false, false, 0);
5370           MemOpChains.push_back(Load.getValue(1));
5371           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5372           ArgOffset += PtrByteSize;
5373         } else {
5374           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5375           break;
5376         }
5377       }
5378       continue;
5379     }
5380
5381     switch (Arg.getSimpleValueType().SimpleTy) {
5382     default: llvm_unreachable("Unexpected ValueType for argument!");
5383     case MVT::i1:
5384     case MVT::i32:
5385     case MVT::i64:
5386       if (GPR_idx != NumGPRs) {
5387         if (Arg.getValueType() == MVT::i1)
5388           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5389
5390         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5391       } else {
5392         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5393                          isPPC64, isTailCall, false, MemOpChains,
5394                          TailCallArguments, dl);
5395       }
5396       ArgOffset += PtrByteSize;
5397       break;
5398     case MVT::f32:
5399     case MVT::f64:
5400       if (FPR_idx != NumFPRs) {
5401         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5402
5403         if (isVarArg) {
5404           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5405                                        MachinePointerInfo(), false, false, 0);
5406           MemOpChains.push_back(Store);
5407
5408           // Float varargs are always shadowed in available integer registers
5409           if (GPR_idx != NumGPRs) {
5410             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5411                                        MachinePointerInfo(), false, false,
5412                                        false, 0);
5413             MemOpChains.push_back(Load.getValue(1));
5414             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5415           }
5416           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5417             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5418             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5419             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5420                                        MachinePointerInfo(),
5421                                        false, false, false, 0);
5422             MemOpChains.push_back(Load.getValue(1));
5423             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5424           }
5425         } else {
5426           // If we have any FPRs remaining, we may also have GPRs remaining.
5427           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5428           // GPRs.
5429           if (GPR_idx != NumGPRs)
5430             ++GPR_idx;
5431           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5432               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5433             ++GPR_idx;
5434         }
5435       } else
5436         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5437                          isPPC64, isTailCall, false, MemOpChains,
5438                          TailCallArguments, dl);
5439       if (isPPC64)
5440         ArgOffset += 8;
5441       else
5442         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5443       break;
5444     case MVT::v4f32:
5445     case MVT::v4i32:
5446     case MVT::v8i16:
5447     case MVT::v16i8:
5448       if (isVarArg) {
5449         // These go aligned on the stack, or in the corresponding R registers
5450         // when within range.  The Darwin PPC ABI doc claims they also go in
5451         // V registers; in fact gcc does this only for arguments that are
5452         // prototyped, not for those that match the ...  We do it for all
5453         // arguments, seems to work.
5454         while (ArgOffset % 16 !=0) {
5455           ArgOffset += PtrByteSize;
5456           if (GPR_idx != NumGPRs)
5457             GPR_idx++;
5458         }
5459         // We could elide this store in the case where the object fits
5460         // entirely in R registers.  Maybe later.
5461         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5462                             DAG.getConstant(ArgOffset, PtrVT));
5463         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5464                                      MachinePointerInfo(), false, false, 0);
5465         MemOpChains.push_back(Store);
5466         if (VR_idx != NumVRs) {
5467           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5468                                      MachinePointerInfo(),
5469                                      false, false, false, 0);
5470           MemOpChains.push_back(Load.getValue(1));
5471           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5472         }
5473         ArgOffset += 16;
5474         for (unsigned i=0; i<16; i+=PtrByteSize) {
5475           if (GPR_idx == NumGPRs)
5476             break;
5477           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5478                                   DAG.getConstant(i, PtrVT));
5479           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5480                                      false, false, false, 0);
5481           MemOpChains.push_back(Load.getValue(1));
5482           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5483         }
5484         break;
5485       }
5486
5487       // Non-varargs Altivec params generally go in registers, but have
5488       // stack space allocated at the end.
5489       if (VR_idx != NumVRs) {
5490         // Doesn't have GPR space allocated.
5491         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5492       } else if (nAltivecParamsAtEnd==0) {
5493         // We are emitting Altivec params in order.
5494         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5495                          isPPC64, isTailCall, true, MemOpChains,
5496                          TailCallArguments, dl);
5497         ArgOffset += 16;
5498       }
5499       break;
5500     }
5501   }
5502   // If all Altivec parameters fit in registers, as they usually do,
5503   // they get stack space following the non-Altivec parameters.  We
5504   // don't track this here because nobody below needs it.
5505   // If there are more Altivec parameters than fit in registers emit
5506   // the stores here.
5507   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5508     unsigned j = 0;
5509     // Offset is aligned; skip 1st 12 params which go in V registers.
5510     ArgOffset = ((ArgOffset+15)/16)*16;
5511     ArgOffset += 12*16;
5512     for (unsigned i = 0; i != NumOps; ++i) {
5513       SDValue Arg = OutVals[i];
5514       EVT ArgType = Outs[i].VT;
5515       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5516           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5517         if (++j > NumVRs) {
5518           SDValue PtrOff;
5519           // We are emitting Altivec params in order.
5520           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5521                            isPPC64, isTailCall, true, MemOpChains,
5522                            TailCallArguments, dl);
5523           ArgOffset += 16;
5524         }
5525       }
5526     }
5527   }
5528
5529   if (!MemOpChains.empty())
5530     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5531
5532   // On Darwin, R12 must contain the address of an indirect callee.  This does
5533   // not mean the MTCTR instruction must use R12; it's easier to model this as
5534   // an extra parameter, so do that.
5535   if (!isTailCall &&
5536       !isFunctionGlobalAddress(Callee) &&
5537       !isa<ExternalSymbolSDNode>(Callee) &&
5538       !isBLACompatibleAddress(Callee, DAG))
5539     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5540                                                    PPC::R12), Callee));
5541
5542   // Build a sequence of copy-to-reg nodes chained together with token chain
5543   // and flag operands which copy the outgoing args into the appropriate regs.
5544   SDValue InFlag;
5545   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5546     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5547                              RegsToPass[i].second, InFlag);
5548     InFlag = Chain.getValue(1);
5549   }
5550
5551   if (isTailCall)
5552     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5553                     FPOp, true, TailCallArguments);
5554
5555   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5556                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5557                     NumBytes, Ins, InVals, CS);
5558 }
5559
5560 bool
5561 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5562                                   MachineFunction &MF, bool isVarArg,
5563                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5564                                   LLVMContext &Context) const {
5565   SmallVector<CCValAssign, 16> RVLocs;
5566   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5567   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5568 }
5569
5570 SDValue
5571 PPCTargetLowering::LowerReturn(SDValue Chain,
5572                                CallingConv::ID CallConv, bool isVarArg,
5573                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5574                                const SmallVectorImpl<SDValue> &OutVals,
5575                                SDLoc dl, SelectionDAG &DAG) const {
5576
5577   SmallVector<CCValAssign, 16> RVLocs;
5578   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5579                  *DAG.getContext());
5580   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5581
5582   SDValue Flag;
5583   SmallVector<SDValue, 4> RetOps(1, Chain);
5584
5585   // Copy the result values into the output registers.
5586   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5587     CCValAssign &VA = RVLocs[i];
5588     assert(VA.isRegLoc() && "Can only return in registers!");
5589
5590     SDValue Arg = OutVals[i];
5591
5592     switch (VA.getLocInfo()) {
5593     default: llvm_unreachable("Unknown loc info!");
5594     case CCValAssign::Full: break;
5595     case CCValAssign::AExt:
5596       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5597       break;
5598     case CCValAssign::ZExt:
5599       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5600       break;
5601     case CCValAssign::SExt:
5602       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5603       break;
5604     }
5605
5606     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5607     Flag = Chain.getValue(1);
5608     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5609   }
5610
5611   RetOps[0] = Chain;  // Update chain.
5612
5613   // Add the flag if we have it.
5614   if (Flag.getNode())
5615     RetOps.push_back(Flag);
5616
5617   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5618 }
5619
5620 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5621                                    const PPCSubtarget &Subtarget) const {
5622   // When we pop the dynamic allocation we need to restore the SP link.
5623   SDLoc dl(Op);
5624
5625   // Get the corect type for pointers.
5626   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5627
5628   // Construct the stack pointer operand.
5629   bool isPPC64 = Subtarget.isPPC64();
5630   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5631   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5632
5633   // Get the operands for the STACKRESTORE.
5634   SDValue Chain = Op.getOperand(0);
5635   SDValue SaveSP = Op.getOperand(1);
5636
5637   // Load the old link SP.
5638   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5639                                    MachinePointerInfo(),
5640                                    false, false, false, 0);
5641
5642   // Restore the stack pointer.
5643   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5644
5645   // Store the old link SP.
5646   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5647                       false, false, 0);
5648 }
5649
5650
5651
5652 SDValue
5653 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5654   MachineFunction &MF = DAG.getMachineFunction();
5655   bool isPPC64 = Subtarget.isPPC64();
5656   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5657
5658   // Get current frame pointer save index.  The users of this index will be
5659   // primarily DYNALLOC instructions.
5660   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5661   int RASI = FI->getReturnAddrSaveIndex();
5662
5663   // If the frame pointer save index hasn't been defined yet.
5664   if (!RASI) {
5665     // Find out what the fix offset of the frame pointer save area.
5666     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5667     // Allocate the frame index for frame pointer save area.
5668     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5669     // Save the result.
5670     FI->setReturnAddrSaveIndex(RASI);
5671   }
5672   return DAG.getFrameIndex(RASI, PtrVT);
5673 }
5674
5675 SDValue
5676 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5677   MachineFunction &MF = DAG.getMachineFunction();
5678   bool isPPC64 = Subtarget.isPPC64();
5679   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5680
5681   // Get current frame pointer save index.  The users of this index will be
5682   // primarily DYNALLOC instructions.
5683   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5684   int FPSI = FI->getFramePointerSaveIndex();
5685
5686   // If the frame pointer save index hasn't been defined yet.
5687   if (!FPSI) {
5688     // Find out what the fix offset of the frame pointer save area.
5689     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5690     // Allocate the frame index for frame pointer save area.
5691     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5692     // Save the result.
5693     FI->setFramePointerSaveIndex(FPSI);
5694   }
5695   return DAG.getFrameIndex(FPSI, PtrVT);
5696 }
5697
5698 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5699                                          SelectionDAG &DAG,
5700                                          const PPCSubtarget &Subtarget) const {
5701   // Get the inputs.
5702   SDValue Chain = Op.getOperand(0);
5703   SDValue Size  = Op.getOperand(1);
5704   SDLoc dl(Op);
5705
5706   // Get the corect type for pointers.
5707   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5708   // Negate the size.
5709   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5710                                   DAG.getConstant(0, PtrVT), Size);
5711   // Construct a node for the frame pointer save index.
5712   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5713   // Build a DYNALLOC node.
5714   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5715   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5716   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5717 }
5718
5719 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5720                                                SelectionDAG &DAG) const {
5721   SDLoc DL(Op);
5722   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5723                      DAG.getVTList(MVT::i32, MVT::Other),
5724                      Op.getOperand(0), Op.getOperand(1));
5725 }
5726
5727 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5728                                                 SelectionDAG &DAG) const {
5729   SDLoc DL(Op);
5730   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5731                      Op.getOperand(0), Op.getOperand(1));
5732 }
5733
5734 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5735   if (Op.getValueType().isVector())
5736     return LowerVectorLoad(Op, DAG);
5737
5738   assert(Op.getValueType() == MVT::i1 &&
5739          "Custom lowering only for i1 loads");
5740
5741   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5742
5743   SDLoc dl(Op);
5744   LoadSDNode *LD = cast<LoadSDNode>(Op);
5745
5746   SDValue Chain = LD->getChain();
5747   SDValue BasePtr = LD->getBasePtr();
5748   MachineMemOperand *MMO = LD->getMemOperand();
5749
5750   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5751                                  BasePtr, MVT::i8, MMO);
5752   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5753
5754   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5755   return DAG.getMergeValues(Ops, dl);
5756 }
5757
5758 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5759   if (Op.getOperand(1).getValueType().isVector())
5760     return LowerVectorStore(Op, DAG);
5761
5762   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5763          "Custom lowering only for i1 stores");
5764
5765   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5766
5767   SDLoc dl(Op);
5768   StoreSDNode *ST = cast<StoreSDNode>(Op);
5769
5770   SDValue Chain = ST->getChain();
5771   SDValue BasePtr = ST->getBasePtr();
5772   SDValue Value = ST->getValue();
5773   MachineMemOperand *MMO = ST->getMemOperand();
5774
5775   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5776   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5777 }
5778
5779 // FIXME: Remove this once the ANDI glue bug is fixed:
5780 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5781   assert(Op.getValueType() == MVT::i1 &&
5782          "Custom lowering only for i1 results");
5783
5784   SDLoc DL(Op);
5785   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5786                      Op.getOperand(0));
5787 }
5788
5789 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5790 /// possible.
5791 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5792   // Not FP? Not a fsel.
5793   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5794       !Op.getOperand(2).getValueType().isFloatingPoint())
5795     return Op;
5796
5797   // We might be able to do better than this under some circumstances, but in
5798   // general, fsel-based lowering of select is a finite-math-only optimization.
5799   // For more information, see section F.3 of the 2.06 ISA specification.
5800   if (!DAG.getTarget().Options.NoInfsFPMath ||
5801       !DAG.getTarget().Options.NoNaNsFPMath)
5802     return Op;
5803
5804   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5805
5806   EVT ResVT = Op.getValueType();
5807   EVT CmpVT = Op.getOperand(0).getValueType();
5808   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5809   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5810   SDLoc dl(Op);
5811
5812   // If the RHS of the comparison is a 0.0, we don't need to do the
5813   // subtraction at all.
5814   SDValue Sel1;
5815   if (isFloatingPointZero(RHS))
5816     switch (CC) {
5817     default: break;       // SETUO etc aren't handled by fsel.
5818     case ISD::SETNE:
5819       std::swap(TV, FV);
5820     case ISD::SETEQ:
5821       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5822         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5823       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5824       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5825         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5826       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5827                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5828     case ISD::SETULT:
5829     case ISD::SETLT:
5830       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5831     case ISD::SETOGE:
5832     case ISD::SETGE:
5833       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5834         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5835       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5836     case ISD::SETUGT:
5837     case ISD::SETGT:
5838       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5839     case ISD::SETOLE:
5840     case ISD::SETLE:
5841       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5842         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5843       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5844                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5845     }
5846
5847   SDValue Cmp;
5848   switch (CC) {
5849   default: break;       // SETUO etc aren't handled by fsel.
5850   case ISD::SETNE:
5851     std::swap(TV, FV);
5852   case ISD::SETEQ:
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     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5857     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5858       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5859     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5860                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5861   case ISD::SETULT:
5862   case ISD::SETLT:
5863     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5864     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5865       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5866     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5867   case ISD::SETOGE:
5868   case ISD::SETGE:
5869     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5870     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5871       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5872     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5873   case ISD::SETUGT:
5874   case ISD::SETGT:
5875     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5876     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5877       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5878     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5879   case ISD::SETOLE:
5880   case ISD::SETLE:
5881     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5882     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5883       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5884     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5885   }
5886   return Op;
5887 }
5888
5889 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5890                                                SelectionDAG &DAG,
5891                                                SDLoc dl) const {
5892   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5893   SDValue Src = Op.getOperand(0);
5894   if (Src.getValueType() == MVT::f32)
5895     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5896
5897   SDValue Tmp;
5898   switch (Op.getSimpleValueType().SimpleTy) {
5899   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5900   case MVT::i32:
5901     Tmp = DAG.getNode(
5902         Op.getOpcode() == ISD::FP_TO_SINT
5903             ? PPCISD::FCTIWZ
5904             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5905         dl, MVT::f64, Src);
5906     break;
5907   case MVT::i64:
5908     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5909            "i64 FP_TO_UINT is supported only with FPCVT");
5910     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5911                                                         PPCISD::FCTIDUZ,
5912                       dl, MVT::f64, Src);
5913     break;
5914   }
5915
5916   // Convert the FP value to an int value through memory.
5917   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5918     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5919   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5920   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5921   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5922
5923   // Emit a store to the stack slot.
5924   SDValue Chain;
5925   if (i32Stack) {
5926     MachineFunction &MF = DAG.getMachineFunction();
5927     MachineMemOperand *MMO =
5928       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5929     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5930     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5931               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5932   } else
5933     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5934                          MPI, false, false, 0);
5935
5936   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5937   // add in a bias.
5938   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5939     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5940                         DAG.getConstant(4, FIPtr.getValueType()));
5941     MPI = MPI.getWithOffset(4);
5942   }
5943
5944   RLI.Chain = Chain;
5945   RLI.Ptr = FIPtr;
5946   RLI.MPI = MPI;
5947 }
5948
5949 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5950                                           SDLoc dl) const {
5951   ReuseLoadInfo RLI;
5952   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5953
5954   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5955                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5956                      RLI.Ranges);
5957 }
5958
5959 // We're trying to insert a regular store, S, and then a load, L. If the
5960 // incoming value, O, is a load, we might just be able to have our load use the
5961 // address used by O. However, we don't know if anything else will store to
5962 // that address before we can load from it. To prevent this situation, we need
5963 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5964 // the same chain operand as O, we create a token factor from the chain results
5965 // of O and L, and we replace all uses of O's chain result with that token
5966 // factor (see spliceIntoChain below for this last part).
5967 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5968                                             ReuseLoadInfo &RLI,
5969                                             SelectionDAG &DAG,
5970                                             ISD::LoadExtType ET) const {
5971   SDLoc dl(Op);
5972   if (ET == ISD::NON_EXTLOAD &&
5973       (Op.getOpcode() == ISD::FP_TO_UINT ||
5974        Op.getOpcode() == ISD::FP_TO_SINT) &&
5975       isOperationLegalOrCustom(Op.getOpcode(),
5976                                Op.getOperand(0).getValueType())) {
5977
5978     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5979     return true;
5980   }
5981
5982   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5983   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5984       LD->isNonTemporal())
5985     return false;
5986   if (LD->getMemoryVT() != MemVT)
5987     return false;
5988
5989   RLI.Ptr = LD->getBasePtr();
5990   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5991     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5992            "Non-pre-inc AM on PPC?");
5993     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5994                           LD->getOffset());
5995   }
5996
5997   RLI.Chain = LD->getChain();
5998   RLI.MPI = LD->getPointerInfo();
5999   RLI.IsInvariant = LD->isInvariant();
6000   RLI.Alignment = LD->getAlignment();
6001   RLI.AAInfo = LD->getAAInfo();
6002   RLI.Ranges = LD->getRanges();
6003
6004   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6005   return true;
6006 }
6007
6008 // Given the head of the old chain, ResChain, insert a token factor containing
6009 // it and NewResChain, and make users of ResChain now be users of that token
6010 // factor.
6011 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6012                                         SDValue NewResChain,
6013                                         SelectionDAG &DAG) const {
6014   if (!ResChain)
6015     return;
6016
6017   SDLoc dl(NewResChain);
6018
6019   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6020                            NewResChain, DAG.getUNDEF(MVT::Other));
6021   assert(TF.getNode() != NewResChain.getNode() &&
6022          "A new TF really is required here");
6023
6024   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6025   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6026 }
6027
6028 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6029                                           SelectionDAG &DAG) const {
6030   SDLoc dl(Op);
6031
6032   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6033     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6034       return SDValue();
6035
6036     SDValue Value = Op.getOperand(0);
6037     // The values are now known to be -1 (false) or 1 (true). To convert this
6038     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6039     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6040     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6041   
6042     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6043     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6044                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6045   
6046     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6047
6048     if (Op.getValueType() != MVT::v4f64)
6049       Value = DAG.getNode(ISD::FP_ROUND, dl,
6050                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6051     return Value;
6052   }
6053
6054   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6055   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6056     return SDValue();
6057
6058   if (Op.getOperand(0).getValueType() == MVT::i1)
6059     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6060                        DAG.getConstantFP(1.0, Op.getValueType()),
6061                        DAG.getConstantFP(0.0, Op.getValueType()));
6062
6063   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6064          "UINT_TO_FP is supported only with FPCVT");
6065
6066   // If we have FCFIDS, then use it when converting to single-precision.
6067   // Otherwise, convert to double-precision and then round.
6068   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6069                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6070                                                             : PPCISD::FCFIDS)
6071                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6072                                                             : PPCISD::FCFID);
6073   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6074                   ? MVT::f32
6075                   : MVT::f64;
6076
6077   if (Op.getOperand(0).getValueType() == MVT::i64) {
6078     SDValue SINT = Op.getOperand(0);
6079     // When converting to single-precision, we actually need to convert
6080     // to double-precision first and then round to single-precision.
6081     // To avoid double-rounding effects during that operation, we have
6082     // to prepare the input operand.  Bits that might be truncated when
6083     // converting to double-precision are replaced by a bit that won't
6084     // be lost at this stage, but is below the single-precision rounding
6085     // position.
6086     //
6087     // However, if -enable-unsafe-fp-math is in effect, accept double
6088     // rounding to avoid the extra overhead.
6089     if (Op.getValueType() == MVT::f32 &&
6090         !Subtarget.hasFPCVT() &&
6091         !DAG.getTarget().Options.UnsafeFPMath) {
6092
6093       // Twiddle input to make sure the low 11 bits are zero.  (If this
6094       // is the case, we are guaranteed the value will fit into the 53 bit
6095       // mantissa of an IEEE double-precision value without rounding.)
6096       // If any of those low 11 bits were not zero originally, make sure
6097       // bit 12 (value 2048) is set instead, so that the final rounding
6098       // to single-precision gets the correct result.
6099       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6100                                   SINT, DAG.getConstant(2047, MVT::i64));
6101       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6102                           Round, DAG.getConstant(2047, MVT::i64));
6103       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6104       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6105                           Round, DAG.getConstant(-2048, MVT::i64));
6106
6107       // However, we cannot use that value unconditionally: if the magnitude
6108       // of the input value is small, the bit-twiddling we did above might
6109       // end up visibly changing the output.  Fortunately, in that case, we
6110       // don't need to twiddle bits since the original input will convert
6111       // exactly to double-precision floating-point already.  Therefore,
6112       // construct a conditional to use the original value if the top 11
6113       // bits are all sign-bit copies, and use the rounded value computed
6114       // above otherwise.
6115       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6116                                  SINT, DAG.getConstant(53, MVT::i32));
6117       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6118                          Cond, DAG.getConstant(1, MVT::i64));
6119       Cond = DAG.getSetCC(dl, MVT::i32,
6120                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6121
6122       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6123     }
6124
6125     ReuseLoadInfo RLI;
6126     SDValue Bits;
6127
6128     MachineFunction &MF = DAG.getMachineFunction();
6129     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6130       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6131                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6132                          RLI.Ranges);
6133       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6134     } else if (Subtarget.hasLFIWAX() &&
6135                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6136       MachineMemOperand *MMO =
6137         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6138                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6139       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6140       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6141                                      DAG.getVTList(MVT::f64, MVT::Other),
6142                                      Ops, MVT::i32, MMO);
6143       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6144     } else if (Subtarget.hasFPCVT() &&
6145                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6146       MachineMemOperand *MMO =
6147         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6148                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6149       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6150       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6151                                      DAG.getVTList(MVT::f64, MVT::Other),
6152                                      Ops, MVT::i32, MMO);
6153       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6154     } else if (((Subtarget.hasLFIWAX() &&
6155                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6156                 (Subtarget.hasFPCVT() &&
6157                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6158                SINT.getOperand(0).getValueType() == MVT::i32) {
6159       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6160       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6161
6162       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6163       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6164
6165       SDValue Store =
6166         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6167                      MachinePointerInfo::getFixedStack(FrameIdx),
6168                      false, false, 0);
6169
6170       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6171              "Expected an i32 store");
6172
6173       RLI.Ptr = FIdx;
6174       RLI.Chain = Store;
6175       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6176       RLI.Alignment = 4;
6177
6178       MachineMemOperand *MMO =
6179         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6180                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6181       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6182       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6183                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6184                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6185                                      Ops, MVT::i32, MMO);
6186     } else
6187       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6188
6189     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6190
6191     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6192       FP = DAG.getNode(ISD::FP_ROUND, dl,
6193                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6194     return FP;
6195   }
6196
6197   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6198          "Unhandled INT_TO_FP type in custom expander!");
6199   // Since we only generate this in 64-bit mode, we can take advantage of
6200   // 64-bit registers.  In particular, sign extend the input value into the
6201   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6202   // then lfd it and fcfid it.
6203   MachineFunction &MF = DAG.getMachineFunction();
6204   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6205   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6206
6207   SDValue Ld;
6208   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6209     ReuseLoadInfo RLI;
6210     bool ReusingLoad;
6211     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6212                                             DAG))) {
6213       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6214       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6215
6216       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6217                                    MachinePointerInfo::getFixedStack(FrameIdx),
6218                                    false, false, 0);
6219
6220       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6221              "Expected an i32 store");
6222
6223       RLI.Ptr = FIdx;
6224       RLI.Chain = Store;
6225       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6226       RLI.Alignment = 4;
6227     }
6228
6229     MachineMemOperand *MMO =
6230       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6231                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6232     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6233     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6234                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6235                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6236                                  Ops, MVT::i32, MMO);
6237     if (ReusingLoad)
6238       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6239   } else {
6240     assert(Subtarget.isPPC64() &&
6241            "i32->FP without LFIWAX supported only on PPC64");
6242
6243     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6244     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6245
6246     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6247                                 Op.getOperand(0));
6248
6249     // STD the extended value into the stack slot.
6250     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6251                                  MachinePointerInfo::getFixedStack(FrameIdx),
6252                                  false, false, 0);
6253
6254     // Load the value as a double.
6255     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6256                      MachinePointerInfo::getFixedStack(FrameIdx),
6257                      false, false, false, 0);
6258   }
6259
6260   // FCFID it and return it.
6261   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6262   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6263     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6264   return FP;
6265 }
6266
6267 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6268                                             SelectionDAG &DAG) const {
6269   SDLoc dl(Op);
6270   /*
6271    The rounding mode is in bits 30:31 of FPSR, and has the following
6272    settings:
6273      00 Round to nearest
6274      01 Round to 0
6275      10 Round to +inf
6276      11 Round to -inf
6277
6278   FLT_ROUNDS, on the other hand, expects the following:
6279     -1 Undefined
6280      0 Round to 0
6281      1 Round to nearest
6282      2 Round to +inf
6283      3 Round to -inf
6284
6285   To perform the conversion, we do:
6286     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6287   */
6288
6289   MachineFunction &MF = DAG.getMachineFunction();
6290   EVT VT = Op.getValueType();
6291   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6292
6293   // Save FP Control Word to register
6294   EVT NodeTys[] = {
6295     MVT::f64,    // return register
6296     MVT::Glue    // unused in this context
6297   };
6298   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6299
6300   // Save FP register to stack slot
6301   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6302   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6303   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6304                                StackSlot, MachinePointerInfo(), false, false,0);
6305
6306   // Load FP Control Word from low 32 bits of stack slot.
6307   SDValue Four = DAG.getConstant(4, PtrVT);
6308   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6309   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6310                             false, false, false, 0);
6311
6312   // Transform as necessary
6313   SDValue CWD1 =
6314     DAG.getNode(ISD::AND, dl, MVT::i32,
6315                 CWD, DAG.getConstant(3, MVT::i32));
6316   SDValue CWD2 =
6317     DAG.getNode(ISD::SRL, dl, MVT::i32,
6318                 DAG.getNode(ISD::AND, dl, MVT::i32,
6319                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6320                                         CWD, DAG.getConstant(3, MVT::i32)),
6321                             DAG.getConstant(3, MVT::i32)),
6322                 DAG.getConstant(1, MVT::i32));
6323
6324   SDValue RetVal =
6325     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6326
6327   return DAG.getNode((VT.getSizeInBits() < 16 ?
6328                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6329 }
6330
6331 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6332   EVT VT = Op.getValueType();
6333   unsigned BitWidth = VT.getSizeInBits();
6334   SDLoc dl(Op);
6335   assert(Op.getNumOperands() == 3 &&
6336          VT == Op.getOperand(1).getValueType() &&
6337          "Unexpected SHL!");
6338
6339   // Expand into a bunch of logical ops.  Note that these ops
6340   // depend on the PPC behavior for oversized shift amounts.
6341   SDValue Lo = Op.getOperand(0);
6342   SDValue Hi = Op.getOperand(1);
6343   SDValue Amt = Op.getOperand(2);
6344   EVT AmtVT = Amt.getValueType();
6345
6346   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6347                              DAG.getConstant(BitWidth, AmtVT), Amt);
6348   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6349   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6350   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6351   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6352                              DAG.getConstant(-BitWidth, AmtVT));
6353   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6354   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6355   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6356   SDValue OutOps[] = { OutLo, OutHi };
6357   return DAG.getMergeValues(OutOps, dl);
6358 }
6359
6360 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6361   EVT VT = Op.getValueType();
6362   SDLoc dl(Op);
6363   unsigned BitWidth = VT.getSizeInBits();
6364   assert(Op.getNumOperands() == 3 &&
6365          VT == Op.getOperand(1).getValueType() &&
6366          "Unexpected SRL!");
6367
6368   // Expand into a bunch of logical ops.  Note that these ops
6369   // depend on the PPC behavior for oversized shift amounts.
6370   SDValue Lo = Op.getOperand(0);
6371   SDValue Hi = Op.getOperand(1);
6372   SDValue Amt = Op.getOperand(2);
6373   EVT AmtVT = Amt.getValueType();
6374
6375   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6376                              DAG.getConstant(BitWidth, AmtVT), Amt);
6377   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6378   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6379   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6380   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6381                              DAG.getConstant(-BitWidth, AmtVT));
6382   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6383   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6384   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6385   SDValue OutOps[] = { OutLo, OutHi };
6386   return DAG.getMergeValues(OutOps, dl);
6387 }
6388
6389 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6390   SDLoc dl(Op);
6391   EVT VT = Op.getValueType();
6392   unsigned BitWidth = VT.getSizeInBits();
6393   assert(Op.getNumOperands() == 3 &&
6394          VT == Op.getOperand(1).getValueType() &&
6395          "Unexpected SRA!");
6396
6397   // Expand into a bunch of logical ops, followed by a select_cc.
6398   SDValue Lo = Op.getOperand(0);
6399   SDValue Hi = Op.getOperand(1);
6400   SDValue Amt = Op.getOperand(2);
6401   EVT AmtVT = Amt.getValueType();
6402
6403   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6404                              DAG.getConstant(BitWidth, AmtVT), Amt);
6405   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6406   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6407   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6408   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6409                              DAG.getConstant(-BitWidth, AmtVT));
6410   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6411   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6412   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6413                                   Tmp4, Tmp6, ISD::SETLE);
6414   SDValue OutOps[] = { OutLo, OutHi };
6415   return DAG.getMergeValues(OutOps, dl);
6416 }
6417
6418 //===----------------------------------------------------------------------===//
6419 // Vector related lowering.
6420 //
6421
6422 /// BuildSplatI - Build a canonical splati of Val with an element size of
6423 /// SplatSize.  Cast the result to VT.
6424 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6425                              SelectionDAG &DAG, SDLoc dl) {
6426   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6427
6428   static const EVT VTys[] = { // canonical VT to use for each size.
6429     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6430   };
6431
6432   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6433
6434   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6435   if (Val == -1)
6436     SplatSize = 1;
6437
6438   EVT CanonicalVT = VTys[SplatSize-1];
6439
6440   // Build a canonical splat for this value.
6441   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6442   SmallVector<SDValue, 8> Ops;
6443   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6444   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6445   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6446 }
6447
6448 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6449 /// specified intrinsic ID.
6450 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6451                                 SelectionDAG &DAG, SDLoc dl,
6452                                 EVT DestVT = MVT::Other) {
6453   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6454   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6455                      DAG.getConstant(IID, MVT::i32), Op);
6456 }
6457
6458 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6459 /// specified intrinsic ID.
6460 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6461                                 SelectionDAG &DAG, SDLoc dl,
6462                                 EVT DestVT = MVT::Other) {
6463   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6464   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6465                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6466 }
6467
6468 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6469 /// specified intrinsic ID.
6470 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6471                                 SDValue Op2, SelectionDAG &DAG,
6472                                 SDLoc dl, EVT DestVT = MVT::Other) {
6473   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6474   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6475                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6476 }
6477
6478
6479 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6480 /// amount.  The result has the specified value type.
6481 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6482                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6483   // Force LHS/RHS to be the right type.
6484   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6485   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6486
6487   int Ops[16];
6488   for (unsigned i = 0; i != 16; ++i)
6489     Ops[i] = i + Amt;
6490   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6491   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6492 }
6493
6494 // If this is a case we can't handle, return null and let the default
6495 // expansion code take care of it.  If we CAN select this case, and if it
6496 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6497 // this case more efficiently than a constant pool load, lower it to the
6498 // sequence of ops that should be used.
6499 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6500                                              SelectionDAG &DAG) const {
6501   SDLoc dl(Op);
6502   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6503   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6504
6505   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6506     // We first build an i32 vector, load it into a QPX register,
6507     // then convert it to a floating-point vector and compare it
6508     // to a zero vector to get the boolean result.
6509     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6510     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6511     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6512     EVT PtrVT = getPointerTy();
6513     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6514
6515     assert(BVN->getNumOperands() == 4 &&
6516       "BUILD_VECTOR for v4i1 does not have 4 operands");
6517
6518     bool IsConst = true;
6519     for (unsigned i = 0; i < 4; ++i) {
6520       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6521       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6522         IsConst = false;
6523         break;
6524       }
6525     }
6526
6527     if (IsConst) {
6528       Constant *One =
6529         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6530       Constant *NegOne =
6531         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6532
6533       SmallVector<Constant*, 4> CV(4, NegOne);
6534       for (unsigned i = 0; i < 4; ++i) {
6535         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6536           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6537         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6538                    getConstantIntValue()->isZero())
6539           continue;
6540         else
6541           CV[i] = One;
6542       }
6543
6544       Constant *CP = ConstantVector::get(CV);
6545       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6546                       16 /* alignment */);
6547  
6548       SmallVector<SDValue, 2> Ops;
6549       Ops.push_back(DAG.getEntryNode());
6550       Ops.push_back(CPIdx);
6551
6552       SmallVector<EVT, 2> ValueVTs;
6553       ValueVTs.push_back(MVT::v4i1);
6554       ValueVTs.push_back(MVT::Other); // chain
6555       SDVTList VTs = DAG.getVTList(ValueVTs);
6556
6557       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6558         dl, VTs, Ops, MVT::v4f32,
6559         MachinePointerInfo::getConstantPool());
6560     }
6561
6562     SmallVector<SDValue, 4> Stores;
6563     for (unsigned i = 0; i < 4; ++i) {
6564       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6565
6566       unsigned Offset = 4*i;
6567       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6568       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6569
6570       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6571       if (StoreSize > 4) {
6572         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6573                                            BVN->getOperand(i), Idx,
6574                                            PtrInfo.getWithOffset(Offset),
6575                                            MVT::i32, false, false, 0));
6576       } else {
6577         SDValue StoreValue = BVN->getOperand(i);
6578         if (StoreSize < 4)
6579           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6580
6581         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6582                                       StoreValue, Idx,
6583                                       PtrInfo.getWithOffset(Offset),
6584                                       false, false, 0));
6585       }
6586     }
6587
6588     SDValue StoreChain;
6589     if (!Stores.empty())
6590       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6591     else
6592       StoreChain = DAG.getEntryNode();
6593
6594     // Now load from v4i32 into the QPX register; this will extend it to
6595     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6596     // is typed as v4f64 because the QPX register integer states are not
6597     // explicitly represented.
6598
6599     SmallVector<SDValue, 2> Ops;
6600     Ops.push_back(StoreChain);
6601     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6602     Ops.push_back(FIdx);
6603
6604     SmallVector<EVT, 2> ValueVTs;
6605     ValueVTs.push_back(MVT::v4f64);
6606     ValueVTs.push_back(MVT::Other); // chain
6607     SDVTList VTs = DAG.getVTList(ValueVTs);
6608
6609     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6610       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6611     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6612       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6613       LoadedVect);
6614
6615     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6616     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6617                           FPZeros, FPZeros, FPZeros, FPZeros);
6618
6619     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6620   }
6621
6622   // All other QPX vectors are handled by generic code.
6623   if (Subtarget.hasQPX())
6624     return SDValue();
6625
6626   // Check if this is a splat of a constant value.
6627   APInt APSplatBits, APSplatUndef;
6628   unsigned SplatBitSize;
6629   bool HasAnyUndefs;
6630   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6631                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6632     return SDValue();
6633
6634   unsigned SplatBits = APSplatBits.getZExtValue();
6635   unsigned SplatUndef = APSplatUndef.getZExtValue();
6636   unsigned SplatSize = SplatBitSize / 8;
6637
6638   // First, handle single instruction cases.
6639
6640   // All zeros?
6641   if (SplatBits == 0) {
6642     // Canonicalize all zero vectors to be v4i32.
6643     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6644       SDValue Z = DAG.getConstant(0, MVT::i32);
6645       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6646       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6647     }
6648     return Op;
6649   }
6650
6651   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6652   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6653                     (32-SplatBitSize));
6654   if (SextVal >= -16 && SextVal <= 15)
6655     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6656
6657
6658   // Two instruction sequences.
6659
6660   // If this value is in the range [-32,30] and is even, use:
6661   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6662   // If this value is in the range [17,31] and is odd, use:
6663   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6664   // If this value is in the range [-31,-17] and is odd, use:
6665   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6666   // Note the last two are three-instruction sequences.
6667   if (SextVal >= -32 && SextVal <= 31) {
6668     // To avoid having these optimizations undone by constant folding,
6669     // we convert to a pseudo that will be expanded later into one of
6670     // the above forms.
6671     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6672     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6673               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6674     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6675     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6676     if (VT == Op.getValueType())
6677       return RetVal;
6678     else
6679       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6680   }
6681
6682   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6683   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6684   // for fneg/fabs.
6685   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6686     // Make -1 and vspltisw -1:
6687     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6688
6689     // Make the VSLW intrinsic, computing 0x8000_0000.
6690     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6691                                    OnesV, DAG, dl);
6692
6693     // xor by OnesV to invert it.
6694     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6695     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6696   }
6697
6698   // The remaining cases assume either big endian element order or
6699   // a splat-size that equates to the element size of the vector
6700   // to be built.  An example that doesn't work for little endian is
6701   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6702   // and a vector element size of 16 bits.  The code below will
6703   // produce the vector in big endian element order, which for little
6704   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6705
6706   // For now, just avoid these optimizations in that case.
6707   // FIXME: Develop correct optimizations for LE with mismatched
6708   // splat and element sizes.
6709
6710   if (Subtarget.isLittleEndian() &&
6711       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6712     return SDValue();
6713
6714   // Check to see if this is a wide variety of vsplti*, binop self cases.
6715   static const signed char SplatCsts[] = {
6716     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6717     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6718   };
6719
6720   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6721     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6722     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6723     int i = SplatCsts[idx];
6724
6725     // Figure out what shift amount will be used by altivec if shifted by i in
6726     // this splat size.
6727     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6728
6729     // vsplti + shl self.
6730     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6731       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6732       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6733         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6734         Intrinsic::ppc_altivec_vslw
6735       };
6736       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6737       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6738     }
6739
6740     // vsplti + srl self.
6741     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6742       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6743       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6744         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6745         Intrinsic::ppc_altivec_vsrw
6746       };
6747       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6748       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6749     }
6750
6751     // vsplti + sra self.
6752     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6753       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6754       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6755         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6756         Intrinsic::ppc_altivec_vsraw
6757       };
6758       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6759       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6760     }
6761
6762     // vsplti + rol self.
6763     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6764                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6765       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6766       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6767         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6768         Intrinsic::ppc_altivec_vrlw
6769       };
6770       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6771       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6772     }
6773
6774     // t = vsplti c, result = vsldoi t, t, 1
6775     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6776       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6777       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6778     }
6779     // t = vsplti c, result = vsldoi t, t, 2
6780     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6781       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6782       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6783     }
6784     // t = vsplti c, result = vsldoi t, t, 3
6785     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6786       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6787       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6788     }
6789   }
6790
6791   return SDValue();
6792 }
6793
6794 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6795 /// the specified operations to build the shuffle.
6796 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6797                                       SDValue RHS, SelectionDAG &DAG,
6798                                       SDLoc dl) {
6799   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6800   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6801   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6802
6803   enum {
6804     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6805     OP_VMRGHW,
6806     OP_VMRGLW,
6807     OP_VSPLTISW0,
6808     OP_VSPLTISW1,
6809     OP_VSPLTISW2,
6810     OP_VSPLTISW3,
6811     OP_VSLDOI4,
6812     OP_VSLDOI8,
6813     OP_VSLDOI12
6814   };
6815
6816   if (OpNum == OP_COPY) {
6817     if (LHSID == (1*9+2)*9+3) return LHS;
6818     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6819     return RHS;
6820   }
6821
6822   SDValue OpLHS, OpRHS;
6823   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6824   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6825
6826   int ShufIdxs[16];
6827   switch (OpNum) {
6828   default: llvm_unreachable("Unknown i32 permute!");
6829   case OP_VMRGHW:
6830     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6831     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6832     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6833     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6834     break;
6835   case OP_VMRGLW:
6836     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6837     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6838     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6839     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6840     break;
6841   case OP_VSPLTISW0:
6842     for (unsigned i = 0; i != 16; ++i)
6843       ShufIdxs[i] = (i&3)+0;
6844     break;
6845   case OP_VSPLTISW1:
6846     for (unsigned i = 0; i != 16; ++i)
6847       ShufIdxs[i] = (i&3)+4;
6848     break;
6849   case OP_VSPLTISW2:
6850     for (unsigned i = 0; i != 16; ++i)
6851       ShufIdxs[i] = (i&3)+8;
6852     break;
6853   case OP_VSPLTISW3:
6854     for (unsigned i = 0; i != 16; ++i)
6855       ShufIdxs[i] = (i&3)+12;
6856     break;
6857   case OP_VSLDOI4:
6858     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6859   case OP_VSLDOI8:
6860     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6861   case OP_VSLDOI12:
6862     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6863   }
6864   EVT VT = OpLHS.getValueType();
6865   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6866   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6867   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6868   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6869 }
6870
6871 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6872 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6873 /// return the code it can be lowered into.  Worst case, it can always be
6874 /// lowered into a vperm.
6875 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6876                                                SelectionDAG &DAG) const {
6877   SDLoc dl(Op);
6878   SDValue V1 = Op.getOperand(0);
6879   SDValue V2 = Op.getOperand(1);
6880   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6881   EVT VT = Op.getValueType();
6882   bool isLittleEndian = Subtarget.isLittleEndian();
6883
6884   if (Subtarget.hasQPX()) {
6885     if (VT.getVectorNumElements() != 4)
6886       return SDValue();
6887
6888     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6889
6890     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6891     if (AlignIdx != -1) {
6892       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6893                          DAG.getConstant(AlignIdx, MVT::i32));
6894     } else if (SVOp->isSplat()) {
6895       int SplatIdx = SVOp->getSplatIndex();
6896       if (SplatIdx >= 4) {
6897         std::swap(V1, V2);
6898         SplatIdx -= 4;
6899       }
6900
6901       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6902       // nothing to do.
6903
6904       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6905                          DAG.getConstant(SplatIdx, MVT::i32));
6906     }
6907
6908     // Lower this into a qvgpci/qvfperm pair.
6909
6910     // Compute the qvgpci literal
6911     unsigned idx = 0;
6912     for (unsigned i = 0; i < 4; ++i) {
6913       int m = SVOp->getMaskElt(i);
6914       unsigned mm = m >= 0 ? (unsigned) m : i;
6915       idx |= mm << (3-i)*3;
6916     }
6917
6918     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6919                              DAG.getConstant(idx, MVT::i32));
6920     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6921   }
6922
6923   // Cases that are handled by instructions that take permute immediates
6924   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6925   // selected by the instruction selector.
6926   if (V2.getOpcode() == ISD::UNDEF) {
6927     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6928         PPC::isSplatShuffleMask(SVOp, 2) ||
6929         PPC::isSplatShuffleMask(SVOp, 4) ||
6930         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6931         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6932         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6933         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6934         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6935         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6936         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6937         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6938         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6939       return Op;
6940     }
6941   }
6942
6943   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6944   // and produce a fixed permutation.  If any of these match, do not lower to
6945   // VPERM.
6946   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6947   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6948       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6949       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6950       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6951       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6952       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6953       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6954       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6955       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6956     return Op;
6957
6958   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6959   // perfect shuffle table to emit an optimal matching sequence.
6960   ArrayRef<int> PermMask = SVOp->getMask();
6961
6962   unsigned PFIndexes[4];
6963   bool isFourElementShuffle = true;
6964   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6965     unsigned EltNo = 8;   // Start out undef.
6966     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6967       if (PermMask[i*4+j] < 0)
6968         continue;   // Undef, ignore it.
6969
6970       unsigned ByteSource = PermMask[i*4+j];
6971       if ((ByteSource & 3) != j) {
6972         isFourElementShuffle = false;
6973         break;
6974       }
6975
6976       if (EltNo == 8) {
6977         EltNo = ByteSource/4;
6978       } else if (EltNo != ByteSource/4) {
6979         isFourElementShuffle = false;
6980         break;
6981       }
6982     }
6983     PFIndexes[i] = EltNo;
6984   }
6985
6986   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6987   // perfect shuffle vector to determine if it is cost effective to do this as
6988   // discrete instructions, or whether we should use a vperm.
6989   // For now, we skip this for little endian until such time as we have a
6990   // little-endian perfect shuffle table.
6991   if (isFourElementShuffle && !isLittleEndian) {
6992     // Compute the index in the perfect shuffle table.
6993     unsigned PFTableIndex =
6994       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6995
6996     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6997     unsigned Cost  = (PFEntry >> 30);
6998
6999     // Determining when to avoid vperm is tricky.  Many things affect the cost
7000     // of vperm, particularly how many times the perm mask needs to be computed.
7001     // For example, if the perm mask can be hoisted out of a loop or is already
7002     // used (perhaps because there are multiple permutes with the same shuffle
7003     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7004     // the loop requires an extra register.
7005     //
7006     // As a compromise, we only emit discrete instructions if the shuffle can be
7007     // generated in 3 or fewer operations.  When we have loop information
7008     // available, if this block is within a loop, we should avoid using vperm
7009     // for 3-operation perms and use a constant pool load instead.
7010     if (Cost < 3)
7011       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7012   }
7013
7014   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7015   // vector that will get spilled to the constant pool.
7016   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7017
7018   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7019   // that it is in input element units, not in bytes.  Convert now.
7020
7021   // For little endian, the order of the input vectors is reversed, and
7022   // the permutation mask is complemented with respect to 31.  This is
7023   // necessary to produce proper semantics with the big-endian-biased vperm
7024   // instruction.
7025   EVT EltVT = V1.getValueType().getVectorElementType();
7026   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7027
7028   SmallVector<SDValue, 16> ResultMask;
7029   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7030     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7031
7032     for (unsigned j = 0; j != BytesPerElement; ++j)
7033       if (isLittleEndian)
7034         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7035                                              MVT::i32));
7036       else
7037         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7038                                              MVT::i32));
7039   }
7040
7041   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7042                                   ResultMask);
7043   if (isLittleEndian)
7044     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7045                        V2, V1, VPermMask);
7046   else
7047     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7048                        V1, V2, VPermMask);
7049 }
7050
7051 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7052 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7053 /// information about the intrinsic.
7054 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7055                                   bool &isDot) {
7056   unsigned IntrinsicID =
7057     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7058   CompareOpc = -1;
7059   isDot = false;
7060   switch (IntrinsicID) {
7061   default: return false;
7062     // Comparison predicates.
7063   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7064   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7065   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7066   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7067   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7068   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7069   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7070   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7071   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7072   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7073   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7074   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7075   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7076
7077     // Normal Comparisons.
7078   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7079   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7080   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7081   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7082   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7083   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7084   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7085   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7086   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7087   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7088   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7089   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7090   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7091   }
7092   return true;
7093 }
7094
7095 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7096 /// lower, do it, otherwise return null.
7097 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7098                                                    SelectionDAG &DAG) const {
7099   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7100   // opcode number of the comparison.
7101   SDLoc dl(Op);
7102   int CompareOpc;
7103   bool isDot;
7104   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
7105     return SDValue();    // Don't custom lower most intrinsics.
7106
7107   // If this is a non-dot comparison, make the VCMP node and we are done.
7108   if (!isDot) {
7109     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7110                               Op.getOperand(1), Op.getOperand(2),
7111                               DAG.getConstant(CompareOpc, MVT::i32));
7112     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7113   }
7114
7115   // Create the PPCISD altivec 'dot' comparison node.
7116   SDValue Ops[] = {
7117     Op.getOperand(2),  // LHS
7118     Op.getOperand(3),  // RHS
7119     DAG.getConstant(CompareOpc, MVT::i32)
7120   };
7121   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7122   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7123
7124   // Now that we have the comparison, emit a copy from the CR to a GPR.
7125   // This is flagged to the above dot comparison.
7126   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7127                                 DAG.getRegister(PPC::CR6, MVT::i32),
7128                                 CompNode.getValue(1));
7129
7130   // Unpack the result based on how the target uses it.
7131   unsigned BitNo;   // Bit # of CR6.
7132   bool InvertBit;   // Invert result?
7133   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7134   default:  // Can't happen, don't crash on invalid number though.
7135   case 0:   // Return the value of the EQ bit of CR6.
7136     BitNo = 0; InvertBit = false;
7137     break;
7138   case 1:   // Return the inverted value of the EQ bit of CR6.
7139     BitNo = 0; InvertBit = true;
7140     break;
7141   case 2:   // Return the value of the LT bit of CR6.
7142     BitNo = 2; InvertBit = false;
7143     break;
7144   case 3:   // Return the inverted value of the LT bit of CR6.
7145     BitNo = 2; InvertBit = true;
7146     break;
7147   }
7148
7149   // Shift the bit into the low position.
7150   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7151                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7152   // Isolate the bit.
7153   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7154                       DAG.getConstant(1, MVT::i32));
7155
7156   // If we are supposed to, toggle the bit.
7157   if (InvertBit)
7158     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7159                         DAG.getConstant(1, MVT::i32));
7160   return Flags;
7161 }
7162
7163 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7164                                                   SelectionDAG &DAG) const {
7165   SDLoc dl(Op);
7166   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7167   // instructions), but for smaller types, we need to first extend up to v2i32
7168   // before doing going farther.
7169   if (Op.getValueType() == MVT::v2i64) {
7170     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7171     if (ExtVT != MVT::v2i32) {
7172       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7173       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7174                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7175                                         ExtVT.getVectorElementType(), 4)));
7176       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7177       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7178                        DAG.getValueType(MVT::v2i32));
7179     }
7180
7181     return Op;
7182   }
7183
7184   return SDValue();
7185 }
7186
7187 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7188                                                    SelectionDAG &DAG) const {
7189   SDLoc dl(Op);
7190   // Create a stack slot that is 16-byte aligned.
7191   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7192   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7193   EVT PtrVT = getPointerTy();
7194   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7195
7196   // Store the input value into Value#0 of the stack slot.
7197   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7198                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7199                                false, false, 0);
7200   // Load it out.
7201   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7202                      false, false, false, 0);
7203 }
7204
7205 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7206                                                    SelectionDAG &DAG) const {
7207   SDLoc dl(Op);
7208   SDNode *N = Op.getNode();
7209
7210   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7211          "Unknown extract_vector_elt type");
7212
7213   SDValue Value = N->getOperand(0);
7214
7215   // The first part of this is like the store lowering except that we don't
7216   // need to track the chain.
7217
7218   // The values are now known to be -1 (false) or 1 (true). To convert this
7219   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7220   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7221   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7222
7223   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7224   // understand how to form the extending load.
7225   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7226   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7227                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7228
7229   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7230
7231   // Now convert to an integer and store.
7232   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7233     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7234     Value);
7235
7236   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7237   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7238   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7239   EVT PtrVT = getPointerTy();
7240   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7241
7242   SDValue StoreChain = DAG.getEntryNode();
7243   SmallVector<SDValue, 2> Ops;
7244   Ops.push_back(StoreChain);
7245   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7246   Ops.push_back(Value);
7247   Ops.push_back(FIdx);
7248
7249   SmallVector<EVT, 2> ValueVTs;
7250   ValueVTs.push_back(MVT::Other); // chain
7251   SDVTList VTs = DAG.getVTList(ValueVTs);
7252
7253   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7254     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7255
7256   // Extract the value requested.
7257   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7258   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7259   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7260
7261   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7262                                PtrInfo.getWithOffset(Offset),
7263                                false, false, false, 0);
7264
7265   if (!Subtarget.useCRBits())
7266     return IntVal;
7267
7268   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7269 }
7270
7271 /// Lowering for QPX v4i1 loads
7272 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7273                                            SelectionDAG &DAG) const {
7274   SDLoc dl(Op);
7275   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7276   SDValue LoadChain = LN->getChain();
7277   SDValue BasePtr = LN->getBasePtr();
7278
7279   if (Op.getValueType() == MVT::v4f64 ||
7280       Op.getValueType() == MVT::v4f32) {
7281     EVT MemVT = LN->getMemoryVT();
7282     unsigned Alignment = LN->getAlignment();
7283
7284     // If this load is properly aligned, then it is legal.
7285     if (Alignment >= MemVT.getStoreSize())
7286       return Op;
7287
7288     EVT ScalarVT = Op.getValueType().getScalarType(),
7289         ScalarMemVT = MemVT.getScalarType();
7290     unsigned Stride = ScalarMemVT.getStoreSize();
7291
7292     SmallVector<SDValue, 8> Vals, LoadChains;
7293     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7294       SDValue Load;
7295       if (ScalarVT != ScalarMemVT)
7296         Load =
7297           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7298                          BasePtr,
7299                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7300                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7301                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7302                          LN->getAAInfo());
7303       else
7304         Load =
7305           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7306                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7307                        LN->isVolatile(), LN->isNonTemporal(),
7308                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7309                        LN->getAAInfo());
7310
7311       if (Idx == 0 && LN->isIndexed()) {
7312         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7313                "Unknown addressing mode on vector load");
7314         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7315                                   LN->getAddressingMode());
7316       }
7317
7318       Vals.push_back(Load);
7319       LoadChains.push_back(Load.getValue(1));
7320
7321       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7322                             DAG.getConstant(Stride, BasePtr.getValueType()));
7323     }
7324
7325     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7326     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7327                                    Op.getValueType(), Vals);
7328
7329     if (LN->isIndexed()) {
7330       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7331       return DAG.getMergeValues(RetOps, dl);
7332     }
7333
7334     SDValue RetOps[] = { Value, TF };
7335     return DAG.getMergeValues(RetOps, dl);
7336   }
7337
7338   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7339   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7340
7341   // To lower v4i1 from a byte array, we load the byte elements of the
7342   // vector and then reuse the BUILD_VECTOR logic.
7343
7344   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7345   for (unsigned i = 0; i < 4; ++i) {
7346     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7347     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7348
7349     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7350                         dl, MVT::i32, LoadChain, Idx,
7351                         LN->getPointerInfo().getWithOffset(i),
7352                         MVT::i8 /* memory type */,
7353                         LN->isVolatile(), LN->isNonTemporal(),
7354                         LN->isInvariant(),
7355                         1 /* alignment */, LN->getAAInfo()));
7356     VectElmtChains.push_back(VectElmts[i].getValue(1));
7357   }
7358
7359   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7360   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7361
7362   SDValue RVals[] = { Value, LoadChain };
7363   return DAG.getMergeValues(RVals, dl);
7364 }
7365
7366 /// Lowering for QPX v4i1 stores
7367 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7368                                             SelectionDAG &DAG) const {
7369   SDLoc dl(Op);
7370   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7371   SDValue StoreChain = SN->getChain();
7372   SDValue BasePtr = SN->getBasePtr();
7373   SDValue Value = SN->getValue();
7374
7375   if (Value.getValueType() == MVT::v4f64 ||
7376       Value.getValueType() == MVT::v4f32) {
7377     EVT MemVT = SN->getMemoryVT();
7378     unsigned Alignment = SN->getAlignment();
7379
7380     // If this store is properly aligned, then it is legal.
7381     if (Alignment >= MemVT.getStoreSize())
7382       return Op;
7383
7384     EVT ScalarVT = Value.getValueType().getScalarType(),
7385         ScalarMemVT = MemVT.getScalarType();
7386     unsigned Stride = ScalarMemVT.getStoreSize();
7387
7388     SmallVector<SDValue, 8> Stores;
7389     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7390       SDValue Ex =
7391         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7392                     DAG.getConstant(Idx, getVectorIdxTy()));
7393       SDValue Store;
7394       if (ScalarVT != ScalarMemVT)
7395         Store =
7396           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7397                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7398                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7399                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7400       else
7401         Store =
7402           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7403                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7404                        SN->isVolatile(), SN->isNonTemporal(),
7405                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7406
7407       if (Idx == 0 && SN->isIndexed()) {
7408         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7409                "Unknown addressing mode on vector store");
7410         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7411                                     SN->getAddressingMode());
7412       }
7413
7414       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7415                             DAG.getConstant(Stride, BasePtr.getValueType()));
7416       Stores.push_back(Store);
7417     }
7418
7419     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7420
7421     if (SN->isIndexed()) {
7422       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7423       return DAG.getMergeValues(RetOps, dl);
7424     }
7425
7426     return TF;
7427   }
7428
7429   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7430   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7431
7432   // The values are now known to be -1 (false) or 1 (true). To convert this
7433   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7434   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7435   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7436
7437   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7438   // understand how to form the extending load.
7439   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7440   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7441                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7442
7443   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7444
7445   // Now convert to an integer and store.
7446   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7447     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7448     Value);
7449
7450   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7451   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7452   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7453   EVT PtrVT = getPointerTy();
7454   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7455
7456   SmallVector<SDValue, 2> Ops;
7457   Ops.push_back(StoreChain);
7458   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7459   Ops.push_back(Value);
7460   Ops.push_back(FIdx);
7461
7462   SmallVector<EVT, 2> ValueVTs;
7463   ValueVTs.push_back(MVT::Other); // chain
7464   SDVTList VTs = DAG.getVTList(ValueVTs);
7465
7466   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7467     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7468
7469   // Move data into the byte array.
7470   SmallVector<SDValue, 4> Loads, LoadChains;
7471   for (unsigned i = 0; i < 4; ++i) {
7472     unsigned Offset = 4*i;
7473     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7474     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7475
7476     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7477                                    PtrInfo.getWithOffset(Offset),
7478                                    false, false, false, 0));
7479     LoadChains.push_back(Loads[i].getValue(1));
7480   }
7481
7482   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7483
7484   SmallVector<SDValue, 4> Stores;
7485   for (unsigned i = 0; i < 4; ++i) {
7486     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7487     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7488
7489     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7490                                        SN->getPointerInfo().getWithOffset(i),
7491                                        MVT::i8 /* memory type */,
7492                                        SN->isNonTemporal(), SN->isVolatile(), 
7493                                        1 /* alignment */, SN->getAAInfo()));
7494   }
7495
7496   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7497
7498   return StoreChain;
7499 }
7500
7501 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7502   SDLoc dl(Op);
7503   if (Op.getValueType() == MVT::v4i32) {
7504     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7505
7506     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7507     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7508
7509     SDValue RHSSwap =   // = vrlw RHS, 16
7510       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7511
7512     // Shrinkify inputs to v8i16.
7513     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7514     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7515     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7516
7517     // Low parts multiplied together, generating 32-bit results (we ignore the
7518     // top parts).
7519     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7520                                         LHS, RHS, DAG, dl, MVT::v4i32);
7521
7522     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7523                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7524     // Shift the high parts up 16 bits.
7525     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7526                               Neg16, DAG, dl);
7527     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7528   } else if (Op.getValueType() == MVT::v8i16) {
7529     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7530
7531     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7532
7533     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7534                             LHS, RHS, Zero, DAG, dl);
7535   } else if (Op.getValueType() == MVT::v16i8) {
7536     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7537     bool isLittleEndian = Subtarget.isLittleEndian();
7538
7539     // Multiply the even 8-bit parts, producing 16-bit sums.
7540     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7541                                            LHS, RHS, DAG, dl, MVT::v8i16);
7542     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7543
7544     // Multiply the odd 8-bit parts, producing 16-bit sums.
7545     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7546                                           LHS, RHS, DAG, dl, MVT::v8i16);
7547     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7548
7549     // Merge the results together.  Because vmuleub and vmuloub are
7550     // instructions with a big-endian bias, we must reverse the
7551     // element numbering and reverse the meaning of "odd" and "even"
7552     // when generating little endian code.
7553     int Ops[16];
7554     for (unsigned i = 0; i != 8; ++i) {
7555       if (isLittleEndian) {
7556         Ops[i*2  ] = 2*i;
7557         Ops[i*2+1] = 2*i+16;
7558       } else {
7559         Ops[i*2  ] = 2*i+1;
7560         Ops[i*2+1] = 2*i+1+16;
7561       }
7562     }
7563     if (isLittleEndian)
7564       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7565     else
7566       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7567   } else {
7568     llvm_unreachable("Unknown mul to lower!");
7569   }
7570 }
7571
7572 /// LowerOperation - Provide custom lowering hooks for some operations.
7573 ///
7574 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7575   switch (Op.getOpcode()) {
7576   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7577   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7578   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7579   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7580   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7581   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7582   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7583   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7584   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7585   case ISD::VASTART:
7586     return LowerVASTART(Op, DAG, Subtarget);
7587
7588   case ISD::VAARG:
7589     return LowerVAARG(Op, DAG, Subtarget);
7590
7591   case ISD::VACOPY:
7592     return LowerVACOPY(Op, DAG, Subtarget);
7593
7594   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7595   case ISD::DYNAMIC_STACKALLOC:
7596     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7597
7598   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7599   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7600
7601   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7602   case ISD::STORE:              return LowerSTORE(Op, DAG);
7603   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7604   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7605   case ISD::FP_TO_UINT:
7606   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7607                                                       SDLoc(Op));
7608   case ISD::UINT_TO_FP:
7609   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7610   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7611
7612   // Lower 64-bit shifts.
7613   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7614   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7615   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7616
7617   // Vector-related lowering.
7618   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7619   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7620   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7621   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7622   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7623   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7624   case ISD::MUL:                return LowerMUL(Op, DAG);
7625
7626   // For counter-based loop handling.
7627   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7628
7629   // Frame & Return address.
7630   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7631   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7632   }
7633 }
7634
7635 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7636                                            SmallVectorImpl<SDValue>&Results,
7637                                            SelectionDAG &DAG) const {
7638   SDLoc dl(N);
7639   switch (N->getOpcode()) {
7640   default:
7641     llvm_unreachable("Do not know how to custom type legalize this operation!");
7642   case ISD::READCYCLECOUNTER: {
7643     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7644     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7645
7646     Results.push_back(RTB);
7647     Results.push_back(RTB.getValue(1));
7648     Results.push_back(RTB.getValue(2));
7649     break;
7650   }
7651   case ISD::INTRINSIC_W_CHAIN: {
7652     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7653         Intrinsic::ppc_is_decremented_ctr_nonzero)
7654       break;
7655
7656     assert(N->getValueType(0) == MVT::i1 &&
7657            "Unexpected result type for CTR decrement intrinsic");
7658     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7659     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7660     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7661                                  N->getOperand(1)); 
7662
7663     Results.push_back(NewInt);
7664     Results.push_back(NewInt.getValue(1));
7665     break;
7666   }
7667   case ISD::VAARG: {
7668     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7669       return;
7670
7671     EVT VT = N->getValueType(0);
7672
7673     if (VT == MVT::i64) {
7674       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7675
7676       Results.push_back(NewNode);
7677       Results.push_back(NewNode.getValue(1));
7678     }
7679     return;
7680   }
7681   case ISD::FP_ROUND_INREG: {
7682     assert(N->getValueType(0) == MVT::ppcf128);
7683     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7684     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7685                              MVT::f64, N->getOperand(0),
7686                              DAG.getIntPtrConstant(0));
7687     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7688                              MVT::f64, N->getOperand(0),
7689                              DAG.getIntPtrConstant(1));
7690
7691     // Add the two halves of the long double in round-to-zero mode.
7692     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7693
7694     // We know the low half is about to be thrown away, so just use something
7695     // convenient.
7696     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7697                                 FPreg, FPreg));
7698     return;
7699   }
7700   case ISD::FP_TO_SINT:
7701     // LowerFP_TO_INT() can only handle f32 and f64.
7702     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7703       return;
7704     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7705     return;
7706   }
7707 }
7708
7709
7710 //===----------------------------------------------------------------------===//
7711 //  Other Lowering Code
7712 //===----------------------------------------------------------------------===//
7713
7714 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7715   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7716   Function *Func = Intrinsic::getDeclaration(M, Id);
7717   return Builder.CreateCall(Func);
7718 }
7719
7720 // The mappings for emitLeading/TrailingFence is taken from
7721 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7722 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7723                                          AtomicOrdering Ord, bool IsStore,
7724                                          bool IsLoad) const {
7725   if (Ord == SequentiallyConsistent)
7726     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7727   else if (isAtLeastRelease(Ord))
7728     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7729   else
7730     return nullptr;
7731 }
7732
7733 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7734                                           AtomicOrdering Ord, bool IsStore,
7735                                           bool IsLoad) const {
7736   if (IsLoad && isAtLeastAcquire(Ord))
7737     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7738   // FIXME: this is too conservative, a dependent branch + isync is enough.
7739   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7740   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7741   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7742   else
7743     return nullptr;
7744 }
7745
7746 MachineBasicBlock *
7747 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7748                                     bool is64bit, unsigned BinOpcode) const {
7749   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7750   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7751
7752   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7753   MachineFunction *F = BB->getParent();
7754   MachineFunction::iterator It = BB;
7755   ++It;
7756
7757   unsigned dest = MI->getOperand(0).getReg();
7758   unsigned ptrA = MI->getOperand(1).getReg();
7759   unsigned ptrB = MI->getOperand(2).getReg();
7760   unsigned incr = MI->getOperand(3).getReg();
7761   DebugLoc dl = MI->getDebugLoc();
7762
7763   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7764   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7765   F->insert(It, loopMBB);
7766   F->insert(It, exitMBB);
7767   exitMBB->splice(exitMBB->begin(), BB,
7768                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7769   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7770
7771   MachineRegisterInfo &RegInfo = F->getRegInfo();
7772   unsigned TmpReg = (!BinOpcode) ? incr :
7773     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
7774                                            : &PPC::GPRCRegClass);
7775
7776   //  thisMBB:
7777   //   ...
7778   //   fallthrough --> loopMBB
7779   BB->addSuccessor(loopMBB);
7780
7781   //  loopMBB:
7782   //   l[wd]arx dest, ptr
7783   //   add r0, dest, incr
7784   //   st[wd]cx. r0, ptr
7785   //   bne- loopMBB
7786   //   fallthrough --> exitMBB
7787   BB = loopMBB;
7788   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7789     .addReg(ptrA).addReg(ptrB);
7790   if (BinOpcode)
7791     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7792   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7793     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7794   BuildMI(BB, dl, TII->get(PPC::BCC))
7795     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7796   BB->addSuccessor(loopMBB);
7797   BB->addSuccessor(exitMBB);
7798
7799   //  exitMBB:
7800   //   ...
7801   BB = exitMBB;
7802   return BB;
7803 }
7804
7805 MachineBasicBlock *
7806 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7807                                             MachineBasicBlock *BB,
7808                                             bool is8bit,    // operation
7809                                             unsigned BinOpcode) const {
7810   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7811   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7812   // In 64 bit mode we have to use 64 bits for addresses, even though the
7813   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7814   // registers without caring whether they're 32 or 64, but here we're
7815   // doing actual arithmetic on the addresses.
7816   bool is64bit = Subtarget.isPPC64();
7817   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7818
7819   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7820   MachineFunction *F = BB->getParent();
7821   MachineFunction::iterator It = BB;
7822   ++It;
7823
7824   unsigned dest = MI->getOperand(0).getReg();
7825   unsigned ptrA = MI->getOperand(1).getReg();
7826   unsigned ptrB = MI->getOperand(2).getReg();
7827   unsigned incr = MI->getOperand(3).getReg();
7828   DebugLoc dl = MI->getDebugLoc();
7829
7830   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7831   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7832   F->insert(It, loopMBB);
7833   F->insert(It, exitMBB);
7834   exitMBB->splice(exitMBB->begin(), BB,
7835                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7836   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7837
7838   MachineRegisterInfo &RegInfo = F->getRegInfo();
7839   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7840                                           : &PPC::GPRCRegClass;
7841   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7842   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7843   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7844   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7845   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7846   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7847   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7848   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7849   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7850   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7851   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7852   unsigned Ptr1Reg;
7853   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7854
7855   //  thisMBB:
7856   //   ...
7857   //   fallthrough --> loopMBB
7858   BB->addSuccessor(loopMBB);
7859
7860   // The 4-byte load must be aligned, while a char or short may be
7861   // anywhere in the word.  Hence all this nasty bookkeeping code.
7862   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7863   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7864   //   xori shift, shift1, 24 [16]
7865   //   rlwinm ptr, ptr1, 0, 0, 29
7866   //   slw incr2, incr, shift
7867   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7868   //   slw mask, mask2, shift
7869   //  loopMBB:
7870   //   lwarx tmpDest, ptr
7871   //   add tmp, tmpDest, incr2
7872   //   andc tmp2, tmpDest, mask
7873   //   and tmp3, tmp, mask
7874   //   or tmp4, tmp3, tmp2
7875   //   stwcx. tmp4, ptr
7876   //   bne- loopMBB
7877   //   fallthrough --> exitMBB
7878   //   srw dest, tmpDest, shift
7879   if (ptrA != ZeroReg) {
7880     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7881     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7882       .addReg(ptrA).addReg(ptrB);
7883   } else {
7884     Ptr1Reg = ptrB;
7885   }
7886   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7887       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7888   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7889       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7890   if (is64bit)
7891     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7892       .addReg(Ptr1Reg).addImm(0).addImm(61);
7893   else
7894     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7895       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7896   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7897       .addReg(incr).addReg(ShiftReg);
7898   if (is8bit)
7899     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7900   else {
7901     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7902     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7903   }
7904   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7905       .addReg(Mask2Reg).addReg(ShiftReg);
7906
7907   BB = loopMBB;
7908   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7909     .addReg(ZeroReg).addReg(PtrReg);
7910   if (BinOpcode)
7911     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7912       .addReg(Incr2Reg).addReg(TmpDestReg);
7913   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7914     .addReg(TmpDestReg).addReg(MaskReg);
7915   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7916     .addReg(TmpReg).addReg(MaskReg);
7917   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7918     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7919   BuildMI(BB, dl, TII->get(PPC::STWCX))
7920     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7921   BuildMI(BB, dl, TII->get(PPC::BCC))
7922     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7923   BB->addSuccessor(loopMBB);
7924   BB->addSuccessor(exitMBB);
7925
7926   //  exitMBB:
7927   //   ...
7928   BB = exitMBB;
7929   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7930     .addReg(ShiftReg);
7931   return BB;
7932 }
7933
7934 llvm::MachineBasicBlock*
7935 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7936                                     MachineBasicBlock *MBB) const {
7937   DebugLoc DL = MI->getDebugLoc();
7938   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7939
7940   MachineFunction *MF = MBB->getParent();
7941   MachineRegisterInfo &MRI = MF->getRegInfo();
7942
7943   const BasicBlock *BB = MBB->getBasicBlock();
7944   MachineFunction::iterator I = MBB;
7945   ++I;
7946
7947   // Memory Reference
7948   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7949   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7950
7951   unsigned DstReg = MI->getOperand(0).getReg();
7952   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7953   assert(RC->hasType(MVT::i32) && "Invalid destination!");
7954   unsigned mainDstReg = MRI.createVirtualRegister(RC);
7955   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7956
7957   MVT PVT = getPointerTy();
7958   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7959          "Invalid Pointer Size!");
7960   // For v = setjmp(buf), we generate
7961   //
7962   // thisMBB:
7963   //  SjLjSetup mainMBB
7964   //  bl mainMBB
7965   //  v_restore = 1
7966   //  b sinkMBB
7967   //
7968   // mainMBB:
7969   //  buf[LabelOffset] = LR
7970   //  v_main = 0
7971   //
7972   // sinkMBB:
7973   //  v = phi(main, restore)
7974   //
7975
7976   MachineBasicBlock *thisMBB = MBB;
7977   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7978   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7979   MF->insert(I, mainMBB);
7980   MF->insert(I, sinkMBB);
7981
7982   MachineInstrBuilder MIB;
7983
7984   // Transfer the remainder of BB and its successor edges to sinkMBB.
7985   sinkMBB->splice(sinkMBB->begin(), MBB,
7986                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7987   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7988
7989   // Note that the structure of the jmp_buf used here is not compatible
7990   // with that used by libc, and is not designed to be. Specifically, it
7991   // stores only those 'reserved' registers that LLVM does not otherwise
7992   // understand how to spill. Also, by convention, by the time this
7993   // intrinsic is called, Clang has already stored the frame address in the
7994   // first slot of the buffer and stack address in the third. Following the
7995   // X86 target code, we'll store the jump address in the second slot. We also
7996   // need to save the TOC pointer (R2) to handle jumps between shared
7997   // libraries, and that will be stored in the fourth slot. The thread
7998   // identifier (R13) is not affected.
7999
8000   // thisMBB:
8001   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8002   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8003   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8004
8005   // Prepare IP either in reg.
8006   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8007   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8008   unsigned BufReg = MI->getOperand(1).getReg();
8009
8010   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8011     setUsesTOCBasePtr(*MBB->getParent());
8012     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8013             .addReg(PPC::X2)
8014             .addImm(TOCOffset)
8015             .addReg(BufReg);
8016     MIB.setMemRefs(MMOBegin, MMOEnd);
8017   }
8018
8019   // Naked functions never have a base pointer, and so we use r1. For all
8020   // other functions, this decision must be delayed until during PEI.
8021   unsigned BaseReg;
8022   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8023     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8024   else
8025     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8026
8027   MIB = BuildMI(*thisMBB, MI, DL,
8028                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8029             .addReg(BaseReg)
8030             .addImm(BPOffset)
8031             .addReg(BufReg);
8032   MIB.setMemRefs(MMOBegin, MMOEnd);
8033
8034   // Setup
8035   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8036   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8037   MIB.addRegMask(TRI->getNoPreservedMask());
8038
8039   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8040
8041   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8042           .addMBB(mainMBB);
8043   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8044
8045   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8046   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8047
8048   // mainMBB:
8049   //  mainDstReg = 0
8050   MIB =
8051       BuildMI(mainMBB, DL,
8052               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8053
8054   // Store IP
8055   if (Subtarget.isPPC64()) {
8056     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8057             .addReg(LabelReg)
8058             .addImm(LabelOffset)
8059             .addReg(BufReg);
8060   } else {
8061     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8062             .addReg(LabelReg)
8063             .addImm(LabelOffset)
8064             .addReg(BufReg);
8065   }
8066
8067   MIB.setMemRefs(MMOBegin, MMOEnd);
8068
8069   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8070   mainMBB->addSuccessor(sinkMBB);
8071
8072   // sinkMBB:
8073   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8074           TII->get(PPC::PHI), DstReg)
8075     .addReg(mainDstReg).addMBB(mainMBB)
8076     .addReg(restoreDstReg).addMBB(thisMBB);
8077
8078   MI->eraseFromParent();
8079   return sinkMBB;
8080 }
8081
8082 MachineBasicBlock *
8083 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8084                                      MachineBasicBlock *MBB) const {
8085   DebugLoc DL = MI->getDebugLoc();
8086   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8087
8088   MachineFunction *MF = MBB->getParent();
8089   MachineRegisterInfo &MRI = MF->getRegInfo();
8090
8091   // Memory Reference
8092   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8093   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8094
8095   MVT PVT = getPointerTy();
8096   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8097          "Invalid Pointer Size!");
8098
8099   const TargetRegisterClass *RC =
8100     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8101   unsigned Tmp = MRI.createVirtualRegister(RC);
8102   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8103   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8104   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8105   unsigned BP =
8106       (PVT == MVT::i64)
8107           ? PPC::X30
8108           : (Subtarget.isSVR4ABI() &&
8109                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8110                  ? PPC::R29
8111                  : PPC::R30);
8112
8113   MachineInstrBuilder MIB;
8114
8115   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8116   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8117   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8118   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8119
8120   unsigned BufReg = MI->getOperand(0).getReg();
8121
8122   // Reload FP (the jumped-to function may not have had a
8123   // frame pointer, and if so, then its r31 will be restored
8124   // as necessary).
8125   if (PVT == MVT::i64) {
8126     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8127             .addImm(0)
8128             .addReg(BufReg);
8129   } else {
8130     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8131             .addImm(0)
8132             .addReg(BufReg);
8133   }
8134   MIB.setMemRefs(MMOBegin, MMOEnd);
8135
8136   // Reload IP
8137   if (PVT == MVT::i64) {
8138     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8139             .addImm(LabelOffset)
8140             .addReg(BufReg);
8141   } else {
8142     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8143             .addImm(LabelOffset)
8144             .addReg(BufReg);
8145   }
8146   MIB.setMemRefs(MMOBegin, MMOEnd);
8147
8148   // Reload SP
8149   if (PVT == MVT::i64) {
8150     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8151             .addImm(SPOffset)
8152             .addReg(BufReg);
8153   } else {
8154     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8155             .addImm(SPOffset)
8156             .addReg(BufReg);
8157   }
8158   MIB.setMemRefs(MMOBegin, MMOEnd);
8159
8160   // Reload BP
8161   if (PVT == MVT::i64) {
8162     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8163             .addImm(BPOffset)
8164             .addReg(BufReg);
8165   } else {
8166     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8167             .addImm(BPOffset)
8168             .addReg(BufReg);
8169   }
8170   MIB.setMemRefs(MMOBegin, MMOEnd);
8171
8172   // Reload TOC
8173   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8174     setUsesTOCBasePtr(*MBB->getParent());
8175     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8176             .addImm(TOCOffset)
8177             .addReg(BufReg);
8178
8179     MIB.setMemRefs(MMOBegin, MMOEnd);
8180   }
8181
8182   // Jump
8183   BuildMI(*MBB, MI, DL,
8184           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8185   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8186
8187   MI->eraseFromParent();
8188   return MBB;
8189 }
8190
8191 MachineBasicBlock *
8192 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8193                                                MachineBasicBlock *BB) const {
8194   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8195       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8196     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8197         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8198       // Call lowering should have added an r2 operand to indicate a dependence
8199       // on the TOC base pointer value. It can't however, because there is no
8200       // way to mark the dependence as implicit there, and so the stackmap code
8201       // will confuse it with a regular operand. Instead, add the dependence
8202       // here.
8203       setUsesTOCBasePtr(*BB->getParent());
8204       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8205     }
8206
8207     return emitPatchPoint(MI, BB);
8208   }
8209
8210   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8211       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8212     return emitEHSjLjSetJmp(MI, BB);
8213   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8214              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8215     return emitEHSjLjLongJmp(MI, BB);
8216   }
8217
8218   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8219
8220   // To "insert" these instructions we actually have to insert their
8221   // control-flow patterns.
8222   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8223   MachineFunction::iterator It = BB;
8224   ++It;
8225
8226   MachineFunction *F = BB->getParent();
8227
8228   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8229                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8230                               MI->getOpcode() == PPC::SELECT_I4 ||
8231                               MI->getOpcode() == PPC::SELECT_I8)) {
8232     SmallVector<MachineOperand, 2> Cond;
8233     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8234         MI->getOpcode() == PPC::SELECT_CC_I8)
8235       Cond.push_back(MI->getOperand(4));
8236     else
8237       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8238     Cond.push_back(MI->getOperand(1));
8239
8240     DebugLoc dl = MI->getDebugLoc();
8241     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8242                       Cond, MI->getOperand(2).getReg(),
8243                       MI->getOperand(3).getReg());
8244   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8245              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8246              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8247              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8248              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8249              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8250              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8251              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8252              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8253              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8254              MI->getOpcode() == PPC::SELECT_I4 ||
8255              MI->getOpcode() == PPC::SELECT_I8 ||
8256              MI->getOpcode() == PPC::SELECT_F4 ||
8257              MI->getOpcode() == PPC::SELECT_F8 ||
8258              MI->getOpcode() == PPC::SELECT_QFRC ||
8259              MI->getOpcode() == PPC::SELECT_QSRC ||
8260              MI->getOpcode() == PPC::SELECT_QBRC ||
8261              MI->getOpcode() == PPC::SELECT_VRRC ||
8262              MI->getOpcode() == PPC::SELECT_VSFRC ||
8263              MI->getOpcode() == PPC::SELECT_VSRC) {
8264     // The incoming instruction knows the destination vreg to set, the
8265     // condition code register to branch on, the true/false values to
8266     // select between, and a branch opcode to use.
8267
8268     //  thisMBB:
8269     //  ...
8270     //   TrueVal = ...
8271     //   cmpTY ccX, r1, r2
8272     //   bCC copy1MBB
8273     //   fallthrough --> copy0MBB
8274     MachineBasicBlock *thisMBB = BB;
8275     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8276     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8277     DebugLoc dl = MI->getDebugLoc();
8278     F->insert(It, copy0MBB);
8279     F->insert(It, sinkMBB);
8280
8281     // Transfer the remainder of BB and its successor edges to sinkMBB.
8282     sinkMBB->splice(sinkMBB->begin(), BB,
8283                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8284     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8285
8286     // Next, add the true and fallthrough blocks as its successors.
8287     BB->addSuccessor(copy0MBB);
8288     BB->addSuccessor(sinkMBB);
8289
8290     if (MI->getOpcode() == PPC::SELECT_I4 ||
8291         MI->getOpcode() == PPC::SELECT_I8 ||
8292         MI->getOpcode() == PPC::SELECT_F4 ||
8293         MI->getOpcode() == PPC::SELECT_F8 ||
8294         MI->getOpcode() == PPC::SELECT_QFRC ||
8295         MI->getOpcode() == PPC::SELECT_QSRC ||
8296         MI->getOpcode() == PPC::SELECT_QBRC ||
8297         MI->getOpcode() == PPC::SELECT_VRRC ||
8298         MI->getOpcode() == PPC::SELECT_VSFRC ||
8299         MI->getOpcode() == PPC::SELECT_VSRC) {
8300       BuildMI(BB, dl, TII->get(PPC::BC))
8301         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8302     } else {
8303       unsigned SelectPred = MI->getOperand(4).getImm();
8304       BuildMI(BB, dl, TII->get(PPC::BCC))
8305         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8306     }
8307
8308     //  copy0MBB:
8309     //   %FalseValue = ...
8310     //   # fallthrough to sinkMBB
8311     BB = copy0MBB;
8312
8313     // Update machine-CFG edges
8314     BB->addSuccessor(sinkMBB);
8315
8316     //  sinkMBB:
8317     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8318     //  ...
8319     BB = sinkMBB;
8320     BuildMI(*BB, BB->begin(), dl,
8321             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8322       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8323       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8324   } else if (MI->getOpcode() == PPC::ReadTB) {
8325     // To read the 64-bit time-base register on a 32-bit target, we read the
8326     // two halves. Should the counter have wrapped while it was being read, we
8327     // need to try again.
8328     // ...
8329     // readLoop:
8330     // mfspr Rx,TBU # load from TBU
8331     // mfspr Ry,TB  # load from TB
8332     // mfspr Rz,TBU # load from TBU
8333     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8334     // bne readLoop   # branch if they're not equal
8335     // ...
8336
8337     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8338     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8339     DebugLoc dl = MI->getDebugLoc();
8340     F->insert(It, readMBB);
8341     F->insert(It, sinkMBB);
8342
8343     // Transfer the remainder of BB and its successor edges to sinkMBB.
8344     sinkMBB->splice(sinkMBB->begin(), BB,
8345                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8346     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8347
8348     BB->addSuccessor(readMBB);
8349     BB = readMBB;
8350
8351     MachineRegisterInfo &RegInfo = F->getRegInfo();
8352     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8353     unsigned LoReg = MI->getOperand(0).getReg();
8354     unsigned HiReg = MI->getOperand(1).getReg();
8355
8356     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8357     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8358     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8359
8360     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8361
8362     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8363       .addReg(HiReg).addReg(ReadAgainReg);
8364     BuildMI(BB, dl, TII->get(PPC::BCC))
8365       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8366
8367     BB->addSuccessor(readMBB);
8368     BB->addSuccessor(sinkMBB);
8369   }
8370   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8371     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8372   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8373     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8374   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8375     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
8376   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8377     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
8378
8379   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8380     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8381   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8382     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8383   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8384     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
8385   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8386     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
8387
8388   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8389     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8390   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8391     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8392   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8393     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
8394   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8395     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
8396
8397   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8398     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8399   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8400     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8401   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8402     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
8403   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8404     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
8405
8406   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8407     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8408   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8409     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8410   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8411     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
8412   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8413     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
8414
8415   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8416     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8417   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8418     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8419   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8420     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
8421   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8422     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
8423
8424   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8425     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8426   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8427     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8428   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8429     BB = EmitAtomicBinary(MI, BB, false, 0);
8430   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8431     BB = EmitAtomicBinary(MI, BB, true, 0);
8432
8433   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8434            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
8435     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8436
8437     unsigned dest   = MI->getOperand(0).getReg();
8438     unsigned ptrA   = MI->getOperand(1).getReg();
8439     unsigned ptrB   = MI->getOperand(2).getReg();
8440     unsigned oldval = MI->getOperand(3).getReg();
8441     unsigned newval = MI->getOperand(4).getReg();
8442     DebugLoc dl     = MI->getDebugLoc();
8443
8444     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8445     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8446     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8447     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8448     F->insert(It, loop1MBB);
8449     F->insert(It, loop2MBB);
8450     F->insert(It, midMBB);
8451     F->insert(It, exitMBB);
8452     exitMBB->splice(exitMBB->begin(), BB,
8453                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8454     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8455
8456     //  thisMBB:
8457     //   ...
8458     //   fallthrough --> loopMBB
8459     BB->addSuccessor(loop1MBB);
8460
8461     // loop1MBB:
8462     //   l[wd]arx dest, ptr
8463     //   cmp[wd] dest, oldval
8464     //   bne- midMBB
8465     // loop2MBB:
8466     //   st[wd]cx. newval, ptr
8467     //   bne- loopMBB
8468     //   b exitBB
8469     // midMBB:
8470     //   st[wd]cx. dest, ptr
8471     // exitBB:
8472     BB = loop1MBB;
8473     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
8474       .addReg(ptrA).addReg(ptrB);
8475     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8476       .addReg(oldval).addReg(dest);
8477     BuildMI(BB, dl, TII->get(PPC::BCC))
8478       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8479     BB->addSuccessor(loop2MBB);
8480     BB->addSuccessor(midMBB);
8481
8482     BB = loop2MBB;
8483     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8484       .addReg(newval).addReg(ptrA).addReg(ptrB);
8485     BuildMI(BB, dl, TII->get(PPC::BCC))
8486       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8487     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8488     BB->addSuccessor(loop1MBB);
8489     BB->addSuccessor(exitMBB);
8490
8491     BB = midMBB;
8492     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8493       .addReg(dest).addReg(ptrA).addReg(ptrB);
8494     BB->addSuccessor(exitMBB);
8495
8496     //  exitMBB:
8497     //   ...
8498     BB = exitMBB;
8499   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8500              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8501     // We must use 64-bit registers for addresses when targeting 64-bit,
8502     // since we're actually doing arithmetic on them.  Other registers
8503     // can be 32-bit.
8504     bool is64bit = Subtarget.isPPC64();
8505     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8506
8507     unsigned dest   = MI->getOperand(0).getReg();
8508     unsigned ptrA   = MI->getOperand(1).getReg();
8509     unsigned ptrB   = MI->getOperand(2).getReg();
8510     unsigned oldval = MI->getOperand(3).getReg();
8511     unsigned newval = MI->getOperand(4).getReg();
8512     DebugLoc dl     = MI->getDebugLoc();
8513
8514     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8515     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8516     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8517     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8518     F->insert(It, loop1MBB);
8519     F->insert(It, loop2MBB);
8520     F->insert(It, midMBB);
8521     F->insert(It, exitMBB);
8522     exitMBB->splice(exitMBB->begin(), BB,
8523                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8524     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8525
8526     MachineRegisterInfo &RegInfo = F->getRegInfo();
8527     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8528                                             : &PPC::GPRCRegClass;
8529     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8530     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8531     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8532     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8533     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8534     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8535     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8536     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8537     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8538     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8539     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8540     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8541     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8542     unsigned Ptr1Reg;
8543     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8544     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8545     //  thisMBB:
8546     //   ...
8547     //   fallthrough --> loopMBB
8548     BB->addSuccessor(loop1MBB);
8549
8550     // The 4-byte load must be aligned, while a char or short may be
8551     // anywhere in the word.  Hence all this nasty bookkeeping code.
8552     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8553     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8554     //   xori shift, shift1, 24 [16]
8555     //   rlwinm ptr, ptr1, 0, 0, 29
8556     //   slw newval2, newval, shift
8557     //   slw oldval2, oldval,shift
8558     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8559     //   slw mask, mask2, shift
8560     //   and newval3, newval2, mask
8561     //   and oldval3, oldval2, mask
8562     // loop1MBB:
8563     //   lwarx tmpDest, ptr
8564     //   and tmp, tmpDest, mask
8565     //   cmpw tmp, oldval3
8566     //   bne- midMBB
8567     // loop2MBB:
8568     //   andc tmp2, tmpDest, mask
8569     //   or tmp4, tmp2, newval3
8570     //   stwcx. tmp4, ptr
8571     //   bne- loop1MBB
8572     //   b exitBB
8573     // midMBB:
8574     //   stwcx. tmpDest, ptr
8575     // exitBB:
8576     //   srw dest, tmpDest, shift
8577     if (ptrA != ZeroReg) {
8578       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8579       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8580         .addReg(ptrA).addReg(ptrB);
8581     } else {
8582       Ptr1Reg = ptrB;
8583     }
8584     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8585         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8586     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8587         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8588     if (is64bit)
8589       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8590         .addReg(Ptr1Reg).addImm(0).addImm(61);
8591     else
8592       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8593         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8594     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8595         .addReg(newval).addReg(ShiftReg);
8596     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8597         .addReg(oldval).addReg(ShiftReg);
8598     if (is8bit)
8599       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8600     else {
8601       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8602       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8603         .addReg(Mask3Reg).addImm(65535);
8604     }
8605     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8606         .addReg(Mask2Reg).addReg(ShiftReg);
8607     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8608         .addReg(NewVal2Reg).addReg(MaskReg);
8609     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8610         .addReg(OldVal2Reg).addReg(MaskReg);
8611
8612     BB = loop1MBB;
8613     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8614         .addReg(ZeroReg).addReg(PtrReg);
8615     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8616         .addReg(TmpDestReg).addReg(MaskReg);
8617     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8618         .addReg(TmpReg).addReg(OldVal3Reg);
8619     BuildMI(BB, dl, TII->get(PPC::BCC))
8620         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8621     BB->addSuccessor(loop2MBB);
8622     BB->addSuccessor(midMBB);
8623
8624     BB = loop2MBB;
8625     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8626         .addReg(TmpDestReg).addReg(MaskReg);
8627     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8628         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8629     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8630         .addReg(ZeroReg).addReg(PtrReg);
8631     BuildMI(BB, dl, TII->get(PPC::BCC))
8632       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8633     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8634     BB->addSuccessor(loop1MBB);
8635     BB->addSuccessor(exitMBB);
8636
8637     BB = midMBB;
8638     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8639       .addReg(ZeroReg).addReg(PtrReg);
8640     BB->addSuccessor(exitMBB);
8641
8642     //  exitMBB:
8643     //   ...
8644     BB = exitMBB;
8645     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8646       .addReg(ShiftReg);
8647   } else if (MI->getOpcode() == PPC::FADDrtz) {
8648     // This pseudo performs an FADD with rounding mode temporarily forced
8649     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8650     // is not modeled at the SelectionDAG level.
8651     unsigned Dest = MI->getOperand(0).getReg();
8652     unsigned Src1 = MI->getOperand(1).getReg();
8653     unsigned Src2 = MI->getOperand(2).getReg();
8654     DebugLoc dl   = MI->getDebugLoc();
8655
8656     MachineRegisterInfo &RegInfo = F->getRegInfo();
8657     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8658
8659     // Save FPSCR value.
8660     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8661
8662     // Set rounding mode to round-to-zero.
8663     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8664     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8665
8666     // Perform addition.
8667     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8668
8669     // Restore FPSCR value.
8670     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8671   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8672              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8673              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8674              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8675     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8676                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8677                       PPC::ANDIo8 : PPC::ANDIo;
8678     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8679                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8680
8681     MachineRegisterInfo &RegInfo = F->getRegInfo();
8682     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8683                                                   &PPC::GPRCRegClass :
8684                                                   &PPC::G8RCRegClass);
8685
8686     DebugLoc dl   = MI->getDebugLoc();
8687     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8688       .addReg(MI->getOperand(1).getReg()).addImm(1);
8689     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8690             MI->getOperand(0).getReg())
8691       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8692   } else {
8693     llvm_unreachable("Unexpected instr type to insert");
8694   }
8695
8696   MI->eraseFromParent();   // The pseudo instruction is gone now.
8697   return BB;
8698 }
8699
8700 //===----------------------------------------------------------------------===//
8701 // Target Optimization Hooks
8702 //===----------------------------------------------------------------------===//
8703
8704 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8705                                             DAGCombinerInfo &DCI,
8706                                             unsigned &RefinementSteps,
8707                                             bool &UseOneConstNR) const {
8708   EVT VT = Operand.getValueType();
8709   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8710       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8711       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8712       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8713       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8714       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8715     // Convergence is quadratic, so we essentially double the number of digits
8716     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8717     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8718     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8719     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8720     if (VT.getScalarType() == MVT::f64)
8721       ++RefinementSteps;
8722     UseOneConstNR = true;
8723     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8724   }
8725   return SDValue();
8726 }
8727
8728 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8729                                             DAGCombinerInfo &DCI,
8730                                             unsigned &RefinementSteps) const {
8731   EVT VT = Operand.getValueType();
8732   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8733       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8734       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8735       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8736       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8737       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8738     // Convergence is quadratic, so we essentially double the number of digits
8739     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8740     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8741     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8742     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8743     if (VT.getScalarType() == MVT::f64)
8744       ++RefinementSteps;
8745     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8746   }
8747   return SDValue();
8748 }
8749
8750 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8751   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8752   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8753   // enabled for division), this functionality is redundant with the default
8754   // combiner logic (once the division -> reciprocal/multiply transformation
8755   // has taken place). As a result, this matters more for older cores than for
8756   // newer ones.
8757
8758   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8759   // reciprocal if there are two or more FDIVs (for embedded cores with only
8760   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8761   switch (Subtarget.getDarwinDirective()) {
8762   default:
8763     return NumUsers > 2;
8764   case PPC::DIR_440:
8765   case PPC::DIR_A2:
8766   case PPC::DIR_E500mc:
8767   case PPC::DIR_E5500:
8768     return NumUsers > 1;
8769   }
8770 }
8771
8772 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8773                             unsigned Bytes, int Dist,
8774                             SelectionDAG &DAG) {
8775   if (VT.getSizeInBits() / 8 != Bytes)
8776     return false;
8777
8778   SDValue BaseLoc = Base->getBasePtr();
8779   if (Loc.getOpcode() == ISD::FrameIndex) {
8780     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8781       return false;
8782     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8783     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8784     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8785     int FS  = MFI->getObjectSize(FI);
8786     int BFS = MFI->getObjectSize(BFI);
8787     if (FS != BFS || FS != (int)Bytes) return false;
8788     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8789   }
8790
8791   // Handle X+C
8792   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8793       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8794     return true;
8795
8796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8797   const GlobalValue *GV1 = nullptr;
8798   const GlobalValue *GV2 = nullptr;
8799   int64_t Offset1 = 0;
8800   int64_t Offset2 = 0;
8801   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8802   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8803   if (isGA1 && isGA2 && GV1 == GV2)
8804     return Offset1 == (Offset2 + Dist*Bytes);
8805   return false;
8806 }
8807
8808 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8809 // not enforce equality of the chain operands.
8810 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8811                             unsigned Bytes, int Dist,
8812                             SelectionDAG &DAG) {
8813   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8814     EVT VT = LS->getMemoryVT();
8815     SDValue Loc = LS->getBasePtr();
8816     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8817   }
8818
8819   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8820     EVT VT;
8821     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8822     default: return false;
8823     case Intrinsic::ppc_qpx_qvlfd:
8824     case Intrinsic::ppc_qpx_qvlfda:
8825       VT = MVT::v4f64;
8826       break;
8827     case Intrinsic::ppc_qpx_qvlfs:
8828     case Intrinsic::ppc_qpx_qvlfsa:
8829       VT = MVT::v4f32;
8830       break;
8831     case Intrinsic::ppc_qpx_qvlfcd:
8832     case Intrinsic::ppc_qpx_qvlfcda:
8833       VT = MVT::v2f64;
8834       break;
8835     case Intrinsic::ppc_qpx_qvlfcs:
8836     case Intrinsic::ppc_qpx_qvlfcsa:
8837       VT = MVT::v2f32;
8838       break;
8839     case Intrinsic::ppc_qpx_qvlfiwa:
8840     case Intrinsic::ppc_qpx_qvlfiwz:
8841     case Intrinsic::ppc_altivec_lvx:
8842     case Intrinsic::ppc_altivec_lvxl:
8843     case Intrinsic::ppc_vsx_lxvw4x:
8844       VT = MVT::v4i32;
8845       break;
8846     case Intrinsic::ppc_vsx_lxvd2x:
8847       VT = MVT::v2f64;
8848       break;
8849     case Intrinsic::ppc_altivec_lvebx:
8850       VT = MVT::i8;
8851       break;
8852     case Intrinsic::ppc_altivec_lvehx:
8853       VT = MVT::i16;
8854       break;
8855     case Intrinsic::ppc_altivec_lvewx:
8856       VT = MVT::i32;
8857       break;
8858     }
8859
8860     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8861   }
8862
8863   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8864     EVT VT;
8865     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8866     default: return false;
8867     case Intrinsic::ppc_qpx_qvstfd:
8868     case Intrinsic::ppc_qpx_qvstfda:
8869       VT = MVT::v4f64;
8870       break;
8871     case Intrinsic::ppc_qpx_qvstfs:
8872     case Intrinsic::ppc_qpx_qvstfsa:
8873       VT = MVT::v4f32;
8874       break;
8875     case Intrinsic::ppc_qpx_qvstfcd:
8876     case Intrinsic::ppc_qpx_qvstfcda:
8877       VT = MVT::v2f64;
8878       break;
8879     case Intrinsic::ppc_qpx_qvstfcs:
8880     case Intrinsic::ppc_qpx_qvstfcsa:
8881       VT = MVT::v2f32;
8882       break;
8883     case Intrinsic::ppc_qpx_qvstfiw:
8884     case Intrinsic::ppc_qpx_qvstfiwa:
8885     case Intrinsic::ppc_altivec_stvx:
8886     case Intrinsic::ppc_altivec_stvxl:
8887     case Intrinsic::ppc_vsx_stxvw4x:
8888       VT = MVT::v4i32;
8889       break;
8890     case Intrinsic::ppc_vsx_stxvd2x:
8891       VT = MVT::v2f64;
8892       break;
8893     case Intrinsic::ppc_altivec_stvebx:
8894       VT = MVT::i8;
8895       break;
8896     case Intrinsic::ppc_altivec_stvehx:
8897       VT = MVT::i16;
8898       break;
8899     case Intrinsic::ppc_altivec_stvewx:
8900       VT = MVT::i32;
8901       break;
8902     }
8903
8904     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8905   }
8906
8907   return false;
8908 }
8909
8910 // Return true is there is a nearyby consecutive load to the one provided
8911 // (regardless of alignment). We search up and down the chain, looking though
8912 // token factors and other loads (but nothing else). As a result, a true result
8913 // indicates that it is safe to create a new consecutive load adjacent to the
8914 // load provided.
8915 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8916   SDValue Chain = LD->getChain();
8917   EVT VT = LD->getMemoryVT();
8918
8919   SmallSet<SDNode *, 16> LoadRoots;
8920   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8921   SmallSet<SDNode *, 16> Visited;
8922
8923   // First, search up the chain, branching to follow all token-factor operands.
8924   // If we find a consecutive load, then we're done, otherwise, record all
8925   // nodes just above the top-level loads and token factors.
8926   while (!Queue.empty()) {
8927     SDNode *ChainNext = Queue.pop_back_val();
8928     if (!Visited.insert(ChainNext).second)
8929       continue;
8930
8931     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8932       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8933         return true;
8934
8935       if (!Visited.count(ChainLD->getChain().getNode()))
8936         Queue.push_back(ChainLD->getChain().getNode());
8937     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8938       for (const SDUse &O : ChainNext->ops())
8939         if (!Visited.count(O.getNode()))
8940           Queue.push_back(O.getNode());
8941     } else
8942       LoadRoots.insert(ChainNext);
8943   }
8944
8945   // Second, search down the chain, starting from the top-level nodes recorded
8946   // in the first phase. These top-level nodes are the nodes just above all
8947   // loads and token factors. Starting with their uses, recursively look though
8948   // all loads (just the chain uses) and token factors to find a consecutive
8949   // load.
8950   Visited.clear();
8951   Queue.clear();
8952
8953   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8954        IE = LoadRoots.end(); I != IE; ++I) {
8955     Queue.push_back(*I);
8956        
8957     while (!Queue.empty()) {
8958       SDNode *LoadRoot = Queue.pop_back_val();
8959       if (!Visited.insert(LoadRoot).second)
8960         continue;
8961
8962       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8963         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8964           return true;
8965
8966       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8967            UE = LoadRoot->use_end(); UI != UE; ++UI)
8968         if (((isa<MemSDNode>(*UI) &&
8969             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8970             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8971           Queue.push_back(*UI);
8972     }
8973   }
8974
8975   return false;
8976 }
8977
8978 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8979                                                   DAGCombinerInfo &DCI) const {
8980   SelectionDAG &DAG = DCI.DAG;
8981   SDLoc dl(N);
8982
8983   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8984   // If we're tracking CR bits, we need to be careful that we don't have:
8985   //   trunc(binary-ops(zext(x), zext(y)))
8986   // or
8987   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8988   // such that we're unnecessarily moving things into GPRs when it would be
8989   // better to keep them in CR bits.
8990
8991   // Note that trunc here can be an actual i1 trunc, or can be the effective
8992   // truncation that comes from a setcc or select_cc.
8993   if (N->getOpcode() == ISD::TRUNCATE &&
8994       N->getValueType(0) != MVT::i1)
8995     return SDValue();
8996
8997   if (N->getOperand(0).getValueType() != MVT::i32 &&
8998       N->getOperand(0).getValueType() != MVT::i64)
8999     return SDValue();
9000
9001   if (N->getOpcode() == ISD::SETCC ||
9002       N->getOpcode() == ISD::SELECT_CC) {
9003     // If we're looking at a comparison, then we need to make sure that the
9004     // high bits (all except for the first) don't matter the result.
9005     ISD::CondCode CC =
9006       cast<CondCodeSDNode>(N->getOperand(
9007         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9008     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9009
9010     if (ISD::isSignedIntSetCC(CC)) {
9011       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9012           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9013         return SDValue();
9014     } else if (ISD::isUnsignedIntSetCC(CC)) {
9015       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9016                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9017           !DAG.MaskedValueIsZero(N->getOperand(1),
9018                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9019         return SDValue();
9020     } else {
9021       // This is neither a signed nor an unsigned comparison, just make sure
9022       // that the high bits are equal.
9023       APInt Op1Zero, Op1One;
9024       APInt Op2Zero, Op2One;
9025       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9026       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9027
9028       // We don't really care about what is known about the first bit (if
9029       // anything), so clear it in all masks prior to comparing them.
9030       Op1Zero.clearBit(0); Op1One.clearBit(0);
9031       Op2Zero.clearBit(0); Op2One.clearBit(0);
9032
9033       if (Op1Zero != Op2Zero || Op1One != Op2One)
9034         return SDValue();
9035     }
9036   }
9037
9038   // We now know that the higher-order bits are irrelevant, we just need to
9039   // make sure that all of the intermediate operations are bit operations, and
9040   // all inputs are extensions.
9041   if (N->getOperand(0).getOpcode() != ISD::AND &&
9042       N->getOperand(0).getOpcode() != ISD::OR  &&
9043       N->getOperand(0).getOpcode() != ISD::XOR &&
9044       N->getOperand(0).getOpcode() != ISD::SELECT &&
9045       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9046       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9047       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9048       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9049       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9050     return SDValue();
9051
9052   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9053       N->getOperand(1).getOpcode() != ISD::AND &&
9054       N->getOperand(1).getOpcode() != ISD::OR  &&
9055       N->getOperand(1).getOpcode() != ISD::XOR &&
9056       N->getOperand(1).getOpcode() != ISD::SELECT &&
9057       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9058       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9059       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9060       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9061       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9062     return SDValue();
9063
9064   SmallVector<SDValue, 4> Inputs;
9065   SmallVector<SDValue, 8> BinOps, PromOps;
9066   SmallPtrSet<SDNode *, 16> Visited;
9067
9068   for (unsigned i = 0; i < 2; ++i) {
9069     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9070           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9071           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9072           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9073         isa<ConstantSDNode>(N->getOperand(i)))
9074       Inputs.push_back(N->getOperand(i));
9075     else
9076       BinOps.push_back(N->getOperand(i));
9077
9078     if (N->getOpcode() == ISD::TRUNCATE)
9079       break;
9080   }
9081
9082   // Visit all inputs, collect all binary operations (and, or, xor and
9083   // select) that are all fed by extensions. 
9084   while (!BinOps.empty()) {
9085     SDValue BinOp = BinOps.back();
9086     BinOps.pop_back();
9087
9088     if (!Visited.insert(BinOp.getNode()).second)
9089       continue;
9090
9091     PromOps.push_back(BinOp);
9092
9093     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9094       // The condition of the select is not promoted.
9095       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9096         continue;
9097       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9098         continue;
9099
9100       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9101             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9102             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9103            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9104           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9105         Inputs.push_back(BinOp.getOperand(i)); 
9106       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9107                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9108                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9109                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9110                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9111                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9112                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9113                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9114                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9115         BinOps.push_back(BinOp.getOperand(i));
9116       } else {
9117         // We have an input that is not an extension or another binary
9118         // operation; we'll abort this transformation.
9119         return SDValue();
9120       }
9121     }
9122   }
9123
9124   // Make sure that this is a self-contained cluster of operations (which
9125   // is not quite the same thing as saying that everything has only one
9126   // use).
9127   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9128     if (isa<ConstantSDNode>(Inputs[i]))
9129       continue;
9130
9131     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9132                               UE = Inputs[i].getNode()->use_end();
9133          UI != UE; ++UI) {
9134       SDNode *User = *UI;
9135       if (User != N && !Visited.count(User))
9136         return SDValue();
9137
9138       // Make sure that we're not going to promote the non-output-value
9139       // operand(s) or SELECT or SELECT_CC.
9140       // FIXME: Although we could sometimes handle this, and it does occur in
9141       // practice that one of the condition inputs to the select is also one of
9142       // the outputs, we currently can't deal with this.
9143       if (User->getOpcode() == ISD::SELECT) {
9144         if (User->getOperand(0) == Inputs[i])
9145           return SDValue();
9146       } else if (User->getOpcode() == ISD::SELECT_CC) {
9147         if (User->getOperand(0) == Inputs[i] ||
9148             User->getOperand(1) == Inputs[i])
9149           return SDValue();
9150       }
9151     }
9152   }
9153
9154   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9155     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9156                               UE = PromOps[i].getNode()->use_end();
9157          UI != UE; ++UI) {
9158       SDNode *User = *UI;
9159       if (User != N && !Visited.count(User))
9160         return SDValue();
9161
9162       // Make sure that we're not going to promote the non-output-value
9163       // operand(s) or SELECT or SELECT_CC.
9164       // FIXME: Although we could sometimes handle this, and it does occur in
9165       // practice that one of the condition inputs to the select is also one of
9166       // the outputs, we currently can't deal with this.
9167       if (User->getOpcode() == ISD::SELECT) {
9168         if (User->getOperand(0) == PromOps[i])
9169           return SDValue();
9170       } else if (User->getOpcode() == ISD::SELECT_CC) {
9171         if (User->getOperand(0) == PromOps[i] ||
9172             User->getOperand(1) == PromOps[i])
9173           return SDValue();
9174       }
9175     }
9176   }
9177
9178   // Replace all inputs with the extension operand.
9179   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9180     // Constants may have users outside the cluster of to-be-promoted nodes,
9181     // and so we need to replace those as we do the promotions.
9182     if (isa<ConstantSDNode>(Inputs[i]))
9183       continue;
9184     else
9185       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9186   }
9187
9188   // Replace all operations (these are all the same, but have a different
9189   // (i1) return type). DAG.getNode will validate that the types of
9190   // a binary operator match, so go through the list in reverse so that
9191   // we've likely promoted both operands first. Any intermediate truncations or
9192   // extensions disappear.
9193   while (!PromOps.empty()) {
9194     SDValue PromOp = PromOps.back();
9195     PromOps.pop_back();
9196
9197     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9198         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9199         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9200         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9201       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9202           PromOp.getOperand(0).getValueType() != MVT::i1) {
9203         // The operand is not yet ready (see comment below).
9204         PromOps.insert(PromOps.begin(), PromOp);
9205         continue;
9206       }
9207
9208       SDValue RepValue = PromOp.getOperand(0);
9209       if (isa<ConstantSDNode>(RepValue))
9210         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9211
9212       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9213       continue;
9214     }
9215
9216     unsigned C;
9217     switch (PromOp.getOpcode()) {
9218     default:             C = 0; break;
9219     case ISD::SELECT:    C = 1; break;
9220     case ISD::SELECT_CC: C = 2; break;
9221     }
9222
9223     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9224          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9225         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9226          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9227       // The to-be-promoted operands of this node have not yet been
9228       // promoted (this should be rare because we're going through the
9229       // list backward, but if one of the operands has several users in
9230       // this cluster of to-be-promoted nodes, it is possible).
9231       PromOps.insert(PromOps.begin(), PromOp);
9232       continue;
9233     }
9234
9235     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9236                                 PromOp.getNode()->op_end());
9237
9238     // If there are any constant inputs, make sure they're replaced now.
9239     for (unsigned i = 0; i < 2; ++i)
9240       if (isa<ConstantSDNode>(Ops[C+i]))
9241         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9242
9243     DAG.ReplaceAllUsesOfValueWith(PromOp,
9244       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9245   }
9246
9247   // Now we're left with the initial truncation itself.
9248   if (N->getOpcode() == ISD::TRUNCATE)
9249     return N->getOperand(0);
9250
9251   // Otherwise, this is a comparison. The operands to be compared have just
9252   // changed type (to i1), but everything else is the same.
9253   return SDValue(N, 0);
9254 }
9255
9256 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9257                                                   DAGCombinerInfo &DCI) const {
9258   SelectionDAG &DAG = DCI.DAG;
9259   SDLoc dl(N);
9260
9261   // If we're tracking CR bits, we need to be careful that we don't have:
9262   //   zext(binary-ops(trunc(x), trunc(y)))
9263   // or
9264   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9265   // such that we're unnecessarily moving things into CR bits that can more
9266   // efficiently stay in GPRs. Note that if we're not certain that the high
9267   // bits are set as required by the final extension, we still may need to do
9268   // some masking to get the proper behavior.
9269
9270   // This same functionality is important on PPC64 when dealing with
9271   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9272   // the return values of functions. Because it is so similar, it is handled
9273   // here as well.
9274
9275   if (N->getValueType(0) != MVT::i32 &&
9276       N->getValueType(0) != MVT::i64)
9277     return SDValue();
9278
9279   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9280         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9281     return SDValue();
9282
9283   if (N->getOperand(0).getOpcode() != ISD::AND &&
9284       N->getOperand(0).getOpcode() != ISD::OR  &&
9285       N->getOperand(0).getOpcode() != ISD::XOR &&
9286       N->getOperand(0).getOpcode() != ISD::SELECT &&
9287       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9288     return SDValue();
9289
9290   SmallVector<SDValue, 4> Inputs;
9291   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9292   SmallPtrSet<SDNode *, 16> Visited;
9293
9294   // Visit all inputs, collect all binary operations (and, or, xor and
9295   // select) that are all fed by truncations. 
9296   while (!BinOps.empty()) {
9297     SDValue BinOp = BinOps.back();
9298     BinOps.pop_back();
9299
9300     if (!Visited.insert(BinOp.getNode()).second)
9301       continue;
9302
9303     PromOps.push_back(BinOp);
9304
9305     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9306       // The condition of the select is not promoted.
9307       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9308         continue;
9309       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9310         continue;
9311
9312       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9313           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9314         Inputs.push_back(BinOp.getOperand(i)); 
9315       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9316                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9317                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9318                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9319                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9320         BinOps.push_back(BinOp.getOperand(i));
9321       } else {
9322         // We have an input that is not a truncation or another binary
9323         // operation; we'll abort this transformation.
9324         return SDValue();
9325       }
9326     }
9327   }
9328
9329   // The operands of a select that must be truncated when the select is
9330   // promoted because the operand is actually part of the to-be-promoted set.
9331   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9332
9333   // Make sure that this is a self-contained cluster of operations (which
9334   // is not quite the same thing as saying that everything has only one
9335   // use).
9336   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9337     if (isa<ConstantSDNode>(Inputs[i]))
9338       continue;
9339
9340     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9341                               UE = Inputs[i].getNode()->use_end();
9342          UI != UE; ++UI) {
9343       SDNode *User = *UI;
9344       if (User != N && !Visited.count(User))
9345         return SDValue();
9346
9347       // If we're going to promote the non-output-value operand(s) or SELECT or
9348       // SELECT_CC, record them for truncation.
9349       if (User->getOpcode() == ISD::SELECT) {
9350         if (User->getOperand(0) == Inputs[i])
9351           SelectTruncOp[0].insert(std::make_pair(User,
9352                                     User->getOperand(0).getValueType()));
9353       } else if (User->getOpcode() == ISD::SELECT_CC) {
9354         if (User->getOperand(0) == Inputs[i])
9355           SelectTruncOp[0].insert(std::make_pair(User,
9356                                     User->getOperand(0).getValueType()));
9357         if (User->getOperand(1) == Inputs[i])
9358           SelectTruncOp[1].insert(std::make_pair(User,
9359                                     User->getOperand(1).getValueType()));
9360       }
9361     }
9362   }
9363
9364   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9365     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9366                               UE = PromOps[i].getNode()->use_end();
9367          UI != UE; ++UI) {
9368       SDNode *User = *UI;
9369       if (User != N && !Visited.count(User))
9370         return SDValue();
9371
9372       // If we're going to promote the non-output-value operand(s) or SELECT or
9373       // SELECT_CC, record them for truncation.
9374       if (User->getOpcode() == ISD::SELECT) {
9375         if (User->getOperand(0) == PromOps[i])
9376           SelectTruncOp[0].insert(std::make_pair(User,
9377                                     User->getOperand(0).getValueType()));
9378       } else if (User->getOpcode() == ISD::SELECT_CC) {
9379         if (User->getOperand(0) == PromOps[i])
9380           SelectTruncOp[0].insert(std::make_pair(User,
9381                                     User->getOperand(0).getValueType()));
9382         if (User->getOperand(1) == PromOps[i])
9383           SelectTruncOp[1].insert(std::make_pair(User,
9384                                     User->getOperand(1).getValueType()));
9385       }
9386     }
9387   }
9388
9389   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9390   bool ReallyNeedsExt = false;
9391   if (N->getOpcode() != ISD::ANY_EXTEND) {
9392     // If all of the inputs are not already sign/zero extended, then
9393     // we'll still need to do that at the end.
9394     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9395       if (isa<ConstantSDNode>(Inputs[i]))
9396         continue;
9397
9398       unsigned OpBits =
9399         Inputs[i].getOperand(0).getValueSizeInBits();
9400       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9401
9402       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9403            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9404                                   APInt::getHighBitsSet(OpBits,
9405                                                         OpBits-PromBits))) ||
9406           (N->getOpcode() == ISD::SIGN_EXTEND &&
9407            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9408              (OpBits-(PromBits-1)))) {
9409         ReallyNeedsExt = true;
9410         break;
9411       }
9412     }
9413   }
9414
9415   // Replace all inputs, either with the truncation operand, or a
9416   // truncation or extension to the final output type.
9417   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9418     // Constant inputs need to be replaced with the to-be-promoted nodes that
9419     // use them because they might have users outside of the cluster of
9420     // promoted nodes.
9421     if (isa<ConstantSDNode>(Inputs[i]))
9422       continue;
9423
9424     SDValue InSrc = Inputs[i].getOperand(0);
9425     if (Inputs[i].getValueType() == N->getValueType(0))
9426       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9427     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9428       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9429         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9430     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9431       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9432         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9433     else
9434       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9435         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9436   }
9437
9438   // Replace all operations (these are all the same, but have a different
9439   // (promoted) return type). DAG.getNode will validate that the types of
9440   // a binary operator match, so go through the list in reverse so that
9441   // we've likely promoted both operands first.
9442   while (!PromOps.empty()) {
9443     SDValue PromOp = PromOps.back();
9444     PromOps.pop_back();
9445
9446     unsigned C;
9447     switch (PromOp.getOpcode()) {
9448     default:             C = 0; break;
9449     case ISD::SELECT:    C = 1; break;
9450     case ISD::SELECT_CC: C = 2; break;
9451     }
9452
9453     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9454          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9455         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9456          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9457       // The to-be-promoted operands of this node have not yet been
9458       // promoted (this should be rare because we're going through the
9459       // list backward, but if one of the operands has several users in
9460       // this cluster of to-be-promoted nodes, it is possible).
9461       PromOps.insert(PromOps.begin(), PromOp);
9462       continue;
9463     }
9464
9465     // For SELECT and SELECT_CC nodes, we do a similar check for any
9466     // to-be-promoted comparison inputs.
9467     if (PromOp.getOpcode() == ISD::SELECT ||
9468         PromOp.getOpcode() == ISD::SELECT_CC) {
9469       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9470            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9471           (SelectTruncOp[1].count(PromOp.getNode()) &&
9472            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9473         PromOps.insert(PromOps.begin(), PromOp);
9474         continue;
9475       }
9476     }
9477
9478     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9479                                 PromOp.getNode()->op_end());
9480
9481     // If this node has constant inputs, then they'll need to be promoted here.
9482     for (unsigned i = 0; i < 2; ++i) {
9483       if (!isa<ConstantSDNode>(Ops[C+i]))
9484         continue;
9485       if (Ops[C+i].getValueType() == N->getValueType(0))
9486         continue;
9487
9488       if (N->getOpcode() == ISD::SIGN_EXTEND)
9489         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9490       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9491         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9492       else
9493         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9494     }
9495
9496     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9497     // truncate them again to the original value type.
9498     if (PromOp.getOpcode() == ISD::SELECT ||
9499         PromOp.getOpcode() == ISD::SELECT_CC) {
9500       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9501       if (SI0 != SelectTruncOp[0].end())
9502         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9503       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9504       if (SI1 != SelectTruncOp[1].end())
9505         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9506     }
9507
9508     DAG.ReplaceAllUsesOfValueWith(PromOp,
9509       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9510   }
9511
9512   // Now we're left with the initial extension itself.
9513   if (!ReallyNeedsExt)
9514     return N->getOperand(0);
9515
9516   // To zero extend, just mask off everything except for the first bit (in the
9517   // i1 case).
9518   if (N->getOpcode() == ISD::ZERO_EXTEND)
9519     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9520                        DAG.getConstant(APInt::getLowBitsSet(
9521                                          N->getValueSizeInBits(0), PromBits),
9522                                        N->getValueType(0)));
9523
9524   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9525          "Invalid extension type");
9526   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9527   SDValue ShiftCst =
9528     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9529   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9530                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9531                                  N->getOperand(0), ShiftCst), ShiftCst);
9532 }
9533
9534 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9535                                               DAGCombinerInfo &DCI) const {
9536   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9537           N->getOpcode() == ISD::UINT_TO_FP) &&
9538          "Need an int -> FP conversion node here");
9539
9540   if (!Subtarget.has64BitSupport())
9541     return SDValue();
9542
9543   SelectionDAG &DAG = DCI.DAG;
9544   SDLoc dl(N);
9545   SDValue Op(N, 0);
9546
9547   // Don't handle ppc_fp128 here or i1 conversions.
9548   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9549     return SDValue();
9550   if (Op.getOperand(0).getValueType() == MVT::i1)
9551     return SDValue();
9552
9553   // For i32 intermediate values, unfortunately, the conversion functions
9554   // leave the upper 32 bits of the value are undefined. Within the set of
9555   // scalar instructions, we have no method for zero- or sign-extending the
9556   // value. Thus, we cannot handle i32 intermediate values here.
9557   if (Op.getOperand(0).getValueType() == MVT::i32)
9558     return SDValue();
9559
9560   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9561          "UINT_TO_FP is supported only with FPCVT");
9562
9563   // If we have FCFIDS, then use it when converting to single-precision.
9564   // Otherwise, convert to double-precision and then round.
9565   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9566                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9567                                                             : PPCISD::FCFIDS)
9568                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9569                                                             : PPCISD::FCFID);
9570   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9571                   ? MVT::f32
9572                   : MVT::f64;
9573
9574   // If we're converting from a float, to an int, and back to a float again,
9575   // then we don't need the store/load pair at all.
9576   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9577        Subtarget.hasFPCVT()) ||
9578       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9579     SDValue Src = Op.getOperand(0).getOperand(0);
9580     if (Src.getValueType() == MVT::f32) {
9581       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9582       DCI.AddToWorklist(Src.getNode());
9583     }
9584
9585     unsigned FCTOp =
9586       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9587                                                         PPCISD::FCTIDUZ;
9588
9589     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9590     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9591
9592     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9593       FP = DAG.getNode(ISD::FP_ROUND, dl,
9594                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9595       DCI.AddToWorklist(FP.getNode());
9596     }
9597
9598     return FP;
9599   }
9600
9601   return SDValue();
9602 }
9603
9604 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9605 // builtins) into loads with swaps.
9606 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9607                                               DAGCombinerInfo &DCI) const {
9608   SelectionDAG &DAG = DCI.DAG;
9609   SDLoc dl(N);
9610   SDValue Chain;
9611   SDValue Base;
9612   MachineMemOperand *MMO;
9613
9614   switch (N->getOpcode()) {
9615   default:
9616     llvm_unreachable("Unexpected opcode for little endian VSX load");
9617   case ISD::LOAD: {
9618     LoadSDNode *LD = cast<LoadSDNode>(N);
9619     Chain = LD->getChain();
9620     Base = LD->getBasePtr();
9621     MMO = LD->getMemOperand();
9622     // If the MMO suggests this isn't a load of a full vector, leave
9623     // things alone.  For a built-in, we have to make the change for
9624     // correctness, so if there is a size problem that will be a bug.
9625     if (MMO->getSize() < 16)
9626       return SDValue();
9627     break;
9628   }
9629   case ISD::INTRINSIC_W_CHAIN: {
9630     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9631     Chain = Intrin->getChain();
9632     Base = Intrin->getBasePtr();
9633     MMO = Intrin->getMemOperand();
9634     break;
9635   }
9636   }
9637
9638   MVT VecTy = N->getValueType(0).getSimpleVT();
9639   SDValue LoadOps[] = { Chain, Base };
9640   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9641                                          DAG.getVTList(VecTy, MVT::Other),
9642                                          LoadOps, VecTy, MMO);
9643   DCI.AddToWorklist(Load.getNode());
9644   Chain = Load.getValue(1);
9645   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9646                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9647   DCI.AddToWorklist(Swap.getNode());
9648   return Swap;
9649 }
9650
9651 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9652 // builtins) into stores with swaps.
9653 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9654                                                DAGCombinerInfo &DCI) const {
9655   SelectionDAG &DAG = DCI.DAG;
9656   SDLoc dl(N);
9657   SDValue Chain;
9658   SDValue Base;
9659   unsigned SrcOpnd;
9660   MachineMemOperand *MMO;
9661
9662   switch (N->getOpcode()) {
9663   default:
9664     llvm_unreachable("Unexpected opcode for little endian VSX store");
9665   case ISD::STORE: {
9666     StoreSDNode *ST = cast<StoreSDNode>(N);
9667     Chain = ST->getChain();
9668     Base = ST->getBasePtr();
9669     MMO = ST->getMemOperand();
9670     SrcOpnd = 1;
9671     // If the MMO suggests this isn't a store of a full vector, leave
9672     // things alone.  For a built-in, we have to make the change for
9673     // correctness, so if there is a size problem that will be a bug.
9674     if (MMO->getSize() < 16)
9675       return SDValue();
9676     break;
9677   }
9678   case ISD::INTRINSIC_VOID: {
9679     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9680     Chain = Intrin->getChain();
9681     // Intrin->getBasePtr() oddly does not get what we want.
9682     Base = Intrin->getOperand(3);
9683     MMO = Intrin->getMemOperand();
9684     SrcOpnd = 2;
9685     break;
9686   }
9687   }
9688
9689   SDValue Src = N->getOperand(SrcOpnd);
9690   MVT VecTy = Src.getValueType().getSimpleVT();
9691   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9692                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9693   DCI.AddToWorklist(Swap.getNode());
9694   Chain = Swap.getValue(1);
9695   SDValue StoreOps[] = { Chain, Swap, Base };
9696   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9697                                           DAG.getVTList(MVT::Other),
9698                                           StoreOps, VecTy, MMO);
9699   DCI.AddToWorklist(Store.getNode());
9700   return Store;
9701 }
9702
9703 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9704                                              DAGCombinerInfo &DCI) const {
9705   SelectionDAG &DAG = DCI.DAG;
9706   SDLoc dl(N);
9707   switch (N->getOpcode()) {
9708   default: break;
9709   case PPCISD::SHL:
9710     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9711       if (C->isNullValue())   // 0 << V -> 0.
9712         return N->getOperand(0);
9713     }
9714     break;
9715   case PPCISD::SRL:
9716     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9717       if (C->isNullValue())   // 0 >>u V -> 0.
9718         return N->getOperand(0);
9719     }
9720     break;
9721   case PPCISD::SRA:
9722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9723       if (C->isNullValue() ||   //  0 >>s V -> 0.
9724           C->isAllOnesValue())    // -1 >>s V -> -1.
9725         return N->getOperand(0);
9726     }
9727     break;
9728   case ISD::SIGN_EXTEND:
9729   case ISD::ZERO_EXTEND:
9730   case ISD::ANY_EXTEND: 
9731     return DAGCombineExtBoolTrunc(N, DCI);
9732   case ISD::TRUNCATE:
9733   case ISD::SETCC:
9734   case ISD::SELECT_CC:
9735     return DAGCombineTruncBoolExt(N, DCI);
9736   case ISD::SINT_TO_FP:
9737   case ISD::UINT_TO_FP:
9738     return combineFPToIntToFP(N, DCI);
9739   case ISD::STORE: {
9740     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9741     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9742         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9743         N->getOperand(1).getValueType() == MVT::i32 &&
9744         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9745       SDValue Val = N->getOperand(1).getOperand(0);
9746       if (Val.getValueType() == MVT::f32) {
9747         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9748         DCI.AddToWorklist(Val.getNode());
9749       }
9750       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9751       DCI.AddToWorklist(Val.getNode());
9752
9753       SDValue Ops[] = {
9754         N->getOperand(0), Val, N->getOperand(2),
9755         DAG.getValueType(N->getOperand(1).getValueType())
9756       };
9757
9758       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9759               DAG.getVTList(MVT::Other), Ops,
9760               cast<StoreSDNode>(N)->getMemoryVT(),
9761               cast<StoreSDNode>(N)->getMemOperand());
9762       DCI.AddToWorklist(Val.getNode());
9763       return Val;
9764     }
9765
9766     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9767     if (cast<StoreSDNode>(N)->isUnindexed() &&
9768         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9769         N->getOperand(1).getNode()->hasOneUse() &&
9770         (N->getOperand(1).getValueType() == MVT::i32 ||
9771          N->getOperand(1).getValueType() == MVT::i16 ||
9772          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9773           N->getOperand(1).getValueType() == MVT::i64))) {
9774       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9775       // Do an any-extend to 32-bits if this is a half-word input.
9776       if (BSwapOp.getValueType() == MVT::i16)
9777         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9778
9779       SDValue Ops[] = {
9780         N->getOperand(0), BSwapOp, N->getOperand(2),
9781         DAG.getValueType(N->getOperand(1).getValueType())
9782       };
9783       return
9784         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9785                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9786                                 cast<StoreSDNode>(N)->getMemOperand());
9787     }
9788
9789     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9790     EVT VT = N->getOperand(1).getValueType();
9791     if (VT.isSimple()) {
9792       MVT StoreVT = VT.getSimpleVT();
9793       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9794           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9795            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9796         return expandVSXStoreForLE(N, DCI);
9797     }
9798     break;
9799   }
9800   case ISD::LOAD: {
9801     LoadSDNode *LD = cast<LoadSDNode>(N);
9802     EVT VT = LD->getValueType(0);
9803
9804     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9805     if (VT.isSimple()) {
9806       MVT LoadVT = VT.getSimpleVT();
9807       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9808           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9809            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9810         return expandVSXLoadForLE(N, DCI);
9811     }
9812
9813     EVT MemVT = LD->getMemoryVT();
9814     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9815     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9816     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9817     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9818     if (LD->isUnindexed() && VT.isVector() &&
9819         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9820           // P8 and later hardware should just use LOAD.
9821           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9822                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9823          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9824           LD->getAlignment() >= ScalarABIAlignment)) &&
9825         LD->getAlignment() < ABIAlignment) {
9826       // This is a type-legal unaligned Altivec or QPX load.
9827       SDValue Chain = LD->getChain();
9828       SDValue Ptr = LD->getBasePtr();
9829       bool isLittleEndian = Subtarget.isLittleEndian();
9830
9831       // This implements the loading of unaligned vectors as described in
9832       // the venerable Apple Velocity Engine overview. Specifically:
9833       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9834       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9835       //
9836       // The general idea is to expand a sequence of one or more unaligned
9837       // loads into an alignment-based permutation-control instruction (lvsl
9838       // or lvsr), a series of regular vector loads (which always truncate
9839       // their input address to an aligned address), and a series of
9840       // permutations.  The results of these permutations are the requested
9841       // loaded values.  The trick is that the last "extra" load is not taken
9842       // from the address you might suspect (sizeof(vector) bytes after the
9843       // last requested load), but rather sizeof(vector) - 1 bytes after the
9844       // last requested vector. The point of this is to avoid a page fault if
9845       // the base address happened to be aligned. This works because if the
9846       // base address is aligned, then adding less than a full vector length
9847       // will cause the last vector in the sequence to be (re)loaded.
9848       // Otherwise, the next vector will be fetched as you might suspect was
9849       // necessary.
9850
9851       // We might be able to reuse the permutation generation from
9852       // a different base address offset from this one by an aligned amount.
9853       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9854       // optimization later.
9855       Intrinsic::ID Intr, IntrLD, IntrPerm;
9856       MVT PermCntlTy, PermTy, LDTy;
9857       if (Subtarget.hasAltivec()) {
9858         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
9859                                  Intrinsic::ppc_altivec_lvsl;
9860         IntrLD = Intrinsic::ppc_altivec_lvx;
9861         IntrPerm = Intrinsic::ppc_altivec_vperm;
9862         PermCntlTy = MVT::v16i8;
9863         PermTy = MVT::v4i32;
9864         LDTy = MVT::v4i32;
9865       } else {
9866         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9867                                        Intrinsic::ppc_qpx_qvlpcls;
9868         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9869                                        Intrinsic::ppc_qpx_qvlfs;
9870         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9871         PermCntlTy = MVT::v4f64;
9872         PermTy = MVT::v4f64;
9873         LDTy = MemVT.getSimpleVT();
9874       }
9875
9876       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9877
9878       // Create the new MMO for the new base load. It is like the original MMO,
9879       // but represents an area in memory almost twice the vector size centered
9880       // on the original address. If the address is unaligned, we might start
9881       // reading up to (sizeof(vector)-1) bytes below the address of the
9882       // original unaligned load.
9883       MachineFunction &MF = DAG.getMachineFunction();
9884       MachineMemOperand *BaseMMO =
9885         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9886                                 2*MemVT.getStoreSize()-1);
9887
9888       // Create the new base load.
9889       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9890       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9891       SDValue BaseLoad =
9892         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9893                                 DAG.getVTList(PermTy, MVT::Other),
9894                                 BaseLoadOps, LDTy, BaseMMO);
9895
9896       // Note that the value of IncOffset (which is provided to the next
9897       // load's pointer info offset value, and thus used to calculate the
9898       // alignment), and the value of IncValue (which is actually used to
9899       // increment the pointer value) are different! This is because we
9900       // require the next load to appear to be aligned, even though it
9901       // is actually offset from the base pointer by a lesser amount.
9902       int IncOffset = VT.getSizeInBits() / 8;
9903       int IncValue = IncOffset;
9904
9905       // Walk (both up and down) the chain looking for another load at the real
9906       // (aligned) offset (the alignment of the other load does not matter in
9907       // this case). If found, then do not use the offset reduction trick, as
9908       // that will prevent the loads from being later combined (as they would
9909       // otherwise be duplicates).
9910       if (!findConsecutiveLoad(LD, DAG))
9911         --IncValue;
9912
9913       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9914       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9915
9916       MachineMemOperand *ExtraMMO =
9917         MF.getMachineMemOperand(LD->getMemOperand(),
9918                                 1, 2*MemVT.getStoreSize()-1);
9919       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9920       SDValue ExtraLoad =
9921         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9922                                 DAG.getVTList(PermTy, MVT::Other),
9923                                 ExtraLoadOps, LDTy, ExtraMMO);
9924
9925       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9926         BaseLoad.getValue(1), ExtraLoad.getValue(1));
9927
9928       // Because vperm has a big-endian bias, we must reverse the order
9929       // of the input vectors and complement the permute control vector
9930       // when generating little endian code.  We have already handled the
9931       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9932       // and ExtraLoad here.
9933       SDValue Perm;
9934       if (isLittleEndian)
9935         Perm = BuildIntrinsicOp(IntrPerm,
9936                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9937       else
9938         Perm = BuildIntrinsicOp(IntrPerm,
9939                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9940
9941       if (VT != PermTy)
9942         Perm = Subtarget.hasAltivec() ?
9943                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
9944                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
9945                                DAG.getTargetConstant(1, MVT::i64));
9946                                // second argument is 1 because this rounding
9947                                // is always exact.
9948
9949       // The output of the permutation is our loaded result, the TokenFactor is
9950       // our new chain.
9951       DCI.CombineTo(N, Perm, TF);
9952       return SDValue(N, 0);
9953     }
9954     }
9955     break;
9956     case ISD::INTRINSIC_WO_CHAIN: {
9957       bool isLittleEndian = Subtarget.isLittleEndian();
9958       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9959       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9960                                            : Intrinsic::ppc_altivec_lvsl);
9961       if ((IID == Intr ||
9962            IID == Intrinsic::ppc_qpx_qvlpcld  ||
9963            IID == Intrinsic::ppc_qpx_qvlpcls) &&
9964         N->getOperand(1)->getOpcode() == ISD::ADD) {
9965         SDValue Add = N->getOperand(1);
9966
9967         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
9968                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
9969
9970         if (DAG.MaskedValueIsZero(
9971                 Add->getOperand(1),
9972                 APInt::getAllOnesValue(Bits /* alignment */)
9973                     .zext(
9974                         Add.getValueType().getScalarType().getSizeInBits()))) {
9975           SDNode *BasePtr = Add->getOperand(0).getNode();
9976           for (SDNode::use_iterator UI = BasePtr->use_begin(),
9977                                     UE = BasePtr->use_end();
9978                UI != UE; ++UI) {
9979             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9980                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
9981               // We've found another LVSL/LVSR, and this address is an aligned
9982               // multiple of that one. The results will be the same, so use the
9983               // one we've just found instead.
9984
9985               return SDValue(*UI, 0);
9986             }
9987           }
9988         }
9989
9990         if (isa<ConstantSDNode>(Add->getOperand(1))) {
9991           SDNode *BasePtr = Add->getOperand(0).getNode();
9992           for (SDNode::use_iterator UI = BasePtr->use_begin(),
9993                UE = BasePtr->use_end(); UI != UE; ++UI) {
9994             if (UI->getOpcode() == ISD::ADD &&
9995                 isa<ConstantSDNode>(UI->getOperand(1)) &&
9996                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
9997                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
9998                 (1ULL << Bits) == 0) {
9999               SDNode *OtherAdd = *UI;
10000               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10001                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10002                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10003                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10004                   return SDValue(*VI, 0);
10005                 }
10006               }
10007             }
10008           }
10009         }
10010       }
10011     }
10012
10013     break;
10014   case ISD::INTRINSIC_W_CHAIN: {
10015     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10016     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10017       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10018       default:
10019         break;
10020       case Intrinsic::ppc_vsx_lxvw4x:
10021       case Intrinsic::ppc_vsx_lxvd2x:
10022         return expandVSXLoadForLE(N, DCI);
10023       }
10024     }
10025     break;
10026   }
10027   case ISD::INTRINSIC_VOID: {
10028     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10029     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10030       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10031       default:
10032         break;
10033       case Intrinsic::ppc_vsx_stxvw4x:
10034       case Intrinsic::ppc_vsx_stxvd2x:
10035         return expandVSXStoreForLE(N, DCI);
10036       }
10037     }
10038     break;
10039   }
10040   case ISD::BSWAP:
10041     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10042     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10043         N->getOperand(0).hasOneUse() &&
10044         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10045          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10046           N->getValueType(0) == MVT::i64))) {
10047       SDValue Load = N->getOperand(0);
10048       LoadSDNode *LD = cast<LoadSDNode>(Load);
10049       // Create the byte-swapping load.
10050       SDValue Ops[] = {
10051         LD->getChain(),    // Chain
10052         LD->getBasePtr(),  // Ptr
10053         DAG.getValueType(N->getValueType(0)) // VT
10054       };
10055       SDValue BSLoad =
10056         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10057                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10058                                               MVT::i64 : MVT::i32, MVT::Other),
10059                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10060
10061       // If this is an i16 load, insert the truncate.
10062       SDValue ResVal = BSLoad;
10063       if (N->getValueType(0) == MVT::i16)
10064         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10065
10066       // First, combine the bswap away.  This makes the value produced by the
10067       // load dead.
10068       DCI.CombineTo(N, ResVal);
10069
10070       // Next, combine the load away, we give it a bogus result value but a real
10071       // chain result.  The result value is dead because the bswap is dead.
10072       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10073
10074       // Return N so it doesn't get rechecked!
10075       return SDValue(N, 0);
10076     }
10077
10078     break;
10079   case PPCISD::VCMP: {
10080     // If a VCMPo node already exists with exactly the same operands as this
10081     // node, use its result instead of this node (VCMPo computes both a CR6 and
10082     // a normal output).
10083     //
10084     if (!N->getOperand(0).hasOneUse() &&
10085         !N->getOperand(1).hasOneUse() &&
10086         !N->getOperand(2).hasOneUse()) {
10087
10088       // Scan all of the users of the LHS, looking for VCMPo's that match.
10089       SDNode *VCMPoNode = nullptr;
10090
10091       SDNode *LHSN = N->getOperand(0).getNode();
10092       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10093            UI != E; ++UI)
10094         if (UI->getOpcode() == PPCISD::VCMPo &&
10095             UI->getOperand(1) == N->getOperand(1) &&
10096             UI->getOperand(2) == N->getOperand(2) &&
10097             UI->getOperand(0) == N->getOperand(0)) {
10098           VCMPoNode = *UI;
10099           break;
10100         }
10101
10102       // If there is no VCMPo node, or if the flag value has a single use, don't
10103       // transform this.
10104       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10105         break;
10106
10107       // Look at the (necessarily single) use of the flag value.  If it has a
10108       // chain, this transformation is more complex.  Note that multiple things
10109       // could use the value result, which we should ignore.
10110       SDNode *FlagUser = nullptr;
10111       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10112            FlagUser == nullptr; ++UI) {
10113         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10114         SDNode *User = *UI;
10115         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10116           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10117             FlagUser = User;
10118             break;
10119           }
10120         }
10121       }
10122
10123       // If the user is a MFOCRF instruction, we know this is safe.
10124       // Otherwise we give up for right now.
10125       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10126         return SDValue(VCMPoNode, 0);
10127     }
10128     break;
10129   }
10130   case ISD::BRCOND: {
10131     SDValue Cond = N->getOperand(1);
10132     SDValue Target = N->getOperand(2);
10133  
10134     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10135         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10136           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10137
10138       // We now need to make the intrinsic dead (it cannot be instruction
10139       // selected).
10140       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10141       assert(Cond.getNode()->hasOneUse() &&
10142              "Counter decrement has more than one use");
10143
10144       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10145                          N->getOperand(0), Target);
10146     }
10147   }
10148   break;
10149   case ISD::BR_CC: {
10150     // If this is a branch on an altivec predicate comparison, lower this so
10151     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10152     // lowering is done pre-legalize, because the legalizer lowers the predicate
10153     // compare down to code that is difficult to reassemble.
10154     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10155     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10156
10157     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10158     // value. If so, pass-through the AND to get to the intrinsic.
10159     if (LHS.getOpcode() == ISD::AND &&
10160         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10161         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10162           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10163         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10164         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10165           isZero())
10166       LHS = LHS.getOperand(0);
10167
10168     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10169         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10170           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10171         isa<ConstantSDNode>(RHS)) {
10172       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10173              "Counter decrement comparison is not EQ or NE");
10174
10175       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10176       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10177                     (CC == ISD::SETNE && !Val);
10178
10179       // We now need to make the intrinsic dead (it cannot be instruction
10180       // selected).
10181       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10182       assert(LHS.getNode()->hasOneUse() &&
10183              "Counter decrement has more than one use");
10184
10185       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10186                          N->getOperand(0), N->getOperand(4));
10187     }
10188
10189     int CompareOpc;
10190     bool isDot;
10191
10192     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10193         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10194         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
10195       assert(isDot && "Can't compare against a vector result!");
10196
10197       // If this is a comparison against something other than 0/1, then we know
10198       // that the condition is never/always true.
10199       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10200       if (Val != 0 && Val != 1) {
10201         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10202           return N->getOperand(0);
10203         // Always !=, turn it into an unconditional branch.
10204         return DAG.getNode(ISD::BR, dl, MVT::Other,
10205                            N->getOperand(0), N->getOperand(4));
10206       }
10207
10208       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10209
10210       // Create the PPCISD altivec 'dot' comparison node.
10211       SDValue Ops[] = {
10212         LHS.getOperand(2),  // LHS of compare
10213         LHS.getOperand(3),  // RHS of compare
10214         DAG.getConstant(CompareOpc, MVT::i32)
10215       };
10216       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10217       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10218
10219       // Unpack the result based on how the target uses it.
10220       PPC::Predicate CompOpc;
10221       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10222       default:  // Can't happen, don't crash on invalid number though.
10223       case 0:   // Branch on the value of the EQ bit of CR6.
10224         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10225         break;
10226       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10227         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10228         break;
10229       case 2:   // Branch on the value of the LT bit of CR6.
10230         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10231         break;
10232       case 3:   // Branch on the inverted value of the LT bit of CR6.
10233         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10234         break;
10235       }
10236
10237       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10238                          DAG.getConstant(CompOpc, MVT::i32),
10239                          DAG.getRegister(PPC::CR6, MVT::i32),
10240                          N->getOperand(4), CompNode.getValue(1));
10241     }
10242     break;
10243   }
10244   }
10245
10246   return SDValue();
10247 }
10248
10249 SDValue
10250 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10251                                   SelectionDAG &DAG,
10252                                   std::vector<SDNode *> *Created) const {
10253   // fold (sdiv X, pow2)
10254   EVT VT = N->getValueType(0);
10255   if (VT == MVT::i64 && !Subtarget.isPPC64())
10256     return SDValue();
10257   if ((VT != MVT::i32 && VT != MVT::i64) ||
10258       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10259     return SDValue();
10260
10261   SDLoc DL(N);
10262   SDValue N0 = N->getOperand(0);
10263
10264   bool IsNegPow2 = (-Divisor).isPowerOf2();
10265   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10266   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10267
10268   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10269   if (Created)
10270     Created->push_back(Op.getNode());
10271
10272   if (IsNegPow2) {
10273     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10274     if (Created)
10275       Created->push_back(Op.getNode());
10276   }
10277
10278   return Op;
10279 }
10280
10281 //===----------------------------------------------------------------------===//
10282 // Inline Assembly Support
10283 //===----------------------------------------------------------------------===//
10284
10285 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10286                                                       APInt &KnownZero,
10287                                                       APInt &KnownOne,
10288                                                       const SelectionDAG &DAG,
10289                                                       unsigned Depth) const {
10290   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10291   switch (Op.getOpcode()) {
10292   default: break;
10293   case PPCISD::LBRX: {
10294     // lhbrx is known to have the top bits cleared out.
10295     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10296       KnownZero = 0xFFFF0000;
10297     break;
10298   }
10299   case ISD::INTRINSIC_WO_CHAIN: {
10300     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10301     default: break;
10302     case Intrinsic::ppc_altivec_vcmpbfp_p:
10303     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10304     case Intrinsic::ppc_altivec_vcmpequb_p:
10305     case Intrinsic::ppc_altivec_vcmpequh_p:
10306     case Intrinsic::ppc_altivec_vcmpequw_p:
10307     case Intrinsic::ppc_altivec_vcmpgefp_p:
10308     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10309     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10310     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10311     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10312     case Intrinsic::ppc_altivec_vcmpgtub_p:
10313     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10314     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10315       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10316       break;
10317     }
10318   }
10319   }
10320 }
10321
10322 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10323   switch (Subtarget.getDarwinDirective()) {
10324   default: break;
10325   case PPC::DIR_970:
10326   case PPC::DIR_PWR4:
10327   case PPC::DIR_PWR5:
10328   case PPC::DIR_PWR5X:
10329   case PPC::DIR_PWR6:
10330   case PPC::DIR_PWR6X:
10331   case PPC::DIR_PWR7:
10332   case PPC::DIR_PWR8: {
10333     if (!ML)
10334       break;
10335
10336     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10337
10338     // For small loops (between 5 and 8 instructions), align to a 32-byte
10339     // boundary so that the entire loop fits in one instruction-cache line.
10340     uint64_t LoopSize = 0;
10341     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10342       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10343         LoopSize += TII->GetInstSizeInBytes(J);
10344
10345     if (LoopSize > 16 && LoopSize <= 32)
10346       return 5;
10347
10348     break;
10349   }
10350   }
10351
10352   return TargetLowering::getPrefLoopAlignment(ML);
10353 }
10354
10355 /// getConstraintType - Given a constraint, return the type of
10356 /// constraint it is for this target.
10357 PPCTargetLowering::ConstraintType
10358 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10359   if (Constraint.size() == 1) {
10360     switch (Constraint[0]) {
10361     default: break;
10362     case 'b':
10363     case 'r':
10364     case 'f':
10365     case 'v':
10366     case 'y':
10367       return C_RegisterClass;
10368     case 'Z':
10369       // FIXME: While Z does indicate a memory constraint, it specifically
10370       // indicates an r+r address (used in conjunction with the 'y' modifier
10371       // in the replacement string). Currently, we're forcing the base
10372       // register to be r0 in the asm printer (which is interpreted as zero)
10373       // and forming the complete address in the second register. This is
10374       // suboptimal.
10375       return C_Memory;
10376     }
10377   } else if (Constraint == "wc") { // individual CR bits.
10378     return C_RegisterClass;
10379   } else if (Constraint == "wa" || Constraint == "wd" ||
10380              Constraint == "wf" || Constraint == "ws") {
10381     return C_RegisterClass; // VSX registers.
10382   }
10383   return TargetLowering::getConstraintType(Constraint);
10384 }
10385
10386 /// Examine constraint type and operand type and determine a weight value.
10387 /// This object must already have been set up with the operand type
10388 /// and the current alternative constraint selected.
10389 TargetLowering::ConstraintWeight
10390 PPCTargetLowering::getSingleConstraintMatchWeight(
10391     AsmOperandInfo &info, const char *constraint) const {
10392   ConstraintWeight weight = CW_Invalid;
10393   Value *CallOperandVal = info.CallOperandVal;
10394     // If we don't have a value, we can't do a match,
10395     // but allow it at the lowest weight.
10396   if (!CallOperandVal)
10397     return CW_Default;
10398   Type *type = CallOperandVal->getType();
10399
10400   // Look at the constraint type.
10401   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10402     return CW_Register; // an individual CR bit.
10403   else if ((StringRef(constraint) == "wa" ||
10404             StringRef(constraint) == "wd" ||
10405             StringRef(constraint) == "wf") &&
10406            type->isVectorTy())
10407     return CW_Register;
10408   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10409     return CW_Register;
10410
10411   switch (*constraint) {
10412   default:
10413     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10414     break;
10415   case 'b':
10416     if (type->isIntegerTy())
10417       weight = CW_Register;
10418     break;
10419   case 'f':
10420     if (type->isFloatTy())
10421       weight = CW_Register;
10422     break;
10423   case 'd':
10424     if (type->isDoubleTy())
10425       weight = CW_Register;
10426     break;
10427   case 'v':
10428     if (type->isVectorTy())
10429       weight = CW_Register;
10430     break;
10431   case 'y':
10432     weight = CW_Register;
10433     break;
10434   case 'Z':
10435     weight = CW_Memory;
10436     break;
10437   }
10438   return weight;
10439 }
10440
10441 std::pair<unsigned, const TargetRegisterClass *>
10442 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10443                                                 const std::string &Constraint,
10444                                                 MVT VT) const {
10445   if (Constraint.size() == 1) {
10446     // GCC RS6000 Constraint Letters
10447     switch (Constraint[0]) {
10448     case 'b':   // R1-R31
10449       if (VT == MVT::i64 && Subtarget.isPPC64())
10450         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10451       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10452     case 'r':   // R0-R31
10453       if (VT == MVT::i64 && Subtarget.isPPC64())
10454         return std::make_pair(0U, &PPC::G8RCRegClass);
10455       return std::make_pair(0U, &PPC::GPRCRegClass);
10456     case 'f':
10457       if (VT == MVT::f32 || VT == MVT::i32)
10458         return std::make_pair(0U, &PPC::F4RCRegClass);
10459       if (VT == MVT::f64 || VT == MVT::i64)
10460         return std::make_pair(0U, &PPC::F8RCRegClass);
10461       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10462         return std::make_pair(0U, &PPC::QFRCRegClass);
10463       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10464         return std::make_pair(0U, &PPC::QSRCRegClass);
10465       break;
10466     case 'v':
10467       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10468         return std::make_pair(0U, &PPC::QFRCRegClass);
10469       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10470         return std::make_pair(0U, &PPC::QSRCRegClass);
10471       return std::make_pair(0U, &PPC::VRRCRegClass);
10472     case 'y':   // crrc
10473       return std::make_pair(0U, &PPC::CRRCRegClass);
10474     }
10475   } else if (Constraint == "wc") { // an individual CR bit.
10476     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10477   } else if (Constraint == "wa" || Constraint == "wd" ||
10478              Constraint == "wf") {
10479     return std::make_pair(0U, &PPC::VSRCRegClass);
10480   } else if (Constraint == "ws") {
10481     return std::make_pair(0U, &PPC::VSFRCRegClass);
10482   }
10483
10484   std::pair<unsigned, const TargetRegisterClass *> R =
10485       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10486
10487   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10488   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10489   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10490   // register.
10491   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10492   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10493   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10494       PPC::GPRCRegClass.contains(R.first))
10495     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10496                             PPC::sub_32, &PPC::G8RCRegClass),
10497                           &PPC::G8RCRegClass);
10498
10499   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10500   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10501     R.first = PPC::CR0;
10502     R.second = &PPC::CRRCRegClass;
10503   }
10504
10505   return R;
10506 }
10507
10508
10509 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10510 /// vector.  If it is invalid, don't add anything to Ops.
10511 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10512                                                      std::string &Constraint,
10513                                                      std::vector<SDValue>&Ops,
10514                                                      SelectionDAG &DAG) const {
10515   SDValue Result;
10516
10517   // Only support length 1 constraints.
10518   if (Constraint.length() > 1) return;
10519
10520   char Letter = Constraint[0];
10521   switch (Letter) {
10522   default: break;
10523   case 'I':
10524   case 'J':
10525   case 'K':
10526   case 'L':
10527   case 'M':
10528   case 'N':
10529   case 'O':
10530   case 'P': {
10531     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10532     if (!CST) return; // Must be an immediate to match.
10533     int64_t Value = CST->getSExtValue();
10534     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10535                          // numbers are printed as such.
10536     switch (Letter) {
10537     default: llvm_unreachable("Unknown constraint letter!");
10538     case 'I':  // "I" is a signed 16-bit constant.
10539       if (isInt<16>(Value))
10540         Result = DAG.getTargetConstant(Value, TCVT);
10541       break;
10542     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10543       if (isShiftedUInt<16, 16>(Value))
10544         Result = DAG.getTargetConstant(Value, TCVT);
10545       break;
10546     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10547       if (isShiftedInt<16, 16>(Value))
10548         Result = DAG.getTargetConstant(Value, TCVT);
10549       break;
10550     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10551       if (isUInt<16>(Value))
10552         Result = DAG.getTargetConstant(Value, TCVT);
10553       break;
10554     case 'M':  // "M" is a constant that is greater than 31.
10555       if (Value > 31)
10556         Result = DAG.getTargetConstant(Value, TCVT);
10557       break;
10558     case 'N':  // "N" is a positive constant that is an exact power of two.
10559       if (Value > 0 && isPowerOf2_64(Value))
10560         Result = DAG.getTargetConstant(Value, TCVT);
10561       break;
10562     case 'O':  // "O" is the constant zero.
10563       if (Value == 0)
10564         Result = DAG.getTargetConstant(Value, TCVT);
10565       break;
10566     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10567       if (isInt<16>(-Value))
10568         Result = DAG.getTargetConstant(Value, TCVT);
10569       break;
10570     }
10571     break;
10572   }
10573   }
10574
10575   if (Result.getNode()) {
10576     Ops.push_back(Result);
10577     return;
10578   }
10579
10580   // Handle standard constraint letters.
10581   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10582 }
10583
10584 // isLegalAddressingMode - Return true if the addressing mode represented
10585 // by AM is legal for this target, for a load/store of the specified type.
10586 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10587                                               Type *Ty) const {
10588   // PPC does not allow r+i addressing modes for vectors!
10589   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10590     return false;
10591
10592   // PPC allows a sign-extended 16-bit immediate field.
10593   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10594     return false;
10595
10596   // No global is ever allowed as a base.
10597   if (AM.BaseGV)
10598     return false;
10599
10600   // PPC only support r+r,
10601   switch (AM.Scale) {
10602   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10603     break;
10604   case 1:
10605     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10606       return false;
10607     // Otherwise we have r+r or r+i.
10608     break;
10609   case 2:
10610     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10611       return false;
10612     // Allow 2*r as r+r.
10613     break;
10614   default:
10615     // No other scales are supported.
10616     return false;
10617   }
10618
10619   return true;
10620 }
10621
10622 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10623                                            SelectionDAG &DAG) const {
10624   MachineFunction &MF = DAG.getMachineFunction();
10625   MachineFrameInfo *MFI = MF.getFrameInfo();
10626   MFI->setReturnAddressIsTaken(true);
10627
10628   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10629     return SDValue();
10630
10631   SDLoc dl(Op);
10632   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10633
10634   // Make sure the function does not optimize away the store of the RA to
10635   // the stack.
10636   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10637   FuncInfo->setLRStoreRequired();
10638   bool isPPC64 = Subtarget.isPPC64();
10639
10640   if (Depth > 0) {
10641     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10642     SDValue Offset =
10643         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10644                         isPPC64 ? MVT::i64 : MVT::i32);
10645     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10646                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10647                                    FrameAddr, Offset),
10648                        MachinePointerInfo(), false, false, false, 0);
10649   }
10650
10651   // Just load the return address off the stack.
10652   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10653   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10654                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10655 }
10656
10657 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10658                                           SelectionDAG &DAG) const {
10659   SDLoc dl(Op);
10660   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10661
10662   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10663   bool isPPC64 = PtrVT == MVT::i64;
10664
10665   MachineFunction &MF = DAG.getMachineFunction();
10666   MachineFrameInfo *MFI = MF.getFrameInfo();
10667   MFI->setFrameAddressIsTaken(true);
10668
10669   // Naked functions never have a frame pointer, and so we use r1. For all
10670   // other functions, this decision must be delayed until during PEI.
10671   unsigned FrameReg;
10672   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10673     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10674   else
10675     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10676
10677   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10678                                          PtrVT);
10679   while (Depth--)
10680     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10681                             FrameAddr, MachinePointerInfo(), false, false,
10682                             false, 0);
10683   return FrameAddr;
10684 }
10685
10686 // FIXME? Maybe this could be a TableGen attribute on some registers and
10687 // this table could be generated automatically from RegInfo.
10688 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10689                                               EVT VT) const {
10690   bool isPPC64 = Subtarget.isPPC64();
10691   bool isDarwinABI = Subtarget.isDarwinABI();
10692
10693   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10694       (!isPPC64 && VT != MVT::i32))
10695     report_fatal_error("Invalid register global variable type");
10696
10697   bool is64Bit = isPPC64 && VT == MVT::i64;
10698   unsigned Reg = StringSwitch<unsigned>(RegName)
10699                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10700                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10701                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10702                                   (is64Bit ? PPC::X13 : PPC::R13))
10703                    .Default(0);
10704
10705   if (Reg)
10706     return Reg;
10707   report_fatal_error("Invalid register name global variable");
10708 }
10709
10710 bool
10711 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10712   // The PowerPC target isn't yet aware of offsets.
10713   return false;
10714 }
10715
10716 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10717                                            const CallInst &I,
10718                                            unsigned Intrinsic) const {
10719
10720   switch (Intrinsic) {
10721   case Intrinsic::ppc_qpx_qvlfd:
10722   case Intrinsic::ppc_qpx_qvlfs:
10723   case Intrinsic::ppc_qpx_qvlfcd:
10724   case Intrinsic::ppc_qpx_qvlfcs:
10725   case Intrinsic::ppc_qpx_qvlfiwa:
10726   case Intrinsic::ppc_qpx_qvlfiwz:
10727   case Intrinsic::ppc_altivec_lvx:
10728   case Intrinsic::ppc_altivec_lvxl:
10729   case Intrinsic::ppc_altivec_lvebx:
10730   case Intrinsic::ppc_altivec_lvehx:
10731   case Intrinsic::ppc_altivec_lvewx:
10732   case Intrinsic::ppc_vsx_lxvd2x:
10733   case Intrinsic::ppc_vsx_lxvw4x: {
10734     EVT VT;
10735     switch (Intrinsic) {
10736     case Intrinsic::ppc_altivec_lvebx:
10737       VT = MVT::i8;
10738       break;
10739     case Intrinsic::ppc_altivec_lvehx:
10740       VT = MVT::i16;
10741       break;
10742     case Intrinsic::ppc_altivec_lvewx:
10743       VT = MVT::i32;
10744       break;
10745     case Intrinsic::ppc_vsx_lxvd2x:
10746       VT = MVT::v2f64;
10747       break;
10748     case Intrinsic::ppc_qpx_qvlfd:
10749       VT = MVT::v4f64;
10750       break;
10751     case Intrinsic::ppc_qpx_qvlfs:
10752       VT = MVT::v4f32;
10753       break;
10754     case Intrinsic::ppc_qpx_qvlfcd:
10755       VT = MVT::v2f64;
10756       break;
10757     case Intrinsic::ppc_qpx_qvlfcs:
10758       VT = MVT::v2f32;
10759       break;
10760     default:
10761       VT = MVT::v4i32;
10762       break;
10763     }
10764
10765     Info.opc = ISD::INTRINSIC_W_CHAIN;
10766     Info.memVT = VT;
10767     Info.ptrVal = I.getArgOperand(0);
10768     Info.offset = -VT.getStoreSize()+1;
10769     Info.size = 2*VT.getStoreSize()-1;
10770     Info.align = 1;
10771     Info.vol = false;
10772     Info.readMem = true;
10773     Info.writeMem = false;
10774     return true;
10775   }
10776   case Intrinsic::ppc_qpx_qvlfda:
10777   case Intrinsic::ppc_qpx_qvlfsa:
10778   case Intrinsic::ppc_qpx_qvlfcda:
10779   case Intrinsic::ppc_qpx_qvlfcsa:
10780   case Intrinsic::ppc_qpx_qvlfiwaa:
10781   case Intrinsic::ppc_qpx_qvlfiwza: {
10782     EVT VT;
10783     switch (Intrinsic) {
10784     case Intrinsic::ppc_qpx_qvlfda:
10785       VT = MVT::v4f64;
10786       break;
10787     case Intrinsic::ppc_qpx_qvlfsa:
10788       VT = MVT::v4f32;
10789       break;
10790     case Intrinsic::ppc_qpx_qvlfcda:
10791       VT = MVT::v2f64;
10792       break;
10793     case Intrinsic::ppc_qpx_qvlfcsa:
10794       VT = MVT::v2f32;
10795       break;
10796     default:
10797       VT = MVT::v4i32;
10798       break;
10799     }
10800
10801     Info.opc = ISD::INTRINSIC_W_CHAIN;
10802     Info.memVT = VT;
10803     Info.ptrVal = I.getArgOperand(0);
10804     Info.offset = 0;
10805     Info.size = VT.getStoreSize();
10806     Info.align = 1;
10807     Info.vol = false;
10808     Info.readMem = true;
10809     Info.writeMem = false;
10810     return true;
10811   }
10812   case Intrinsic::ppc_qpx_qvstfd:
10813   case Intrinsic::ppc_qpx_qvstfs:
10814   case Intrinsic::ppc_qpx_qvstfcd:
10815   case Intrinsic::ppc_qpx_qvstfcs:
10816   case Intrinsic::ppc_qpx_qvstfiw:
10817   case Intrinsic::ppc_altivec_stvx:
10818   case Intrinsic::ppc_altivec_stvxl:
10819   case Intrinsic::ppc_altivec_stvebx:
10820   case Intrinsic::ppc_altivec_stvehx:
10821   case Intrinsic::ppc_altivec_stvewx:
10822   case Intrinsic::ppc_vsx_stxvd2x:
10823   case Intrinsic::ppc_vsx_stxvw4x: {
10824     EVT VT;
10825     switch (Intrinsic) {
10826     case Intrinsic::ppc_altivec_stvebx:
10827       VT = MVT::i8;
10828       break;
10829     case Intrinsic::ppc_altivec_stvehx:
10830       VT = MVT::i16;
10831       break;
10832     case Intrinsic::ppc_altivec_stvewx:
10833       VT = MVT::i32;
10834       break;
10835     case Intrinsic::ppc_vsx_stxvd2x:
10836       VT = MVT::v2f64;
10837       break;
10838     case Intrinsic::ppc_qpx_qvstfd:
10839       VT = MVT::v4f64;
10840       break;
10841     case Intrinsic::ppc_qpx_qvstfs:
10842       VT = MVT::v4f32;
10843       break;
10844     case Intrinsic::ppc_qpx_qvstfcd:
10845       VT = MVT::v2f64;
10846       break;
10847     case Intrinsic::ppc_qpx_qvstfcs:
10848       VT = MVT::v2f32;
10849       break;
10850     default:
10851       VT = MVT::v4i32;
10852       break;
10853     }
10854
10855     Info.opc = ISD::INTRINSIC_VOID;
10856     Info.memVT = VT;
10857     Info.ptrVal = I.getArgOperand(1);
10858     Info.offset = -VT.getStoreSize()+1;
10859     Info.size = 2*VT.getStoreSize()-1;
10860     Info.align = 1;
10861     Info.vol = false;
10862     Info.readMem = false;
10863     Info.writeMem = true;
10864     return true;
10865   }
10866   case Intrinsic::ppc_qpx_qvstfda:
10867   case Intrinsic::ppc_qpx_qvstfsa:
10868   case Intrinsic::ppc_qpx_qvstfcda:
10869   case Intrinsic::ppc_qpx_qvstfcsa:
10870   case Intrinsic::ppc_qpx_qvstfiwa: {
10871     EVT VT;
10872     switch (Intrinsic) {
10873     case Intrinsic::ppc_qpx_qvstfda:
10874       VT = MVT::v4f64;
10875       break;
10876     case Intrinsic::ppc_qpx_qvstfsa:
10877       VT = MVT::v4f32;
10878       break;
10879     case Intrinsic::ppc_qpx_qvstfcda:
10880       VT = MVT::v2f64;
10881       break;
10882     case Intrinsic::ppc_qpx_qvstfcsa:
10883       VT = MVT::v2f32;
10884       break;
10885     default:
10886       VT = MVT::v4i32;
10887       break;
10888     }
10889
10890     Info.opc = ISD::INTRINSIC_VOID;
10891     Info.memVT = VT;
10892     Info.ptrVal = I.getArgOperand(1);
10893     Info.offset = 0;
10894     Info.size = VT.getStoreSize();
10895     Info.align = 1;
10896     Info.vol = false;
10897     Info.readMem = false;
10898     Info.writeMem = true;
10899     return true;
10900   }
10901   default:
10902     break;
10903   }
10904
10905   return false;
10906 }
10907
10908 /// getOptimalMemOpType - Returns the target specific optimal type for load
10909 /// and store operations as a result of memset, memcpy, and memmove
10910 /// lowering. If DstAlign is zero that means it's safe to destination
10911 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
10912 /// means there isn't a need to check it against alignment requirement,
10913 /// probably because the source does not need to be loaded. If 'IsMemset' is
10914 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
10915 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
10916 /// source is constant so it does not need to be loaded.
10917 /// It returns EVT::Other if the type should be determined using generic
10918 /// target-independent logic.
10919 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
10920                                            unsigned DstAlign, unsigned SrcAlign,
10921                                            bool IsMemset, bool ZeroMemset,
10922                                            bool MemcpyStrSrc,
10923                                            MachineFunction &MF) const {
10924   const Function *F = MF.getFunction();
10925   // When expanding a memset, require at least two QPX instructions to cover
10926   // the cost of loading the value to be stored from the constant pool.
10927   if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
10928      (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
10929       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10930     return MVT::v4f64;
10931   }
10932
10933   // We should use Altivec/VSX loads and stores when available. For unaligned
10934   // addresses, unaligned VSX loads are only fast starting with the P8.
10935   if (Subtarget.hasAltivec() && Size >= 16 &&
10936       (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
10937        ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
10938     return MVT::v4i32;
10939
10940   if (Subtarget.isPPC64()) {
10941     return MVT::i64;
10942   }
10943
10944   return MVT::i32;
10945 }
10946
10947 /// \brief Returns true if it is beneficial to convert a load of a constant
10948 /// to just the constant itself.
10949 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10950                                                           Type *Ty) const {
10951   assert(Ty->isIntegerTy());
10952
10953   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10954   if (BitSize == 0 || BitSize > 64)
10955     return false;
10956   return true;
10957 }
10958
10959 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10960   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10961     return false;
10962   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10963   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10964   return NumBits1 == 64 && NumBits2 == 32;
10965 }
10966
10967 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10968   if (!VT1.isInteger() || !VT2.isInteger())
10969     return false;
10970   unsigned NumBits1 = VT1.getSizeInBits();
10971   unsigned NumBits2 = VT2.getSizeInBits();
10972   return NumBits1 == 64 && NumBits2 == 32;
10973 }
10974
10975 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10976   // Generally speaking, zexts are not free, but they are free when they can be
10977   // folded with other operations.
10978   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
10979     EVT MemVT = LD->getMemoryVT();
10980     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
10981          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
10982         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
10983          LD->getExtensionType() == ISD::ZEXTLOAD))
10984       return true;
10985   }
10986
10987   // FIXME: Add other cases...
10988   //  - 32-bit shifts with a zext to i64
10989   //  - zext after ctlz, bswap, etc.
10990   //  - zext after and by a constant mask
10991
10992   return TargetLowering::isZExtFree(Val, VT2);
10993 }
10994
10995 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
10996   assert(VT.isFloatingPoint());
10997   return true;
10998 }
10999
11000 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11001   return isInt<16>(Imm) || isUInt<16>(Imm);
11002 }
11003
11004 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11005   return isInt<16>(Imm) || isUInt<16>(Imm);
11006 }
11007
11008 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11009                                                        unsigned,
11010                                                        unsigned,
11011                                                        bool *Fast) const {
11012   if (DisablePPCUnaligned)
11013     return false;
11014
11015   // PowerPC supports unaligned memory access for simple non-vector types.
11016   // Although accessing unaligned addresses is not as efficient as accessing
11017   // aligned addresses, it is generally more efficient than manual expansion,
11018   // and generally only traps for software emulation when crossing page
11019   // boundaries.
11020
11021   if (!VT.isSimple())
11022     return false;
11023
11024   if (VT.getSimpleVT().isVector()) {
11025     if (Subtarget.hasVSX()) {
11026       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11027           VT != MVT::v4f32 && VT != MVT::v4i32)
11028         return false;
11029     } else {
11030       return false;
11031     }
11032   }
11033
11034   if (VT == MVT::ppcf128)
11035     return false;
11036
11037   if (Fast)
11038     *Fast = true;
11039
11040   return true;
11041 }
11042
11043 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11044   VT = VT.getScalarType();
11045
11046   if (!VT.isSimple())
11047     return false;
11048
11049   switch (VT.getSimpleVT().SimpleTy) {
11050   case MVT::f32:
11051   case MVT::f64:
11052     return true;
11053   default:
11054     break;
11055   }
11056
11057   return false;
11058 }
11059
11060 const MCPhysReg *
11061 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11062   // LR is a callee-save register, but we must treat it as clobbered by any call
11063   // site. Hence we include LR in the scratch registers, which are in turn added
11064   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11065   // to CTR, which is used by any indirect call.
11066   static const MCPhysReg ScratchRegs[] = {
11067     PPC::X12, PPC::LR8, PPC::CTR8, 0
11068   };
11069
11070   return ScratchRegs;
11071 }
11072
11073 bool
11074 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11075                      EVT VT , unsigned DefinedValues) const {
11076   if (VT == MVT::v2i64)
11077     return false;
11078
11079   if (Subtarget.hasQPX()) {
11080     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11081       return true;
11082   }
11083
11084   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11085 }
11086
11087 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11088   if (DisableILPPref || Subtarget.enableMachineScheduler())
11089     return TargetLowering::getSchedulingPreference(N);
11090
11091   return Sched::ILP;
11092 }
11093
11094 // Create a fast isel object.
11095 FastISel *
11096 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11097                                   const TargetLibraryInfo *LibInfo) const {
11098   return PPC::createFastISel(FuncInfo, LibInfo);
11099 }