72d1d19d0f3371ccbeaf8266d240de78ac94832b
[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
43 using namespace llvm;
44
45 // FIXME: Remove this once soft-float is supported.
46 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
47 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
48
49 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
50 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
51
52 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
53 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
54
55 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
56 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
57
58 // FIXME: Remove this once the bug has been fixed!
59 extern cl::opt<bool> ANDIGlueBug;
60
61 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
62                                      const PPCSubtarget &STI)
63     : TargetLowering(TM), Subtarget(STI) {
64   // Use _setjmp/_longjmp instead of setjmp/longjmp.
65   setUseUnderscoreSetJmp(true);
66   setUseUnderscoreLongJmp(true);
67
68   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
69   // arguments are at least 4/8 bytes aligned.
70   bool isPPC64 = Subtarget.isPPC64();
71   setMinStackArgumentAlignment(isPPC64 ? 8:4);
72
73   // Set up the register classes.
74   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
75   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
76   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77
78   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
79   for (MVT VT : MVT::integer_valuetypes()) {
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
81     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
82   }
83
84   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
85
86   // PowerPC has pre-inc load and store's.
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
100   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
101
102   if (Subtarget.useCRBits()) {
103     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
104
105     if (isPPC64 || Subtarget.hasFPCVT()) {
106       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
107       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
108                          isPPC64 ? MVT::i64 : MVT::i32);
109       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
110       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
111                          isPPC64 ? MVT::i64 : MVT::i32);
112     } else {
113       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
114       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115     }
116
117     // PowerPC does not support direct load / store of condition registers
118     setOperationAction(ISD::LOAD, MVT::i1, Custom);
119     setOperationAction(ISD::STORE, MVT::i1, Custom);
120
121     // FIXME: Remove this once the ANDI glue bug is fixed:
122     if (ANDIGlueBug)
123       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
124
125     for (MVT VT : MVT::integer_valuetypes()) {
126       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
128       setTruncStoreAction(VT, MVT::i1, Expand);
129     }
130
131     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
132   }
133
134   // This is used in the ppcf128->int sequence.  Note it has different semantics
135   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
136   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137
138   // We do not currently implement these libm ops for PowerPC.
139   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
140   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
141   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
142   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
143   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
144   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145
146   // PowerPC has no SREM/UREM instructions
147   setOperationAction(ISD::SREM, MVT::i32, Expand);
148   setOperationAction(ISD::UREM, MVT::i32, Expand);
149   setOperationAction(ISD::SREM, MVT::i64, Expand);
150   setOperationAction(ISD::UREM, MVT::i64, Expand);
151
152   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
153   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
157   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
159   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
160   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161
162   // We don't support sin/cos/sqrt/fmod/pow
163   setOperationAction(ISD::FSIN , MVT::f64, Expand);
164   setOperationAction(ISD::FCOS , MVT::f64, Expand);
165   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
166   setOperationAction(ISD::FREM , MVT::f64, Expand);
167   setOperationAction(ISD::FPOW , MVT::f64, Expand);
168   setOperationAction(ISD::FMA  , MVT::f64, Legal);
169   setOperationAction(ISD::FSIN , MVT::f32, Expand);
170   setOperationAction(ISD::FCOS , MVT::f32, Expand);
171   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
172   setOperationAction(ISD::FREM , MVT::f32, Expand);
173   setOperationAction(ISD::FPOW , MVT::f32, Expand);
174   setOperationAction(ISD::FMA  , MVT::f32, Legal);
175
176   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177
178   // If we're enabling GP optimizations, use hardware square root
179   if (!Subtarget.hasFSQRT() &&
180       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
181         Subtarget.hasFRE()))
182     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183
184   if (!Subtarget.hasFSQRT() &&
185       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
186         Subtarget.hasFRES()))
187     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188
189   if (Subtarget.hasFCPSGN()) {
190     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
191     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192   } else {
193     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
195   }
196
197   if (Subtarget.hasFPRND()) {
198     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
199     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
200     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201     setOperationAction(ISD::FROUND, MVT::f64, Legal);
202
203     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
204     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
205     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
206     setOperationAction(ISD::FROUND, MVT::f32, Legal);
207   }
208
209   // PowerPC does not have BSWAP, CTPOP or CTTZ
210   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
212   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
214   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
216   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
217   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218
219   if (Subtarget.hasPOPCNTD()) {
220     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
221     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
222   } else {
223     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
224     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
225   }
226
227   // PowerPC does not have ROTR
228   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
229   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
230
231   if (!Subtarget.useCRBits()) {
232     // PowerPC does not have Select
233     setOperationAction(ISD::SELECT, MVT::i32, Expand);
234     setOperationAction(ISD::SELECT, MVT::i64, Expand);
235     setOperationAction(ISD::SELECT, MVT::f32, Expand);
236     setOperationAction(ISD::SELECT, MVT::f64, Expand);
237   }
238
239   // PowerPC wants to turn select_cc of FP into fsel when possible.
240   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242
243   // PowerPC wants to optimize integer setcc a bit
244   if (!Subtarget.useCRBits())
245     setOperationAction(ISD::SETCC, MVT::i32, Custom);
246
247   // PowerPC does not have BRCOND which requires SetCC
248   if (!Subtarget.useCRBits())
249     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250
251   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
252
253   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
254   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255
256   // PowerPC does not have [U|S]INT_TO_FP
257   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
258   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259
260   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
262   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
263   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264
265   // We cannot sextinreg(i1).  Expand to shifts.
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267
268   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
269   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
270   // support continuation, user-level threading, and etc.. As a result, no
271   // other SjLj exception interfaces are implemented and please don't build
272   // your own exception handling based on them.
273   // LLVM/Clang supports zero-cost DWARF exception handling.
274   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
275   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276
277   // We want to legalize GlobalAddress and ConstantPool nodes into the
278   // appropriate instructions to materialize the address.
279   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
280   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
281   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
282   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
283   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
284   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
287   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
288   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
289
290   // TRAP is legal.
291   setOperationAction(ISD::TRAP, MVT::Other, Legal);
292
293   // TRAMPOLINE is custom lowered.
294   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
295   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296
297   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
299
300   if (Subtarget.isSVR4ABI()) {
301     if (isPPC64) {
302       // VAARG always uses double-word chunks, so promote anything smaller.
303       setOperationAction(ISD::VAARG, MVT::i1, Promote);
304       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
305       setOperationAction(ISD::VAARG, MVT::i8, Promote);
306       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
307       setOperationAction(ISD::VAARG, MVT::i16, Promote);
308       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
309       setOperationAction(ISD::VAARG, MVT::i32, Promote);
310       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
311       setOperationAction(ISD::VAARG, MVT::Other, Expand);
312     } else {
313       // VAARG is custom lowered with the 32-bit SVR4 ABI.
314       setOperationAction(ISD::VAARG, MVT::Other, Custom);
315       setOperationAction(ISD::VAARG, MVT::i64, Custom);
316     }
317   } else
318     setOperationAction(ISD::VAARG, MVT::Other, Expand);
319
320   if (Subtarget.isSVR4ABI() && !isPPC64)
321     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
322     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
323   else
324     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
325
326   // Use the default implementation.
327   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
328   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
329   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
331   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
332
333   // We want to custom lower some of our intrinsics.
334   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335
336   // To handle counter-based loop conditions.
337   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338
339   // Comparisons that require checking two conditions.
340   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
341   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
343   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
345   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
347   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
349   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
351   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352
353   if (Subtarget.has64BitSupport()) {
354     // They also have instructions for converting between i64 and fp.
355     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
356     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
357     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
358     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
359     // This is just the low 32 bits of a (signed) fp->i64 conversion.
360     // We cannot do this with Promote because i64 is not a legal type.
361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362
363     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
364       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365   } else {
366     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
367     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
368   }
369
370   // With the instructions enabled under FPCVT, we can do everything.
371   if (Subtarget.hasFPCVT()) {
372     if (Subtarget.has64BitSupport()) {
373       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
374       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
375       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
376       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
377     }
378
379     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
383   }
384
385   if (Subtarget.use64BitRegs()) {
386     // 64-bit PowerPC implementations can support i64 types directly
387     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
388     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
389     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
390     // 64-bit PowerPC wants to expand i128 shifts itself.
391     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
393     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394   } else {
395     // 32-bit PowerPC wants to expand i64 shifts itself.
396     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
398     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
399   }
400
401   if (Subtarget.hasAltivec()) {
402     // First set operation action for all vector types to expand. Then we
403     // will selectively turn on ones that can be effectively codegen'd.
404     for (MVT VT : MVT::vector_valuetypes()) {
405       // add/sub are legal for all supported vector VT's.
406       setOperationAction(ISD::ADD , VT, Legal);
407       setOperationAction(ISD::SUB , VT, Legal);
408       
409       // Vector instructions introduced in P8
410       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
411         setOperationAction(ISD::CTPOP, VT, Legal);
412         setOperationAction(ISD::CTLZ, VT, Legal);
413       }
414       else {
415         setOperationAction(ISD::CTPOP, VT, Expand);
416         setOperationAction(ISD::CTLZ, VT, Expand);
417       }
418
419       // We promote all shuffles to v16i8.
420       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
421       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
422
423       // We promote all non-typed operations to v4i32.
424       setOperationAction(ISD::AND   , VT, Promote);
425       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
426       setOperationAction(ISD::OR    , VT, Promote);
427       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
428       setOperationAction(ISD::XOR   , VT, Promote);
429       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
430       setOperationAction(ISD::LOAD  , VT, Promote);
431       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
432       setOperationAction(ISD::SELECT, VT, Promote);
433       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
434       setOperationAction(ISD::STORE, VT, Promote);
435       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
436
437       // No other operations are legal.
438       setOperationAction(ISD::MUL , VT, Expand);
439       setOperationAction(ISD::SDIV, VT, Expand);
440       setOperationAction(ISD::SREM, VT, Expand);
441       setOperationAction(ISD::UDIV, VT, Expand);
442       setOperationAction(ISD::UREM, VT, Expand);
443       setOperationAction(ISD::FDIV, VT, Expand);
444       setOperationAction(ISD::FREM, VT, Expand);
445       setOperationAction(ISD::FNEG, VT, Expand);
446       setOperationAction(ISD::FSQRT, VT, Expand);
447       setOperationAction(ISD::FLOG, VT, Expand);
448       setOperationAction(ISD::FLOG10, VT, Expand);
449       setOperationAction(ISD::FLOG2, VT, Expand);
450       setOperationAction(ISD::FEXP, VT, Expand);
451       setOperationAction(ISD::FEXP2, VT, Expand);
452       setOperationAction(ISD::FSIN, VT, Expand);
453       setOperationAction(ISD::FCOS, VT, Expand);
454       setOperationAction(ISD::FABS, VT, Expand);
455       setOperationAction(ISD::FPOWI, VT, Expand);
456       setOperationAction(ISD::FFLOOR, VT, Expand);
457       setOperationAction(ISD::FCEIL,  VT, Expand);
458       setOperationAction(ISD::FTRUNC, VT, Expand);
459       setOperationAction(ISD::FRINT,  VT, Expand);
460       setOperationAction(ISD::FNEARBYINT, VT, Expand);
461       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
462       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
463       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
464       setOperationAction(ISD::MULHU, VT, Expand);
465       setOperationAction(ISD::MULHS, VT, Expand);
466       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
467       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
468       setOperationAction(ISD::UDIVREM, VT, Expand);
469       setOperationAction(ISD::SDIVREM, VT, Expand);
470       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
471       setOperationAction(ISD::FPOW, VT, Expand);
472       setOperationAction(ISD::BSWAP, VT, Expand);
473       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
474       setOperationAction(ISD::CTTZ, VT, Expand);
475       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
476       setOperationAction(ISD::VSELECT, VT, Expand);
477       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
478
479       for (MVT InnerVT : MVT::vector_valuetypes()) {
480         setTruncStoreAction(VT, InnerVT, Expand);
481         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
482         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
483         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
484       }
485     }
486
487     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
488     // with merges, splats, etc.
489     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
490
491     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
492     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
493     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
494     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
495     setOperationAction(ISD::SELECT, MVT::v4i32,
496                        Subtarget.useCRBits() ? Legal : Expand);
497     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
500     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
502     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
503     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
504     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
505     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
506
507     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
510     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
511
512     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
513     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
514
515     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
516       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
517       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
518     }
519
520     
521     if (Subtarget.hasP8Altivec()) 
522       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
523     else
524       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
525       
526     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
527     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
528
529     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
530     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
531
532     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
533     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
534     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
535     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
536
537     // Altivec does not contain unordered floating-point compare instructions
538     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
539     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
540     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
541     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
542
543     if (Subtarget.hasVSX()) {
544       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
545       if (Subtarget.hasP8Vector())
546         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
547       if (Subtarget.hasDirectMove()) {
548         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
549         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
550         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
551         // FIXME: this is causing bootstrap failures, disable temporarily
552         //setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
553       }
554       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
555
556       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
557       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
558       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
559       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
560       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
561
562       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
563
564       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
565       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
566
567       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
568       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
569
570       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
571       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
572       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
573       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
574       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
575
576       // Share the Altivec comparison restrictions.
577       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
578       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
579       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
580       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
581
582       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
583       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
584
585       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
586
587       if (Subtarget.hasP8Vector())
588         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
589
590       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
591
592       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
593       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
594       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
595
596       if (Subtarget.hasP8Altivec()) {
597         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
598         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
599         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
600
601         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
602       }
603       else {
604         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
605         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
606         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
607
608         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
609
610         // VSX v2i64 only supports non-arithmetic operations.
611         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
612         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
613       }
614
615       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
616       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
617       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
618       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
619
620       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
621
622       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
623       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
624       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
625       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
626
627       // Vector operation legalization checks the result type of
628       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
629       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
630       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
631       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
632       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
633
634       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
635     }
636
637     if (Subtarget.hasP8Altivec()) {
638       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
639       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
640     }
641   }
642
643   if (Subtarget.hasQPX()) {
644     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
645     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
646     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
647     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
648
649     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
650     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
651
652     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
653     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
654
655     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
656     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
657
658     if (!Subtarget.useCRBits())
659       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
660     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
661
662     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
663     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
664     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
665     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
666     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
667     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
668     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
669
670     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
671     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
672
673     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
674     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
675     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
676
677     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
678     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
679     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
680     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
681     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
682     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
683     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
684     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
685     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
686     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
687     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
688
689     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
690     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
691
692     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
693     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
694
695     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
696
697     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
698     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
699     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
700     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
701
702     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
703     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
704
705     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
706     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
707
708     if (!Subtarget.useCRBits())
709       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
710     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
711
712     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
713     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
714     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
715     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
716     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
717     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
718     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
719
720     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
721     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
722
723     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
724     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
725     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
726     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
727     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
728     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
729     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
730     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
731     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
732     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
733     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
734
735     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
736     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
737
738     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
739     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
740
741     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
742
743     setOperationAction(ISD::AND , MVT::v4i1, Legal);
744     setOperationAction(ISD::OR , MVT::v4i1, Legal);
745     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
746
747     if (!Subtarget.useCRBits())
748       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
749     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
750
751     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
752     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
753
754     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
755     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
756     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
757     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
758     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
759     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
760     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
761
762     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
763     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
764
765     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
766
767     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
768     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
769     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
770     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
771
772     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
773     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
774     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
775     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
776
777     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
778     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
779
780     // These need to set FE_INEXACT, and so cannot be vectorized here.
781     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
782     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
783
784     if (TM.Options.UnsafeFPMath) {
785       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
786       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
787
788       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
789       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
790     } else {
791       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
792       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
793
794       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
795       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
796     }
797   }
798
799   if (Subtarget.has64BitSupport())
800     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
801
802   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
803
804   if (!isPPC64) {
805     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
806     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
807   }
808
809   setBooleanContents(ZeroOrOneBooleanContent);
810
811   if (Subtarget.hasAltivec()) {
812     // Altivec instructions set fields to all zeros or all ones.
813     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
814   }
815
816   if (!isPPC64) {
817     // These libcalls are not available in 32-bit.
818     setLibcallName(RTLIB::SHL_I128, nullptr);
819     setLibcallName(RTLIB::SRL_I128, nullptr);
820     setLibcallName(RTLIB::SRA_I128, nullptr);
821   }
822
823   if (isPPC64) {
824     setStackPointerRegisterToSaveRestore(PPC::X1);
825     setExceptionPointerRegister(PPC::X3);
826     setExceptionSelectorRegister(PPC::X4);
827   } else {
828     setStackPointerRegisterToSaveRestore(PPC::R1);
829     setExceptionPointerRegister(PPC::R3);
830     setExceptionSelectorRegister(PPC::R4);
831   }
832
833   // We have target-specific dag combine patterns for the following nodes:
834   setTargetDAGCombine(ISD::SINT_TO_FP);
835   if (Subtarget.hasFPCVT())
836     setTargetDAGCombine(ISD::UINT_TO_FP);
837   setTargetDAGCombine(ISD::LOAD);
838   setTargetDAGCombine(ISD::STORE);
839   setTargetDAGCombine(ISD::BR_CC);
840   if (Subtarget.useCRBits())
841     setTargetDAGCombine(ISD::BRCOND);
842   setTargetDAGCombine(ISD::BSWAP);
843   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
844   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
845   setTargetDAGCombine(ISD::INTRINSIC_VOID);
846
847   setTargetDAGCombine(ISD::SIGN_EXTEND);
848   setTargetDAGCombine(ISD::ZERO_EXTEND);
849   setTargetDAGCombine(ISD::ANY_EXTEND);
850
851   if (Subtarget.useCRBits()) {
852     setTargetDAGCombine(ISD::TRUNCATE);
853     setTargetDAGCombine(ISD::SETCC);
854     setTargetDAGCombine(ISD::SELECT_CC);
855   }
856
857   // Use reciprocal estimates.
858   if (TM.Options.UnsafeFPMath) {
859     setTargetDAGCombine(ISD::FDIV);
860     setTargetDAGCombine(ISD::FSQRT);
861   }
862
863   // Darwin long double math library functions have $LDBL128 appended.
864   if (Subtarget.isDarwin()) {
865     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
866     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
867     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
868     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
869     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
870     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
871     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
872     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
873     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
874     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
875   }
876
877   // With 32 condition bits, we don't need to sink (and duplicate) compares
878   // aggressively in CodeGenPrep.
879   if (Subtarget.useCRBits()) {
880     setHasMultipleConditionRegisters();
881     setJumpIsExpensive();
882   }
883
884   setMinFunctionAlignment(2);
885   if (Subtarget.isDarwin())
886     setPrefFunctionAlignment(4);
887
888   switch (Subtarget.getDarwinDirective()) {
889   default: break;
890   case PPC::DIR_970:
891   case PPC::DIR_A2:
892   case PPC::DIR_E500mc:
893   case PPC::DIR_E5500:
894   case PPC::DIR_PWR4:
895   case PPC::DIR_PWR5:
896   case PPC::DIR_PWR5X:
897   case PPC::DIR_PWR6:
898   case PPC::DIR_PWR6X:
899   case PPC::DIR_PWR7:
900   case PPC::DIR_PWR8:
901     setPrefFunctionAlignment(4);
902     setPrefLoopAlignment(4);
903     break;
904   }
905
906   setInsertFencesForAtomic(true);
907
908   if (Subtarget.enableMachineScheduler())
909     setSchedulingPreference(Sched::Source);
910   else
911     setSchedulingPreference(Sched::Hybrid);
912
913   computeRegisterProperties(STI.getRegisterInfo());
914
915   // The Freescale cores do better with aggressive inlining of memcpy and
916   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
917   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
918       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
919     MaxStoresPerMemset = 32;
920     MaxStoresPerMemsetOptSize = 16;
921     MaxStoresPerMemcpy = 32;
922     MaxStoresPerMemcpyOptSize = 8;
923     MaxStoresPerMemmove = 32;
924     MaxStoresPerMemmoveOptSize = 8;
925   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
926     // The A2 also benefits from (very) aggressive inlining of memcpy and
927     // friends. The overhead of a the function call, even when warm, can be
928     // over one hundred cycles.
929     MaxStoresPerMemset = 128;
930     MaxStoresPerMemcpy = 128;
931     MaxStoresPerMemmove = 128;
932   }
933 }
934
935 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
936 /// the desired ByVal argument alignment.
937 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
938                              unsigned MaxMaxAlign) {
939   if (MaxAlign == MaxMaxAlign)
940     return;
941   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
942     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
943       MaxAlign = 32;
944     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
945       MaxAlign = 16;
946   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
947     unsigned EltAlign = 0;
948     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
949     if (EltAlign > MaxAlign)
950       MaxAlign = EltAlign;
951   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
952     for (auto *EltTy : STy->elements()) {
953       unsigned EltAlign = 0;
954       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
955       if (EltAlign > MaxAlign)
956         MaxAlign = EltAlign;
957       if (MaxAlign == MaxMaxAlign)
958         break;
959     }
960   }
961 }
962
963 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
964 /// function arguments in the caller parameter area.
965 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
966                                                   const DataLayout &DL) const {
967   // Darwin passes everything on 4 byte boundary.
968   if (Subtarget.isDarwin())
969     return 4;
970
971   // 16byte and wider vectors are passed on 16byte boundary.
972   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
973   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
974   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
975     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
976   return Align;
977 }
978
979 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
980   switch ((PPCISD::NodeType)Opcode) {
981   case PPCISD::FIRST_NUMBER:    break;
982   case PPCISD::FSEL:            return "PPCISD::FSEL";
983   case PPCISD::FCFID:           return "PPCISD::FCFID";
984   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
985   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
986   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
987   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
988   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
989   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
990   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
991   case PPCISD::FRE:             return "PPCISD::FRE";
992   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
993   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
994   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
995   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
996   case PPCISD::VPERM:           return "PPCISD::VPERM";
997   case PPCISD::CMPB:            return "PPCISD::CMPB";
998   case PPCISD::Hi:              return "PPCISD::Hi";
999   case PPCISD::Lo:              return "PPCISD::Lo";
1000   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1001   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1002   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1003   case PPCISD::SRL:             return "PPCISD::SRL";
1004   case PPCISD::SRA:             return "PPCISD::SRA";
1005   case PPCISD::SHL:             return "PPCISD::SHL";
1006   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1007   case PPCISD::CALL:            return "PPCISD::CALL";
1008   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1009   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1010   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1011   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1012   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1013   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1014   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1015   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1016   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1017   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1018   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1019   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1020   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1021   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1022   case PPCISD::VCMP:            return "PPCISD::VCMP";
1023   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1024   case PPCISD::LBRX:            return "PPCISD::LBRX";
1025   case PPCISD::STBRX:           return "PPCISD::STBRX";
1026   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1027   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1028   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1029   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1030   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1031   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1032   case PPCISD::BDZ:             return "PPCISD::BDZ";
1033   case PPCISD::MFFS:            return "PPCISD::MFFS";
1034   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1035   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1036   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1037   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1038   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1039   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1040   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1041   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1042   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1043   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1044   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1045   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1046   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1047   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1048   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1049   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1050   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1051   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1052   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1053   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1054   case PPCISD::SC:              return "PPCISD::SC";
1055   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1056   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1057   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1058   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1059   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1060   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1061   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1062   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1063   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1064   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1065   }
1066   return nullptr;
1067 }
1068
1069 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1070                                           EVT VT) const {
1071   if (!VT.isVector())
1072     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1073
1074   if (Subtarget.hasQPX())
1075     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1076
1077   return VT.changeVectorElementTypeToInteger();
1078 }
1079
1080 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1081   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1082   return true;
1083 }
1084
1085 //===----------------------------------------------------------------------===//
1086 // Node matching predicates, for use by the tblgen matching code.
1087 //===----------------------------------------------------------------------===//
1088
1089 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1090 static bool isFloatingPointZero(SDValue Op) {
1091   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1092     return CFP->getValueAPF().isZero();
1093   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1094     // Maybe this has already been legalized into the constant pool?
1095     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1096       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1097         return CFP->getValueAPF().isZero();
1098   }
1099   return false;
1100 }
1101
1102 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1103 /// true if Op is undef or if it matches the specified value.
1104 static bool isConstantOrUndef(int Op, int Val) {
1105   return Op < 0 || Op == Val;
1106 }
1107
1108 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1109 /// VPKUHUM instruction.
1110 /// The ShuffleKind distinguishes between big-endian operations with
1111 /// two different inputs (0), either-endian operations with two identical
1112 /// inputs (1), and little-endian operations with two different inputs (2).
1113 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1114 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1115                                SelectionDAG &DAG) {
1116   bool IsLE = DAG.getDataLayout().isLittleEndian();
1117   if (ShuffleKind == 0) {
1118     if (IsLE)
1119       return false;
1120     for (unsigned i = 0; i != 16; ++i)
1121       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1122         return false;
1123   } else if (ShuffleKind == 2) {
1124     if (!IsLE)
1125       return false;
1126     for (unsigned i = 0; i != 16; ++i)
1127       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1128         return false;
1129   } else if (ShuffleKind == 1) {
1130     unsigned j = IsLE ? 0 : 1;
1131     for (unsigned i = 0; i != 8; ++i)
1132       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1133           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1134         return false;
1135   }
1136   return true;
1137 }
1138
1139 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1140 /// VPKUWUM instruction.
1141 /// The ShuffleKind distinguishes between big-endian operations with
1142 /// two different inputs (0), either-endian operations with two identical
1143 /// inputs (1), and little-endian operations with two different inputs (2).
1144 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1145 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1146                                SelectionDAG &DAG) {
1147   bool IsLE = DAG.getDataLayout().isLittleEndian();
1148   if (ShuffleKind == 0) {
1149     if (IsLE)
1150       return false;
1151     for (unsigned i = 0; i != 16; i += 2)
1152       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1153           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1154         return false;
1155   } else if (ShuffleKind == 2) {
1156     if (!IsLE)
1157       return false;
1158     for (unsigned i = 0; i != 16; i += 2)
1159       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1160           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1161         return false;
1162   } else if (ShuffleKind == 1) {
1163     unsigned j = IsLE ? 0 : 2;
1164     for (unsigned i = 0; i != 8; i += 2)
1165       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1166           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1167           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1168           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1169         return false;
1170   }
1171   return true;
1172 }
1173
1174 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1175 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1176 /// current subtarget.
1177 ///
1178 /// The ShuffleKind distinguishes between big-endian operations with
1179 /// two different inputs (0), either-endian operations with two identical
1180 /// inputs (1), and little-endian operations with two different inputs (2).
1181 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1182 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1183                                SelectionDAG &DAG) {
1184   const PPCSubtarget& Subtarget =
1185     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1186   if (!Subtarget.hasP8Vector())
1187     return false;
1188
1189   bool IsLE = DAG.getDataLayout().isLittleEndian();
1190   if (ShuffleKind == 0) {
1191     if (IsLE)
1192       return false;
1193     for (unsigned i = 0; i != 16; i += 4)
1194       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1195           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1196           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1197           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1198         return false;
1199   } else if (ShuffleKind == 2) {
1200     if (!IsLE)
1201       return false;
1202     for (unsigned i = 0; i != 16; i += 4)
1203       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1204           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1205           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1206           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1207         return false;
1208   } else if (ShuffleKind == 1) {
1209     unsigned j = IsLE ? 0 : 4;
1210     for (unsigned i = 0; i != 8; i += 4)
1211       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1212           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1213           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1214           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1215           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1216           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1217           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1218           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1219         return false;
1220   }
1221   return true;
1222 }
1223
1224 /// isVMerge - Common function, used to match vmrg* shuffles.
1225 ///
1226 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1227                      unsigned LHSStart, unsigned RHSStart) {
1228   if (N->getValueType(0) != MVT::v16i8)
1229     return false;
1230   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1231          "Unsupported merge size!");
1232
1233   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1234     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1235       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1236                              LHSStart+j+i*UnitSize) ||
1237           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1238                              RHSStart+j+i*UnitSize))
1239         return false;
1240     }
1241   return true;
1242 }
1243
1244 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1245 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1246 /// The ShuffleKind distinguishes between big-endian merges with two 
1247 /// different inputs (0), either-endian merges with two identical inputs (1),
1248 /// and little-endian merges with two different inputs (2).  For the latter,
1249 /// the input operands are swapped (see PPCInstrAltivec.td).
1250 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1251                              unsigned ShuffleKind, SelectionDAG &DAG) {
1252   if (DAG.getDataLayout().isLittleEndian()) {
1253     if (ShuffleKind == 1) // unary
1254       return isVMerge(N, UnitSize, 0, 0);
1255     else if (ShuffleKind == 2) // swapped
1256       return isVMerge(N, UnitSize, 0, 16);
1257     else
1258       return false;
1259   } else {
1260     if (ShuffleKind == 1) // unary
1261       return isVMerge(N, UnitSize, 8, 8);
1262     else if (ShuffleKind == 0) // normal
1263       return isVMerge(N, UnitSize, 8, 24);
1264     else
1265       return false;
1266   }
1267 }
1268
1269 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1270 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1271 /// The ShuffleKind distinguishes between big-endian merges with two 
1272 /// different inputs (0), either-endian merges with two identical inputs (1),
1273 /// and little-endian merges with two different inputs (2).  For the latter,
1274 /// the input operands are swapped (see PPCInstrAltivec.td).
1275 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1276                              unsigned ShuffleKind, SelectionDAG &DAG) {
1277   if (DAG.getDataLayout().isLittleEndian()) {
1278     if (ShuffleKind == 1) // unary
1279       return isVMerge(N, UnitSize, 8, 8);
1280     else if (ShuffleKind == 2) // swapped
1281       return isVMerge(N, UnitSize, 8, 24);
1282     else
1283       return false;
1284   } else {
1285     if (ShuffleKind == 1) // unary
1286       return isVMerge(N, UnitSize, 0, 0);
1287     else if (ShuffleKind == 0) // normal
1288       return isVMerge(N, UnitSize, 0, 16);
1289     else
1290       return false;
1291   }
1292 }
1293
1294 /**
1295  * \brief Common function used to match vmrgew and vmrgow shuffles
1296  *
1297  * The indexOffset determines whether to look for even or odd words in
1298  * the shuffle mask. This is based on the of the endianness of the target
1299  * machine.
1300  *   - Little Endian:
1301  *     - Use offset of 0 to check for odd elements
1302  *     - Use offset of 4 to check for even elements
1303  *   - Big Endian:
1304  *     - Use offset of 0 to check for even elements
1305  *     - Use offset of 4 to check for odd elements
1306  * A detailed description of the vector element ordering for little endian and
1307  * big endian can be found at
1308  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1309  * Targeting your applications - what little endian and big endian IBM XL C/C++
1310  * compiler differences mean to you
1311  *
1312  * The mask to the shuffle vector instruction specifies the indices of the
1313  * elements from the two input vectors to place in the result. The elements are
1314  * numbered in array-access order, starting with the first vector. These vectors
1315  * are always of type v16i8, thus each vector will contain 16 elements of size
1316  * 8. More info on the shuffle vector can be found in the
1317  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1318  * Language Reference.
1319  *
1320  * The RHSStartValue indicates whether the same input vectors are used (unary)
1321  * or two different input vectors are used, based on the following:
1322  *   - If the instruction uses the same vector for both inputs, the range of the
1323  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1324  *     be 0.
1325  *   - If the instruction has two different vectors then the range of the
1326  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1327  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1328  *     to 31 specify elements in the second vector).
1329  *
1330  * \param[in] N The shuffle vector SD Node to analyze
1331  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1332  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1333  * vector to the shuffle_vector instruction
1334  * \return true iff this shuffle vector represents an even or odd word merge
1335  */
1336 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1337                      unsigned RHSStartValue) {
1338   if (N->getValueType(0) != MVT::v16i8)
1339     return false;
1340
1341   for (unsigned i = 0; i < 2; ++i)
1342     for (unsigned j = 0; j < 4; ++j)
1343       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1344                              i*RHSStartValue+j+IndexOffset) ||
1345           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1346                              i*RHSStartValue+j+IndexOffset+8))
1347         return false;
1348   return true;
1349 }
1350
1351 /**
1352  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1353  * vmrgow instructions.
1354  *
1355  * \param[in] N The shuffle vector SD Node to analyze
1356  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1357  * \param[in] ShuffleKind Identify the type of merge:
1358  *   - 0 = big-endian merge with two different inputs;
1359  *   - 1 = either-endian merge with two identical inputs;
1360  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1361  *     little-endian merges).
1362  * \param[in] DAG The current SelectionDAG
1363  * \return true iff this shuffle mask 
1364  */
1365 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1366                               unsigned ShuffleKind, SelectionDAG &DAG) {
1367   if (DAG.getDataLayout().isLittleEndian()) {
1368     unsigned indexOffset = CheckEven ? 4 : 0;
1369     if (ShuffleKind == 1) // Unary
1370       return isVMerge(N, indexOffset, 0);
1371     else if (ShuffleKind == 2) // swapped
1372       return isVMerge(N, indexOffset, 16);
1373     else
1374       return false;
1375   }
1376   else {
1377     unsigned indexOffset = CheckEven ? 0 : 4;
1378     if (ShuffleKind == 1) // Unary
1379       return isVMerge(N, indexOffset, 0);
1380     else if (ShuffleKind == 0) // Normal
1381       return isVMerge(N, indexOffset, 16);
1382     else
1383       return false;
1384   }
1385   return false;
1386 }
1387
1388 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1389 /// amount, otherwise return -1.
1390 /// The ShuffleKind distinguishes between big-endian operations with two 
1391 /// different inputs (0), either-endian operations with two identical inputs
1392 /// (1), and little-endian operations with two different inputs (2).  For the
1393 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1394 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1395                              SelectionDAG &DAG) {
1396   if (N->getValueType(0) != MVT::v16i8)
1397     return -1;
1398
1399   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1400
1401   // Find the first non-undef value in the shuffle mask.
1402   unsigned i;
1403   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1404     /*search*/;
1405
1406   if (i == 16) return -1;  // all undef.
1407
1408   // Otherwise, check to see if the rest of the elements are consecutively
1409   // numbered from this value.
1410   unsigned ShiftAmt = SVOp->getMaskElt(i);
1411   if (ShiftAmt < i) return -1;
1412
1413   ShiftAmt -= i;
1414   bool isLE = DAG.getDataLayout().isLittleEndian();
1415
1416   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1417     // Check the rest of the elements to see if they are consecutive.
1418     for (++i; i != 16; ++i)
1419       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1420         return -1;
1421   } else if (ShuffleKind == 1) {
1422     // Check the rest of the elements to see if they are consecutive.
1423     for (++i; i != 16; ++i)
1424       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1425         return -1;
1426   } else
1427     return -1;
1428
1429   if (isLE)
1430     ShiftAmt = 16 - ShiftAmt;
1431
1432   return ShiftAmt;
1433 }
1434
1435 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1436 /// specifies a splat of a single element that is suitable for input to
1437 /// VSPLTB/VSPLTH/VSPLTW.
1438 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1439   assert(N->getValueType(0) == MVT::v16i8 &&
1440          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1441
1442   // The consecutive indices need to specify an element, not part of two
1443   // different elements.  So abandon ship early if this isn't the case.
1444   if (N->getMaskElt(0) % EltSize != 0)
1445     return false;
1446
1447   // This is a splat operation if each element of the permute is the same, and
1448   // if the value doesn't reference the second vector.
1449   unsigned ElementBase = N->getMaskElt(0);
1450
1451   // FIXME: Handle UNDEF elements too!
1452   if (ElementBase >= 16)
1453     return false;
1454
1455   // Check that the indices are consecutive, in the case of a multi-byte element
1456   // splatted with a v16i8 mask.
1457   for (unsigned i = 1; i != EltSize; ++i)
1458     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1459       return false;
1460
1461   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1462     if (N->getMaskElt(i) < 0) continue;
1463     for (unsigned j = 0; j != EltSize; ++j)
1464       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1465         return false;
1466   }
1467   return true;
1468 }
1469
1470 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1471 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1472 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1473                                 SelectionDAG &DAG) {
1474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1475   assert(isSplatShuffleMask(SVOp, EltSize));
1476   if (DAG.getDataLayout().isLittleEndian())
1477     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1478   else
1479     return SVOp->getMaskElt(0) / EltSize;
1480 }
1481
1482 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1483 /// by using a vspltis[bhw] instruction of the specified element size, return
1484 /// the constant being splatted.  The ByteSize field indicates the number of
1485 /// bytes of each element [124] -> [bhw].
1486 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1487   SDValue OpVal(nullptr, 0);
1488
1489   // If ByteSize of the splat is bigger than the element size of the
1490   // build_vector, then we have a case where we are checking for a splat where
1491   // multiple elements of the buildvector are folded together into a single
1492   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1493   unsigned EltSize = 16/N->getNumOperands();
1494   if (EltSize < ByteSize) {
1495     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1496     SDValue UniquedVals[4];
1497     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1498
1499     // See if all of the elements in the buildvector agree across.
1500     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1501       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1502       // If the element isn't a constant, bail fully out.
1503       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1504
1505
1506       if (!UniquedVals[i&(Multiple-1)].getNode())
1507         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1508       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1509         return SDValue();  // no match.
1510     }
1511
1512     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1513     // either constant or undef values that are identical for each chunk.  See
1514     // if these chunks can form into a larger vspltis*.
1515
1516     // Check to see if all of the leading entries are either 0 or -1.  If
1517     // neither, then this won't fit into the immediate field.
1518     bool LeadingZero = true;
1519     bool LeadingOnes = true;
1520     for (unsigned i = 0; i != Multiple-1; ++i) {
1521       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1522
1523       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1524       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1525     }
1526     // Finally, check the least significant entry.
1527     if (LeadingZero) {
1528       if (!UniquedVals[Multiple-1].getNode())
1529         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1530       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1531       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1532         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1533     }
1534     if (LeadingOnes) {
1535       if (!UniquedVals[Multiple-1].getNode())
1536         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1537       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1538       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1539         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1540     }
1541
1542     return SDValue();
1543   }
1544
1545   // Check to see if this buildvec has a single non-undef value in its elements.
1546   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1547     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1548     if (!OpVal.getNode())
1549       OpVal = N->getOperand(i);
1550     else if (OpVal != N->getOperand(i))
1551       return SDValue();
1552   }
1553
1554   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1555
1556   unsigned ValSizeInBytes = EltSize;
1557   uint64_t Value = 0;
1558   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1559     Value = CN->getZExtValue();
1560   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1561     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1562     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1563   }
1564
1565   // If the splat value is larger than the element value, then we can never do
1566   // this splat.  The only case that we could fit the replicated bits into our
1567   // immediate field for would be zero, and we prefer to use vxor for it.
1568   if (ValSizeInBytes < ByteSize) return SDValue();
1569
1570   // If the element value is larger than the splat value, check if it consists
1571   // of a repeated bit pattern of size ByteSize.
1572   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1573     return SDValue();
1574
1575   // Properly sign extend the value.
1576   int MaskVal = SignExtend32(Value, ByteSize * 8);
1577
1578   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1579   if (MaskVal == 0) return SDValue();
1580
1581   // Finally, if this value fits in a 5 bit sext field, return it
1582   if (SignExtend32<5>(MaskVal) == MaskVal)
1583     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1584   return SDValue();
1585 }
1586
1587 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1588 /// amount, otherwise return -1.
1589 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1590   EVT VT = N->getValueType(0);
1591   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1592     return -1;
1593
1594   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1595
1596   // Find the first non-undef value in the shuffle mask.
1597   unsigned i;
1598   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1599     /*search*/;
1600
1601   if (i == 4) return -1;  // all undef.
1602
1603   // Otherwise, check to see if the rest of the elements are consecutively
1604   // numbered from this value.
1605   unsigned ShiftAmt = SVOp->getMaskElt(i);
1606   if (ShiftAmt < i) return -1;
1607   ShiftAmt -= i;
1608
1609   // Check the rest of the elements to see if they are consecutive.
1610   for (++i; i != 4; ++i)
1611     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1612       return -1;
1613
1614   return ShiftAmt;
1615 }
1616
1617 //===----------------------------------------------------------------------===//
1618 //  Addressing Mode Selection
1619 //===----------------------------------------------------------------------===//
1620
1621 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1622 /// or 64-bit immediate, and if the value can be accurately represented as a
1623 /// sign extension from a 16-bit value.  If so, this returns true and the
1624 /// immediate.
1625 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1626   if (!isa<ConstantSDNode>(N))
1627     return false;
1628
1629   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1630   if (N->getValueType(0) == MVT::i32)
1631     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1632   else
1633     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1634 }
1635 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1636   return isIntS16Immediate(Op.getNode(), Imm);
1637 }
1638
1639
1640 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1641 /// can be represented as an indexed [r+r] operation.  Returns false if it
1642 /// can be more efficiently represented with [r+imm].
1643 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1644                                             SDValue &Index,
1645                                             SelectionDAG &DAG) const {
1646   short imm = 0;
1647   if (N.getOpcode() == ISD::ADD) {
1648     if (isIntS16Immediate(N.getOperand(1), imm))
1649       return false;    // r+i
1650     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1651       return false;    // r+i
1652
1653     Base = N.getOperand(0);
1654     Index = N.getOperand(1);
1655     return true;
1656   } else if (N.getOpcode() == ISD::OR) {
1657     if (isIntS16Immediate(N.getOperand(1), imm))
1658       return false;    // r+i can fold it if we can.
1659
1660     // If this is an or of disjoint bitfields, we can codegen this as an add
1661     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1662     // disjoint.
1663     APInt LHSKnownZero, LHSKnownOne;
1664     APInt RHSKnownZero, RHSKnownOne;
1665     DAG.computeKnownBits(N.getOperand(0),
1666                          LHSKnownZero, LHSKnownOne);
1667
1668     if (LHSKnownZero.getBoolValue()) {
1669       DAG.computeKnownBits(N.getOperand(1),
1670                            RHSKnownZero, RHSKnownOne);
1671       // If all of the bits are known zero on the LHS or RHS, the add won't
1672       // carry.
1673       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1674         Base = N.getOperand(0);
1675         Index = N.getOperand(1);
1676         return true;
1677       }
1678     }
1679   }
1680
1681   return false;
1682 }
1683
1684 // If we happen to be doing an i64 load or store into a stack slot that has
1685 // less than a 4-byte alignment, then the frame-index elimination may need to
1686 // use an indexed load or store instruction (because the offset may not be a
1687 // multiple of 4). The extra register needed to hold the offset comes from the
1688 // register scavenger, and it is possible that the scavenger will need to use
1689 // an emergency spill slot. As a result, we need to make sure that a spill slot
1690 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1691 // stack slot.
1692 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1693   // FIXME: This does not handle the LWA case.
1694   if (VT != MVT::i64)
1695     return;
1696
1697   // NOTE: We'll exclude negative FIs here, which come from argument
1698   // lowering, because there are no known test cases triggering this problem
1699   // using packed structures (or similar). We can remove this exclusion if
1700   // we find such a test case. The reason why this is so test-case driven is
1701   // because this entire 'fixup' is only to prevent crashes (from the
1702   // register scavenger) on not-really-valid inputs. For example, if we have:
1703   //   %a = alloca i1
1704   //   %b = bitcast i1* %a to i64*
1705   //   store i64* a, i64 b
1706   // then the store should really be marked as 'align 1', but is not. If it
1707   // were marked as 'align 1' then the indexed form would have been
1708   // instruction-selected initially, and the problem this 'fixup' is preventing
1709   // won't happen regardless.
1710   if (FrameIdx < 0)
1711     return;
1712
1713   MachineFunction &MF = DAG.getMachineFunction();
1714   MachineFrameInfo *MFI = MF.getFrameInfo();
1715
1716   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1717   if (Align >= 4)
1718     return;
1719
1720   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1721   FuncInfo->setHasNonRISpills();
1722 }
1723
1724 /// Returns true if the address N can be represented by a base register plus
1725 /// a signed 16-bit displacement [r+imm], and if it is not better
1726 /// represented as reg+reg.  If Aligned is true, only accept displacements
1727 /// suitable for STD and friends, i.e. multiples of 4.
1728 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1729                                             SDValue &Base,
1730                                             SelectionDAG &DAG,
1731                                             bool Aligned) const {
1732   // FIXME dl should come from parent load or store, not from address
1733   SDLoc dl(N);
1734   // If this can be more profitably realized as r+r, fail.
1735   if (SelectAddressRegReg(N, Disp, Base, DAG))
1736     return false;
1737
1738   if (N.getOpcode() == ISD::ADD) {
1739     short imm = 0;
1740     if (isIntS16Immediate(N.getOperand(1), imm) &&
1741         (!Aligned || (imm & 3) == 0)) {
1742       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1743       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1744         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1745         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1746       } else {
1747         Base = N.getOperand(0);
1748       }
1749       return true; // [r+i]
1750     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1751       // Match LOAD (ADD (X, Lo(G))).
1752       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1753              && "Cannot handle constant offsets yet!");
1754       Disp = N.getOperand(1).getOperand(0);  // The global address.
1755       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1756              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1757              Disp.getOpcode() == ISD::TargetConstantPool ||
1758              Disp.getOpcode() == ISD::TargetJumpTable);
1759       Base = N.getOperand(0);
1760       return true;  // [&g+r]
1761     }
1762   } else if (N.getOpcode() == ISD::OR) {
1763     short imm = 0;
1764     if (isIntS16Immediate(N.getOperand(1), imm) &&
1765         (!Aligned || (imm & 3) == 0)) {
1766       // If this is an or of disjoint bitfields, we can codegen this as an add
1767       // (for better address arithmetic) if the LHS and RHS of the OR are
1768       // provably disjoint.
1769       APInt LHSKnownZero, LHSKnownOne;
1770       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1771
1772       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1773         // If all of the bits are known zero on the LHS or RHS, the add won't
1774         // carry.
1775         if (FrameIndexSDNode *FI =
1776               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1777           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1778           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1779         } else {
1780           Base = N.getOperand(0);
1781         }
1782         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1783         return true;
1784       }
1785     }
1786   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1787     // Loading from a constant address.
1788
1789     // If this address fits entirely in a 16-bit sext immediate field, codegen
1790     // this as "d, 0"
1791     short Imm;
1792     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1793       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1794       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1795                              CN->getValueType(0));
1796       return true;
1797     }
1798
1799     // Handle 32-bit sext immediates with LIS + addr mode.
1800     if ((CN->getValueType(0) == MVT::i32 ||
1801          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1802         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1803       int Addr = (int)CN->getZExtValue();
1804
1805       // Otherwise, break this down into an LIS + disp.
1806       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1807
1808       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1809                                    MVT::i32);
1810       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1811       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1812       return true;
1813     }
1814   }
1815
1816   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1817   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1818     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1819     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1820   } else
1821     Base = N;
1822   return true;      // [r+0]
1823 }
1824
1825 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1826 /// represented as an indexed [r+r] operation.
1827 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1828                                                 SDValue &Index,
1829                                                 SelectionDAG &DAG) const {
1830   // Check to see if we can easily represent this as an [r+r] address.  This
1831   // will fail if it thinks that the address is more profitably represented as
1832   // reg+imm, e.g. where imm = 0.
1833   if (SelectAddressRegReg(N, Base, Index, DAG))
1834     return true;
1835
1836   // If the operand is an addition, always emit this as [r+r], since this is
1837   // better (for code size, and execution, as the memop does the add for free)
1838   // than emitting an explicit add.
1839   if (N.getOpcode() == ISD::ADD) {
1840     Base = N.getOperand(0);
1841     Index = N.getOperand(1);
1842     return true;
1843   }
1844
1845   // Otherwise, do it the hard way, using R0 as the base register.
1846   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1847                          N.getValueType());
1848   Index = N;
1849   return true;
1850 }
1851
1852 /// getPreIndexedAddressParts - returns true by value, base pointer and
1853 /// offset pointer and addressing mode by reference if the node's address
1854 /// can be legally represented as pre-indexed load / store address.
1855 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1856                                                   SDValue &Offset,
1857                                                   ISD::MemIndexedMode &AM,
1858                                                   SelectionDAG &DAG) const {
1859   if (DisablePPCPreinc) return false;
1860
1861   bool isLoad = true;
1862   SDValue Ptr;
1863   EVT VT;
1864   unsigned Alignment;
1865   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1866     Ptr = LD->getBasePtr();
1867     VT = LD->getMemoryVT();
1868     Alignment = LD->getAlignment();
1869   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1870     Ptr = ST->getBasePtr();
1871     VT  = ST->getMemoryVT();
1872     Alignment = ST->getAlignment();
1873     isLoad = false;
1874   } else
1875     return false;
1876
1877   // PowerPC doesn't have preinc load/store instructions for vectors (except
1878   // for QPX, which does have preinc r+r forms).
1879   if (VT.isVector()) {
1880     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1881       return false;
1882     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1883       AM = ISD::PRE_INC;
1884       return true;
1885     }
1886   }
1887
1888   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1889
1890     // Common code will reject creating a pre-inc form if the base pointer
1891     // is a frame index, or if N is a store and the base pointer is either
1892     // the same as or a predecessor of the value being stored.  Check for
1893     // those situations here, and try with swapped Base/Offset instead.
1894     bool Swap = false;
1895
1896     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1897       Swap = true;
1898     else if (!isLoad) {
1899       SDValue Val = cast<StoreSDNode>(N)->getValue();
1900       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1901         Swap = true;
1902     }
1903
1904     if (Swap)
1905       std::swap(Base, Offset);
1906
1907     AM = ISD::PRE_INC;
1908     return true;
1909   }
1910
1911   // LDU/STU can only handle immediates that are a multiple of 4.
1912   if (VT != MVT::i64) {
1913     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1914       return false;
1915   } else {
1916     // LDU/STU need an address with at least 4-byte alignment.
1917     if (Alignment < 4)
1918       return false;
1919
1920     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1921       return false;
1922   }
1923
1924   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1925     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1926     // sext i32 to i64 when addr mode is r+i.
1927     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1928         LD->getExtensionType() == ISD::SEXTLOAD &&
1929         isa<ConstantSDNode>(Offset))
1930       return false;
1931   }
1932
1933   AM = ISD::PRE_INC;
1934   return true;
1935 }
1936
1937 //===----------------------------------------------------------------------===//
1938 //  LowerOperation implementation
1939 //===----------------------------------------------------------------------===//
1940
1941 /// GetLabelAccessInfo - Return true if we should reference labels using a
1942 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1943 static bool GetLabelAccessInfo(const TargetMachine &TM,
1944                                const PPCSubtarget &Subtarget,
1945                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1946                                const GlobalValue *GV = nullptr) {
1947   HiOpFlags = PPCII::MO_HA;
1948   LoOpFlags = PPCII::MO_LO;
1949
1950   // Don't use the pic base if not in PIC relocation model.
1951   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1952
1953   if (isPIC) {
1954     HiOpFlags |= PPCII::MO_PIC_FLAG;
1955     LoOpFlags |= PPCII::MO_PIC_FLAG;
1956   }
1957
1958   // If this is a reference to a global value that requires a non-lazy-ptr, make
1959   // sure that instruction lowering adds it.
1960   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1961     HiOpFlags |= PPCII::MO_NLP_FLAG;
1962     LoOpFlags |= PPCII::MO_NLP_FLAG;
1963
1964     if (GV->hasHiddenVisibility()) {
1965       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1966       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1967     }
1968   }
1969
1970   return isPIC;
1971 }
1972
1973 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1974                              SelectionDAG &DAG) {
1975   SDLoc DL(HiPart);
1976   EVT PtrVT = HiPart.getValueType();
1977   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1978
1979   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1980   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1981
1982   // With PIC, the first instruction is actually "GR+hi(&G)".
1983   if (isPIC)
1984     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1985                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1986
1987   // Generate non-pic code that has direct accesses to the constant pool.
1988   // The address of the global is just (hi(&g)+lo(&g)).
1989   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1990 }
1991
1992 static void setUsesTOCBasePtr(MachineFunction &MF) {
1993   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1994   FuncInfo->setUsesTOCBasePtr();
1995 }
1996
1997 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1998   setUsesTOCBasePtr(DAG.getMachineFunction());
1999 }
2000
2001 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
2002                            SDValue GA) {
2003   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2004   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2005                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2006
2007   SDValue Ops[] = { GA, Reg };
2008   return DAG.getMemIntrinsicNode(
2009       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2010       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2011       false, 0);
2012 }
2013
2014 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2015                                              SelectionDAG &DAG) const {
2016   EVT PtrVT = Op.getValueType();
2017   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2018   const Constant *C = CP->getConstVal();
2019
2020   // 64-bit SVR4 ABI code is always position-independent.
2021   // The actual address of the GlobalValue is stored in the TOC.
2022   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2023     setUsesTOCBasePtr(DAG);
2024     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2025     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2026   }
2027
2028   unsigned MOHiFlag, MOLoFlag;
2029   bool isPIC =
2030       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2031
2032   if (isPIC && Subtarget.isSVR4ABI()) {
2033     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2034                                            PPCII::MO_PIC_FLAG);
2035     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2036   }
2037
2038   SDValue CPIHi =
2039     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2040   SDValue CPILo =
2041     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2042   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
2043 }
2044
2045 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2046   EVT PtrVT = Op.getValueType();
2047   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2048
2049   // 64-bit SVR4 ABI code is always position-independent.
2050   // The actual address of the GlobalValue is stored in the TOC.
2051   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2052     setUsesTOCBasePtr(DAG);
2053     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2054     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2055   }
2056
2057   unsigned MOHiFlag, MOLoFlag;
2058   bool isPIC =
2059       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2060
2061   if (isPIC && Subtarget.isSVR4ABI()) {
2062     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2063                                         PPCII::MO_PIC_FLAG);
2064     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2065   }
2066
2067   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2068   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2069   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
2070 }
2071
2072 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2073                                              SelectionDAG &DAG) const {
2074   EVT PtrVT = Op.getValueType();
2075   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2076   const BlockAddress *BA = BASDN->getBlockAddress();
2077
2078   // 64-bit SVR4 ABI code is always position-independent.
2079   // The actual BlockAddress is stored in the TOC.
2080   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2081     setUsesTOCBasePtr(DAG);
2082     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2083     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2084   }
2085
2086   unsigned MOHiFlag, MOLoFlag;
2087   bool isPIC =
2088       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2089   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2090   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2091   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
2092 }
2093
2094 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2095                                               SelectionDAG &DAG) const {
2096
2097   // FIXME: TLS addresses currently use medium model code sequences,
2098   // which is the most useful form.  Eventually support for small and
2099   // large models could be added if users need it, at the cost of
2100   // additional complexity.
2101   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2102   if (DAG.getTarget().Options.EmulatedTLS)
2103     return LowerToTLSEmulatedModel(GA, DAG);
2104
2105   SDLoc dl(GA);
2106   const GlobalValue *GV = GA->getGlobal();
2107   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2108   bool is64bit = Subtarget.isPPC64();
2109   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2110   PICLevel::Level picLevel = M->getPICLevel();
2111
2112   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2113
2114   if (Model == TLSModel::LocalExec) {
2115     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2116                                                PPCII::MO_TPREL_HA);
2117     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2118                                                PPCII::MO_TPREL_LO);
2119     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2120                                      is64bit ? MVT::i64 : MVT::i32);
2121     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2122     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2123   }
2124
2125   if (Model == TLSModel::InitialExec) {
2126     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2127     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2128                                                 PPCII::MO_TLS);
2129     SDValue GOTPtr;
2130     if (is64bit) {
2131       setUsesTOCBasePtr(DAG);
2132       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2133       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2134                            PtrVT, GOTReg, TGA);
2135     } else
2136       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2137     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2138                                    PtrVT, TGA, GOTPtr);
2139     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2140   }
2141
2142   if (Model == TLSModel::GeneralDynamic) {
2143     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2144     SDValue GOTPtr;
2145     if (is64bit) {
2146       setUsesTOCBasePtr(DAG);
2147       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2148       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2149                                    GOTReg, TGA);
2150     } else {
2151       if (picLevel == PICLevel::Small)
2152         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2153       else
2154         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2155     }
2156     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2157                        GOTPtr, TGA, TGA);
2158   }
2159
2160   if (Model == TLSModel::LocalDynamic) {
2161     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2162     SDValue GOTPtr;
2163     if (is64bit) {
2164       setUsesTOCBasePtr(DAG);
2165       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2166       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2167                            GOTReg, TGA);
2168     } else {
2169       if (picLevel == PICLevel::Small)
2170         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2171       else
2172         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2173     }
2174     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2175                                   PtrVT, GOTPtr, TGA, TGA);
2176     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2177                                       PtrVT, TLSAddr, TGA);
2178     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2179   }
2180
2181   llvm_unreachable("Unknown TLS model!");
2182 }
2183
2184 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2185                                               SelectionDAG &DAG) const {
2186   EVT PtrVT = Op.getValueType();
2187   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2188   SDLoc DL(GSDN);
2189   const GlobalValue *GV = GSDN->getGlobal();
2190
2191   // 64-bit SVR4 ABI code is always position-independent.
2192   // The actual address of the GlobalValue is stored in the TOC.
2193   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2194     setUsesTOCBasePtr(DAG);
2195     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2196     return getTOCEntry(DAG, DL, true, GA);
2197   }
2198
2199   unsigned MOHiFlag, MOLoFlag;
2200   bool isPIC =
2201       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2202
2203   if (isPIC && Subtarget.isSVR4ABI()) {
2204     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2205                                             GSDN->getOffset(),
2206                                             PPCII::MO_PIC_FLAG);
2207     return getTOCEntry(DAG, DL, false, GA);
2208   }
2209
2210   SDValue GAHi =
2211     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2212   SDValue GALo =
2213     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2214
2215   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2216
2217   // If the global reference is actually to a non-lazy-pointer, we have to do an
2218   // extra load to get the address of the global.
2219   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2220     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2221                       false, false, false, 0);
2222   return Ptr;
2223 }
2224
2225 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2226   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2227   SDLoc dl(Op);
2228
2229   if (Op.getValueType() == MVT::v2i64) {
2230     // When the operands themselves are v2i64 values, we need to do something
2231     // special because VSX has no underlying comparison operations for these.
2232     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2233       // Equality can be handled by casting to the legal type for Altivec
2234       // comparisons, everything else needs to be expanded.
2235       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2236         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2237                  DAG.getSetCC(dl, MVT::v4i32,
2238                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2239                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2240                    CC));
2241       }
2242
2243       return SDValue();
2244     }
2245
2246     // We handle most of these in the usual way.
2247     return Op;
2248   }
2249
2250   // If we're comparing for equality to zero, expose the fact that this is
2251   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2252   // fold the new nodes.
2253   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2254     if (C->isNullValue() && CC == ISD::SETEQ) {
2255       EVT VT = Op.getOperand(0).getValueType();
2256       SDValue Zext = Op.getOperand(0);
2257       if (VT.bitsLT(MVT::i32)) {
2258         VT = MVT::i32;
2259         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2260       }
2261       unsigned Log2b = Log2_32(VT.getSizeInBits());
2262       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2263       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2264                                 DAG.getConstant(Log2b, dl, MVT::i32));
2265       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2266     }
2267     // Leave comparisons against 0 and -1 alone for now, since they're usually
2268     // optimized.  FIXME: revisit this when we can custom lower all setcc
2269     // optimizations.
2270     if (C->isAllOnesValue() || C->isNullValue())
2271       return SDValue();
2272   }
2273
2274   // If we have an integer seteq/setne, turn it into a compare against zero
2275   // by xor'ing the rhs with the lhs, which is faster than setting a
2276   // condition register, reading it back out, and masking the correct bit.  The
2277   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2278   // the result to other bit-twiddling opportunities.
2279   EVT LHSVT = Op.getOperand(0).getValueType();
2280   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2281     EVT VT = Op.getValueType();
2282     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2283                                 Op.getOperand(1));
2284     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2285   }
2286   return SDValue();
2287 }
2288
2289 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2290                                       const PPCSubtarget &Subtarget) const {
2291   SDNode *Node = Op.getNode();
2292   EVT VT = Node->getValueType(0);
2293   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2294   SDValue InChain = Node->getOperand(0);
2295   SDValue VAListPtr = Node->getOperand(1);
2296   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2297   SDLoc dl(Node);
2298
2299   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2300
2301   // gpr_index
2302   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2303                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2304                                     false, false, false, 0);
2305   InChain = GprIndex.getValue(1);
2306
2307   if (VT == MVT::i64) {
2308     // Check if GprIndex is even
2309     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2310                                  DAG.getConstant(1, dl, MVT::i32));
2311     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2312                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2313     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2314                                           DAG.getConstant(1, dl, MVT::i32));
2315     // Align GprIndex to be even if it isn't
2316     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2317                            GprIndex);
2318   }
2319
2320   // fpr index is 1 byte after gpr
2321   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2322                                DAG.getConstant(1, dl, MVT::i32));
2323
2324   // fpr
2325   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2326                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2327                                     false, false, false, 0);
2328   InChain = FprIndex.getValue(1);
2329
2330   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2331                                        DAG.getConstant(8, dl, MVT::i32));
2332
2333   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2334                                         DAG.getConstant(4, dl, MVT::i32));
2335
2336   // areas
2337   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2338                                      MachinePointerInfo(), false, false,
2339                                      false, 0);
2340   InChain = OverflowArea.getValue(1);
2341
2342   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2343                                     MachinePointerInfo(), false, false,
2344                                     false, 0);
2345   InChain = RegSaveArea.getValue(1);
2346
2347   // select overflow_area if index > 8
2348   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2349                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2350
2351   // adjustment constant gpr_index * 4/8
2352   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2353                                     VT.isInteger() ? GprIndex : FprIndex,
2354                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2355                                                     MVT::i32));
2356
2357   // OurReg = RegSaveArea + RegConstant
2358   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2359                                RegConstant);
2360
2361   // Floating types are 32 bytes into RegSaveArea
2362   if (VT.isFloatingPoint())
2363     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2364                          DAG.getConstant(32, dl, MVT::i32));
2365
2366   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2367   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2368                                    VT.isInteger() ? GprIndex : FprIndex,
2369                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2370                                                    MVT::i32));
2371
2372   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2373                               VT.isInteger() ? VAListPtr : FprPtr,
2374                               MachinePointerInfo(SV),
2375                               MVT::i8, false, false, 0);
2376
2377   // determine if we should load from reg_save_area or overflow_area
2378   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2379
2380   // increase overflow_area by 4/8 if gpr/fpr > 8
2381   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2382                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2383                                           dl, MVT::i32));
2384
2385   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2386                              OverflowAreaPlusN);
2387
2388   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2389                               OverflowAreaPtr,
2390                               MachinePointerInfo(),
2391                               MVT::i32, false, false, 0);
2392
2393   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2394                      false, false, false, 0);
2395 }
2396
2397 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2398                                        const PPCSubtarget &Subtarget) const {
2399   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2400
2401   // We have to copy the entire va_list struct:
2402   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2403   return DAG.getMemcpy(Op.getOperand(0), Op,
2404                        Op.getOperand(1), Op.getOperand(2),
2405                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2406                        false, MachinePointerInfo(), MachinePointerInfo());
2407 }
2408
2409 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2410                                                   SelectionDAG &DAG) const {
2411   return Op.getOperand(0);
2412 }
2413
2414 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2415                                                 SelectionDAG &DAG) const {
2416   SDValue Chain = Op.getOperand(0);
2417   SDValue Trmp = Op.getOperand(1); // trampoline
2418   SDValue FPtr = Op.getOperand(2); // nested function
2419   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2420   SDLoc dl(Op);
2421
2422   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2423   bool isPPC64 = (PtrVT == MVT::i64);
2424   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2425
2426   TargetLowering::ArgListTy Args;
2427   TargetLowering::ArgListEntry Entry;
2428
2429   Entry.Ty = IntPtrTy;
2430   Entry.Node = Trmp; Args.push_back(Entry);
2431
2432   // TrampSize == (isPPC64 ? 48 : 40);
2433   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2434                                isPPC64 ? MVT::i64 : MVT::i32);
2435   Args.push_back(Entry);
2436
2437   Entry.Node = FPtr; Args.push_back(Entry);
2438   Entry.Node = Nest; Args.push_back(Entry);
2439
2440   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2441   TargetLowering::CallLoweringInfo CLI(DAG);
2442   CLI.setDebugLoc(dl).setChain(Chain)
2443     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2444                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2445                std::move(Args), 0);
2446
2447   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2448   return CallResult.second;
2449 }
2450
2451 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2452                                         const PPCSubtarget &Subtarget) const {
2453   MachineFunction &MF = DAG.getMachineFunction();
2454   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2455
2456   SDLoc dl(Op);
2457
2458   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2459     // vastart just stores the address of the VarArgsFrameIndex slot into the
2460     // memory location argument.
2461     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2462     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2463     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2464     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2465                         MachinePointerInfo(SV),
2466                         false, false, 0);
2467   }
2468
2469   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2470   // We suppose the given va_list is already allocated.
2471   //
2472   // typedef struct {
2473   //  char gpr;     /* index into the array of 8 GPRs
2474   //                 * stored in the register save area
2475   //                 * gpr=0 corresponds to r3,
2476   //                 * gpr=1 to r4, etc.
2477   //                 */
2478   //  char fpr;     /* index into the array of 8 FPRs
2479   //                 * stored in the register save area
2480   //                 * fpr=0 corresponds to f1,
2481   //                 * fpr=1 to f2, etc.
2482   //                 */
2483   //  char *overflow_arg_area;
2484   //                /* location on stack that holds
2485   //                 * the next overflow argument
2486   //                 */
2487   //  char *reg_save_area;
2488   //               /* where r3:r10 and f1:f8 (if saved)
2489   //                * are stored
2490   //                */
2491   // } va_list[1];
2492
2493
2494   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2495   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2496
2497   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2498
2499   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2500                                             PtrVT);
2501   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2502                                  PtrVT);
2503
2504   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2505   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2506
2507   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2508   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2509
2510   uint64_t FPROffset = 1;
2511   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2512
2513   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2514
2515   // Store first byte : number of int regs
2516   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2517                                          Op.getOperand(1),
2518                                          MachinePointerInfo(SV),
2519                                          MVT::i8, false, false, 0);
2520   uint64_t nextOffset = FPROffset;
2521   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2522                                   ConstFPROffset);
2523
2524   // Store second byte : number of float regs
2525   SDValue secondStore =
2526     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2527                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2528                       false, false, 0);
2529   nextOffset += StackOffset;
2530   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2531
2532   // Store second word : arguments given on stack
2533   SDValue thirdStore =
2534     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2535                  MachinePointerInfo(SV, nextOffset),
2536                  false, false, 0);
2537   nextOffset += FrameOffset;
2538   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2539
2540   // Store third word : arguments given in registers
2541   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2542                       MachinePointerInfo(SV, nextOffset),
2543                       false, false, 0);
2544
2545 }
2546
2547 #include "PPCGenCallingConv.inc"
2548
2549 // Function whose sole purpose is to kill compiler warnings 
2550 // stemming from unused functions included from PPCGenCallingConv.inc.
2551 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2552   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2553 }
2554
2555 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2556                                       CCValAssign::LocInfo &LocInfo,
2557                                       ISD::ArgFlagsTy &ArgFlags,
2558                                       CCState &State) {
2559   return true;
2560 }
2561
2562 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2563                                              MVT &LocVT,
2564                                              CCValAssign::LocInfo &LocInfo,
2565                                              ISD::ArgFlagsTy &ArgFlags,
2566                                              CCState &State) {
2567   static const MCPhysReg ArgRegs[] = {
2568     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2569     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2570   };
2571   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2572
2573   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2574
2575   // Skip one register if the first unallocated register has an even register
2576   // number and there are still argument registers available which have not been
2577   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2578   // need to skip a register if RegNum is odd.
2579   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2580     State.AllocateReg(ArgRegs[RegNum]);
2581   }
2582
2583   // Always return false here, as this function only makes sure that the first
2584   // unallocated register has an odd register number and does not actually
2585   // allocate a register for the current argument.
2586   return false;
2587 }
2588
2589 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2590                                                MVT &LocVT,
2591                                                CCValAssign::LocInfo &LocInfo,
2592                                                ISD::ArgFlagsTy &ArgFlags,
2593                                                CCState &State) {
2594   static const MCPhysReg ArgRegs[] = {
2595     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2596     PPC::F8
2597   };
2598
2599   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2600
2601   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2602
2603   // If there is only one Floating-point register left we need to put both f64
2604   // values of a split ppc_fp128 value on the stack.
2605   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2606     State.AllocateReg(ArgRegs[RegNum]);
2607   }
2608
2609   // Always return false here, as this function only makes sure that the two f64
2610   // values a ppc_fp128 value is split into are both passed in registers or both
2611   // passed on the stack and does not actually allocate a register for the
2612   // current argument.
2613   return false;
2614 }
2615
2616 /// FPR - The set of FP registers that should be allocated for arguments,
2617 /// on Darwin.
2618 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2619                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2620                                 PPC::F11, PPC::F12, PPC::F13};
2621
2622 /// QFPR - The set of QPX registers that should be allocated for arguments.
2623 static const MCPhysReg QFPR[] = {
2624     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2625     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2626
2627 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2628 /// the stack.
2629 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2630                                        unsigned PtrByteSize) {
2631   unsigned ArgSize = ArgVT.getStoreSize();
2632   if (Flags.isByVal())
2633     ArgSize = Flags.getByValSize();
2634
2635   // Round up to multiples of the pointer size, except for array members,
2636   // which are always packed.
2637   if (!Flags.isInConsecutiveRegs())
2638     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2639
2640   return ArgSize;
2641 }
2642
2643 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2644 /// on the stack.
2645 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2646                                             ISD::ArgFlagsTy Flags,
2647                                             unsigned PtrByteSize) {
2648   unsigned Align = PtrByteSize;
2649
2650   // Altivec parameters are padded to a 16 byte boundary.
2651   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2652       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2653       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2654       ArgVT == MVT::v1i128)
2655     Align = 16;
2656   // QPX vector types stored in double-precision are padded to a 32 byte
2657   // boundary.
2658   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2659     Align = 32;
2660
2661   // ByVal parameters are aligned as requested.
2662   if (Flags.isByVal()) {
2663     unsigned BVAlign = Flags.getByValAlign();
2664     if (BVAlign > PtrByteSize) {
2665       if (BVAlign % PtrByteSize != 0)
2666           llvm_unreachable(
2667             "ByVal alignment is not a multiple of the pointer size");
2668
2669       Align = BVAlign;
2670     }
2671   }
2672
2673   // Array members are always packed to their original alignment.
2674   if (Flags.isInConsecutiveRegs()) {
2675     // If the array member was split into multiple registers, the first
2676     // needs to be aligned to the size of the full type.  (Except for
2677     // ppcf128, which is only aligned as its f64 components.)
2678     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2679       Align = OrigVT.getStoreSize();
2680     else
2681       Align = ArgVT.getStoreSize();
2682   }
2683
2684   return Align;
2685 }
2686
2687 /// CalculateStackSlotUsed - Return whether this argument will use its
2688 /// stack slot (instead of being passed in registers).  ArgOffset,
2689 /// AvailableFPRs, and AvailableVRs must hold the current argument
2690 /// position, and will be updated to account for this argument.
2691 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2692                                    ISD::ArgFlagsTy Flags,
2693                                    unsigned PtrByteSize,
2694                                    unsigned LinkageSize,
2695                                    unsigned ParamAreaSize,
2696                                    unsigned &ArgOffset,
2697                                    unsigned &AvailableFPRs,
2698                                    unsigned &AvailableVRs, bool HasQPX) {
2699   bool UseMemory = false;
2700
2701   // Respect alignment of argument on the stack.
2702   unsigned Align =
2703     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2704   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2705   // If there's no space left in the argument save area, we must
2706   // use memory (this check also catches zero-sized arguments).
2707   if (ArgOffset >= LinkageSize + ParamAreaSize)
2708     UseMemory = true;
2709
2710   // Allocate argument on the stack.
2711   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2712   if (Flags.isInConsecutiveRegsLast())
2713     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2714   // If we overran the argument save area, we must use memory
2715   // (this check catches arguments passed partially in memory)
2716   if (ArgOffset > LinkageSize + ParamAreaSize)
2717     UseMemory = true;
2718
2719   // However, if the argument is actually passed in an FPR or a VR,
2720   // we don't use memory after all.
2721   if (!Flags.isByVal()) {
2722     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2723         // QPX registers overlap with the scalar FP registers.
2724         (HasQPX && (ArgVT == MVT::v4f32 ||
2725                     ArgVT == MVT::v4f64 ||
2726                     ArgVT == MVT::v4i1)))
2727       if (AvailableFPRs > 0) {
2728         --AvailableFPRs;
2729         return false;
2730       }
2731     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2732         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2733         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2734         ArgVT == MVT::v1i128)
2735       if (AvailableVRs > 0) {
2736         --AvailableVRs;
2737         return false;
2738       }
2739   }
2740
2741   return UseMemory;
2742 }
2743
2744 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2745 /// ensure minimum alignment required for target.
2746 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2747                                      unsigned NumBytes) {
2748   unsigned TargetAlign = Lowering->getStackAlignment();
2749   unsigned AlignMask = TargetAlign - 1;
2750   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2751   return NumBytes;
2752 }
2753
2754 SDValue
2755 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2756                                         CallingConv::ID CallConv, bool isVarArg,
2757                                         const SmallVectorImpl<ISD::InputArg>
2758                                           &Ins,
2759                                         SDLoc dl, SelectionDAG &DAG,
2760                                         SmallVectorImpl<SDValue> &InVals)
2761                                           const {
2762   if (Subtarget.isSVR4ABI()) {
2763     if (Subtarget.isPPC64())
2764       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2765                                          dl, DAG, InVals);
2766     else
2767       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2768                                          dl, DAG, InVals);
2769   } else {
2770     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2771                                        dl, DAG, InVals);
2772   }
2773 }
2774
2775 SDValue
2776 PPCTargetLowering::LowerFormalArguments_32SVR4(
2777                                       SDValue Chain,
2778                                       CallingConv::ID CallConv, bool isVarArg,
2779                                       const SmallVectorImpl<ISD::InputArg>
2780                                         &Ins,
2781                                       SDLoc dl, SelectionDAG &DAG,
2782                                       SmallVectorImpl<SDValue> &InVals) const {
2783
2784   // 32-bit SVR4 ABI Stack Frame Layout:
2785   //              +-----------------------------------+
2786   //        +-->  |            Back chain             |
2787   //        |     +-----------------------------------+
2788   //        |     | Floating-point register save area |
2789   //        |     +-----------------------------------+
2790   //        |     |    General register save area     |
2791   //        |     +-----------------------------------+
2792   //        |     |          CR save word             |
2793   //        |     +-----------------------------------+
2794   //        |     |         VRSAVE save word          |
2795   //        |     +-----------------------------------+
2796   //        |     |         Alignment padding         |
2797   //        |     +-----------------------------------+
2798   //        |     |     Vector register save area     |
2799   //        |     +-----------------------------------+
2800   //        |     |       Local variable space        |
2801   //        |     +-----------------------------------+
2802   //        |     |        Parameter list area        |
2803   //        |     +-----------------------------------+
2804   //        |     |           LR save word            |
2805   //        |     +-----------------------------------+
2806   // SP-->  +---  |            Back chain             |
2807   //              +-----------------------------------+
2808   //
2809   // Specifications:
2810   //   System V Application Binary Interface PowerPC Processor Supplement
2811   //   AltiVec Technology Programming Interface Manual
2812
2813   MachineFunction &MF = DAG.getMachineFunction();
2814   MachineFrameInfo *MFI = MF.getFrameInfo();
2815   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2816
2817   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2818   // Potential tail calls could cause overwriting of argument stack slots.
2819   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2820                        (CallConv == CallingConv::Fast));
2821   unsigned PtrByteSize = 4;
2822
2823   // Assign locations to all of the incoming arguments.
2824   SmallVector<CCValAssign, 16> ArgLocs;
2825   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2826                  *DAG.getContext());
2827
2828   // Reserve space for the linkage area on the stack.
2829   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2830   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2831
2832   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2833
2834   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2835     CCValAssign &VA = ArgLocs[i];
2836
2837     // Arguments stored in registers.
2838     if (VA.isRegLoc()) {
2839       const TargetRegisterClass *RC;
2840       EVT ValVT = VA.getValVT();
2841
2842       switch (ValVT.getSimpleVT().SimpleTy) {
2843         default:
2844           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2845         case MVT::i1:
2846         case MVT::i32:
2847           RC = &PPC::GPRCRegClass;
2848           break;
2849         case MVT::f32:
2850           if (Subtarget.hasP8Vector())
2851             RC = &PPC::VSSRCRegClass;
2852           else
2853             RC = &PPC::F4RCRegClass;
2854           break;
2855         case MVT::f64:
2856           if (Subtarget.hasVSX())
2857             RC = &PPC::VSFRCRegClass;
2858           else
2859             RC = &PPC::F8RCRegClass;
2860           break;
2861         case MVT::v16i8:
2862         case MVT::v8i16:
2863         case MVT::v4i32:
2864           RC = &PPC::VRRCRegClass;
2865           break;
2866         case MVT::v4f32:
2867           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2868           break;
2869         case MVT::v2f64:
2870         case MVT::v2i64:
2871           RC = &PPC::VSHRCRegClass;
2872           break;
2873         case MVT::v4f64:
2874           RC = &PPC::QFRCRegClass;
2875           break;
2876         case MVT::v4i1:
2877           RC = &PPC::QBRCRegClass;
2878           break;
2879       }
2880
2881       // Transform the arguments stored in physical registers into virtual ones.
2882       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2883       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2884                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2885
2886       if (ValVT == MVT::i1)
2887         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2888
2889       InVals.push_back(ArgValue);
2890     } else {
2891       // Argument stored in memory.
2892       assert(VA.isMemLoc());
2893
2894       unsigned ArgSize = VA.getLocVT().getStoreSize();
2895       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2896                                       isImmutable);
2897
2898       // Create load nodes to retrieve arguments from the stack.
2899       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2900       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2901                                    MachinePointerInfo(),
2902                                    false, false, false, 0));
2903     }
2904   }
2905
2906   // Assign locations to all of the incoming aggregate by value arguments.
2907   // Aggregates passed by value are stored in the local variable space of the
2908   // caller's stack frame, right above the parameter list area.
2909   SmallVector<CCValAssign, 16> ByValArgLocs;
2910   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2911                       ByValArgLocs, *DAG.getContext());
2912
2913   // Reserve stack space for the allocations in CCInfo.
2914   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2915
2916   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2917
2918   // Area that is at least reserved in the caller of this function.
2919   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2920   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2921
2922   // Set the size that is at least reserved in caller of this function.  Tail
2923   // call optimized function's reserved stack space needs to be aligned so that
2924   // taking the difference between two stack areas will result in an aligned
2925   // stack.
2926   MinReservedArea =
2927       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2928   FuncInfo->setMinReservedArea(MinReservedArea);
2929
2930   SmallVector<SDValue, 8> MemOps;
2931
2932   // If the function takes variable number of arguments, make a frame index for
2933   // the start of the first vararg value... for expansion of llvm.va_start.
2934   if (isVarArg) {
2935     static const MCPhysReg GPArgRegs[] = {
2936       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2937       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2938     };
2939     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2940
2941     static const MCPhysReg FPArgRegs[] = {
2942       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2943       PPC::F8
2944     };
2945     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2946     if (DisablePPCFloatInVariadic)
2947       NumFPArgRegs = 0;
2948
2949     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2950     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2951
2952     // Make room for NumGPArgRegs and NumFPArgRegs.
2953     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2954                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2955
2956     FuncInfo->setVarArgsStackOffset(
2957       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2958                              CCInfo.getNextStackOffset(), true));
2959
2960     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2961     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2962
2963     // The fixed integer arguments of a variadic function are stored to the
2964     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2965     // the result of va_next.
2966     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2967       // Get an existing live-in vreg, or add a new one.
2968       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2969       if (!VReg)
2970         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2971
2972       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2973       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2974                                    MachinePointerInfo(), false, false, 0);
2975       MemOps.push_back(Store);
2976       // Increment the address by four for the next argument to store
2977       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2978       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2979     }
2980
2981     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2982     // is set.
2983     // The double arguments are stored to the VarArgsFrameIndex
2984     // on the stack.
2985     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2986       // Get an existing live-in vreg, or add a new one.
2987       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2988       if (!VReg)
2989         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2990
2991       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2992       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2993                                    MachinePointerInfo(), false, false, 0);
2994       MemOps.push_back(Store);
2995       // Increment the address by eight for the next argument to store
2996       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2997                                          PtrVT);
2998       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2999     }
3000   }
3001
3002   if (!MemOps.empty())
3003     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3004
3005   return Chain;
3006 }
3007
3008 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3009 // value to MVT::i64 and then truncate to the correct register size.
3010 SDValue
3011 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
3012                                      SelectionDAG &DAG, SDValue ArgVal,
3013                                      SDLoc dl) const {
3014   if (Flags.isSExt())
3015     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3016                          DAG.getValueType(ObjectVT));
3017   else if (Flags.isZExt())
3018     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3019                          DAG.getValueType(ObjectVT));
3020
3021   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3022 }
3023
3024 SDValue
3025 PPCTargetLowering::LowerFormalArguments_64SVR4(
3026                                       SDValue Chain,
3027                                       CallingConv::ID CallConv, bool isVarArg,
3028                                       const SmallVectorImpl<ISD::InputArg>
3029                                         &Ins,
3030                                       SDLoc dl, SelectionDAG &DAG,
3031                                       SmallVectorImpl<SDValue> &InVals) const {
3032   // TODO: add description of PPC stack frame format, or at least some docs.
3033   //
3034   bool isELFv2ABI = Subtarget.isELFv2ABI();
3035   bool isLittleEndian = Subtarget.isLittleEndian();
3036   MachineFunction &MF = DAG.getMachineFunction();
3037   MachineFrameInfo *MFI = MF.getFrameInfo();
3038   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3039
3040   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3041          "fastcc not supported on varargs functions");
3042
3043   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3044   // Potential tail calls could cause overwriting of argument stack slots.
3045   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3046                        (CallConv == CallingConv::Fast));
3047   unsigned PtrByteSize = 8;
3048   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3049
3050   static const MCPhysReg GPR[] = {
3051     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3052     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3053   };
3054   static const MCPhysReg VR[] = {
3055     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3056     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3057   };
3058   static const MCPhysReg VSRH[] = {
3059     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3060     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3061   };
3062
3063   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3064   const unsigned Num_FPR_Regs = 13;
3065   const unsigned Num_VR_Regs  = array_lengthof(VR);
3066   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3067
3068   // Do a first pass over the arguments to determine whether the ABI
3069   // guarantees that our caller has allocated the parameter save area
3070   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3071   // in the ELFv2 ABI, it is true if this is a vararg function or if
3072   // any parameter is located in a stack slot.
3073
3074   bool HasParameterArea = !isELFv2ABI || isVarArg;
3075   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3076   unsigned NumBytes = LinkageSize;
3077   unsigned AvailableFPRs = Num_FPR_Regs;
3078   unsigned AvailableVRs = Num_VR_Regs;
3079   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3080     if (Ins[i].Flags.isNest())
3081       continue;
3082
3083     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3084                                PtrByteSize, LinkageSize, ParamAreaSize,
3085                                NumBytes, AvailableFPRs, AvailableVRs,
3086                                Subtarget.hasQPX()))
3087       HasParameterArea = true;
3088   }
3089
3090   // Add DAG nodes to load the arguments or copy them out of registers.  On
3091   // entry to a function on PPC, the arguments start after the linkage area,
3092   // although the first ones are often in registers.
3093
3094   unsigned ArgOffset = LinkageSize;
3095   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3096   unsigned &QFPR_idx = FPR_idx;
3097   SmallVector<SDValue, 8> MemOps;
3098   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3099   unsigned CurArgIdx = 0;
3100   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3101     SDValue ArgVal;
3102     bool needsLoad = false;
3103     EVT ObjectVT = Ins[ArgNo].VT;
3104     EVT OrigVT = Ins[ArgNo].ArgVT;
3105     unsigned ObjSize = ObjectVT.getStoreSize();
3106     unsigned ArgSize = ObjSize;
3107     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3108     if (Ins[ArgNo].isOrigArg()) {
3109       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3110       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3111     }
3112     // We re-align the argument offset for each argument, except when using the
3113     // fast calling convention, when we need to make sure we do that only when
3114     // we'll actually use a stack slot.
3115     unsigned CurArgOffset, Align;
3116     auto ComputeArgOffset = [&]() {
3117       /* Respect alignment of argument on the stack.  */
3118       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3119       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3120       CurArgOffset = ArgOffset;
3121     };
3122
3123     if (CallConv != CallingConv::Fast) {
3124       ComputeArgOffset();
3125
3126       /* Compute GPR index associated with argument offset.  */
3127       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3128       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3129     }
3130
3131     // FIXME the codegen can be much improved in some cases.
3132     // We do not have to keep everything in memory.
3133     if (Flags.isByVal()) {
3134       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3135
3136       if (CallConv == CallingConv::Fast)
3137         ComputeArgOffset();
3138
3139       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3140       ObjSize = Flags.getByValSize();
3141       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3142       // Empty aggregate parameters do not take up registers.  Examples:
3143       //   struct { } a;
3144       //   union  { } b;
3145       //   int c[0];
3146       // etc.  However, we have to provide a place-holder in InVals, so
3147       // pretend we have an 8-byte item at the current address for that
3148       // purpose.
3149       if (!ObjSize) {
3150         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3151         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3152         InVals.push_back(FIN);
3153         continue;
3154       }
3155
3156       // Create a stack object covering all stack doublewords occupied
3157       // by the argument.  If the argument is (fully or partially) on
3158       // the stack, or if the argument is fully in registers but the
3159       // caller has allocated the parameter save anyway, we can refer
3160       // directly to the caller's stack frame.  Otherwise, create a
3161       // local copy in our own frame.
3162       int FI;
3163       if (HasParameterArea ||
3164           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3165         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3166       else
3167         FI = MFI->CreateStackObject(ArgSize, Align, false);
3168       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3169
3170       // Handle aggregates smaller than 8 bytes.
3171       if (ObjSize < PtrByteSize) {
3172         // The value of the object is its address, which differs from the
3173         // address of the enclosing doubleword on big-endian systems.
3174         SDValue Arg = FIN;
3175         if (!isLittleEndian) {
3176           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3177           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3178         }
3179         InVals.push_back(Arg);
3180
3181         if (GPR_idx != Num_GPR_Regs) {
3182           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3183           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3184           SDValue Store;
3185
3186           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3187             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3188                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3189             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3190                                       MachinePointerInfo(FuncArg),
3191                                       ObjType, false, false, 0);
3192           } else {
3193             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3194             // store the whole register as-is to the parameter save area
3195             // slot.
3196             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3197                                  MachinePointerInfo(FuncArg),
3198                                  false, false, 0);
3199           }
3200
3201           MemOps.push_back(Store);
3202         }
3203         // Whether we copied from a register or not, advance the offset
3204         // into the parameter save area by a full doubleword.
3205         ArgOffset += PtrByteSize;
3206         continue;
3207       }
3208
3209       // The value of the object is its address, which is the address of
3210       // its first stack doubleword.
3211       InVals.push_back(FIN);
3212
3213       // Store whatever pieces of the object are in registers to memory.
3214       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3215         if (GPR_idx == Num_GPR_Regs)
3216           break;
3217
3218         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3219         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3220         SDValue Addr = FIN;
3221         if (j) {
3222           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3223           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3224         }
3225         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3226                                      MachinePointerInfo(FuncArg, j),
3227                                      false, false, 0);
3228         MemOps.push_back(Store);
3229         ++GPR_idx;
3230       }
3231       ArgOffset += ArgSize;
3232       continue;
3233     }
3234
3235     switch (ObjectVT.getSimpleVT().SimpleTy) {
3236     default: llvm_unreachable("Unhandled argument type!");
3237     case MVT::i1:
3238     case MVT::i32:
3239     case MVT::i64:
3240       if (Flags.isNest()) {
3241         // The 'nest' parameter, if any, is passed in R11.
3242         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3243         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3244
3245         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3246           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3247
3248         break;
3249       }
3250
3251       // These can be scalar arguments or elements of an integer array type
3252       // passed directly.  Clang may use those instead of "byval" aggregate
3253       // types to avoid forcing arguments to memory unnecessarily.
3254       if (GPR_idx != Num_GPR_Regs) {
3255         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3256         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3257
3258         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3259           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3260           // value to MVT::i64 and then truncate to the correct register size.
3261           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3262       } else {
3263         if (CallConv == CallingConv::Fast)
3264           ComputeArgOffset();
3265
3266         needsLoad = true;
3267         ArgSize = PtrByteSize;
3268       }
3269       if (CallConv != CallingConv::Fast || needsLoad)
3270         ArgOffset += 8;
3271       break;
3272
3273     case MVT::f32:
3274     case MVT::f64:
3275       // These can be scalar arguments or elements of a float array type
3276       // passed directly.  The latter are used to implement ELFv2 homogenous
3277       // float aggregates.
3278       if (FPR_idx != Num_FPR_Regs) {
3279         unsigned VReg;
3280
3281         if (ObjectVT == MVT::f32)
3282           VReg = MF.addLiveIn(FPR[FPR_idx],
3283                               Subtarget.hasP8Vector()
3284                                   ? &PPC::VSSRCRegClass
3285                                   : &PPC::F4RCRegClass);
3286         else
3287           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3288                                                 ? &PPC::VSFRCRegClass
3289                                                 : &PPC::F8RCRegClass);
3290
3291         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3292         ++FPR_idx;
3293       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3294         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3295         // once we support fp <-> gpr moves.
3296
3297         // This can only ever happen in the presence of f32 array types,
3298         // since otherwise we never run out of FPRs before running out
3299         // of GPRs.
3300         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3301         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3302
3303         if (ObjectVT == MVT::f32) {
3304           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3305             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3306                                  DAG.getConstant(32, dl, MVT::i32));
3307           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3308         }
3309
3310         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3311       } else {
3312         if (CallConv == CallingConv::Fast)
3313           ComputeArgOffset();
3314
3315         needsLoad = true;
3316       }
3317
3318       // When passing an array of floats, the array occupies consecutive
3319       // space in the argument area; only round up to the next doubleword
3320       // at the end of the array.  Otherwise, each float takes 8 bytes.
3321       if (CallConv != CallingConv::Fast || needsLoad) {
3322         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3323         ArgOffset += ArgSize;
3324         if (Flags.isInConsecutiveRegsLast())
3325           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3326       }
3327       break;
3328     case MVT::v4f32:
3329     case MVT::v4i32:
3330     case MVT::v8i16:
3331     case MVT::v16i8:
3332     case MVT::v2f64:
3333     case MVT::v2i64:
3334     case MVT::v1i128:
3335       if (!Subtarget.hasQPX()) {
3336       // These can be scalar arguments or elements of a vector array type
3337       // passed directly.  The latter are used to implement ELFv2 homogenous
3338       // vector aggregates.
3339       if (VR_idx != Num_VR_Regs) {
3340         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3341                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3342                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3343         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3344         ++VR_idx;
3345       } else {
3346         if (CallConv == CallingConv::Fast)
3347           ComputeArgOffset();
3348
3349         needsLoad = true;
3350       }
3351       if (CallConv != CallingConv::Fast || needsLoad)
3352         ArgOffset += 16;
3353       break;
3354       } // not QPX
3355
3356       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3357              "Invalid QPX parameter type");
3358       /* fall through */
3359
3360     case MVT::v4f64:
3361     case MVT::v4i1:
3362       // QPX vectors are treated like their scalar floating-point subregisters
3363       // (except that they're larger).
3364       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3365       if (QFPR_idx != Num_QFPR_Regs) {
3366         const TargetRegisterClass *RC;
3367         switch (ObjectVT.getSimpleVT().SimpleTy) {
3368         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3369         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3370         default:         RC = &PPC::QBRCRegClass; break;
3371         }
3372
3373         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3374         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3375         ++QFPR_idx;
3376       } else {
3377         if (CallConv == CallingConv::Fast)
3378           ComputeArgOffset();
3379         needsLoad = true;
3380       }
3381       if (CallConv != CallingConv::Fast || needsLoad)
3382         ArgOffset += Sz;
3383       break;
3384     }
3385
3386     // We need to load the argument to a virtual register if we determined
3387     // above that we ran out of physical registers of the appropriate type.
3388     if (needsLoad) {
3389       if (ObjSize < ArgSize && !isLittleEndian)
3390         CurArgOffset += ArgSize - ObjSize;
3391       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3392       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3393       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3394                            false, false, false, 0);
3395     }
3396
3397     InVals.push_back(ArgVal);
3398   }
3399
3400   // Area that is at least reserved in the caller of this function.
3401   unsigned MinReservedArea;
3402   if (HasParameterArea)
3403     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3404   else
3405     MinReservedArea = LinkageSize;
3406
3407   // Set the size that is at least reserved in caller of this function.  Tail
3408   // call optimized functions' reserved stack space needs to be aligned so that
3409   // taking the difference between two stack areas will result in an aligned
3410   // stack.
3411   MinReservedArea =
3412       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3413   FuncInfo->setMinReservedArea(MinReservedArea);
3414
3415   // If the function takes variable number of arguments, make a frame index for
3416   // the start of the first vararg value... for expansion of llvm.va_start.
3417   if (isVarArg) {
3418     int Depth = ArgOffset;
3419
3420     FuncInfo->setVarArgsFrameIndex(
3421       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3422     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3423
3424     // If this function is vararg, store any remaining integer argument regs
3425     // to their spots on the stack so that they may be loaded by deferencing the
3426     // result of va_next.
3427     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3428          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3429       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3430       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3431       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3432                                    MachinePointerInfo(), false, false, 0);
3433       MemOps.push_back(Store);
3434       // Increment the address by four for the next argument to store
3435       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3436       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3437     }
3438   }
3439
3440   if (!MemOps.empty())
3441     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3442
3443   return Chain;
3444 }
3445
3446 SDValue
3447 PPCTargetLowering::LowerFormalArguments_Darwin(
3448                                       SDValue Chain,
3449                                       CallingConv::ID CallConv, bool isVarArg,
3450                                       const SmallVectorImpl<ISD::InputArg>
3451                                         &Ins,
3452                                       SDLoc dl, SelectionDAG &DAG,
3453                                       SmallVectorImpl<SDValue> &InVals) const {
3454   // TODO: add description of PPC stack frame format, or at least some docs.
3455   //
3456   MachineFunction &MF = DAG.getMachineFunction();
3457   MachineFrameInfo *MFI = MF.getFrameInfo();
3458   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3459
3460   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3461   bool isPPC64 = PtrVT == MVT::i64;
3462   // Potential tail calls could cause overwriting of argument stack slots.
3463   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3464                        (CallConv == CallingConv::Fast));
3465   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3466   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3467   unsigned ArgOffset = LinkageSize;
3468   // Area that is at least reserved in caller of this function.
3469   unsigned MinReservedArea = ArgOffset;
3470
3471   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3472     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3473     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3474   };
3475   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3476     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3477     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3478   };
3479   static const MCPhysReg VR[] = {
3480     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3481     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3482   };
3483
3484   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3485   const unsigned Num_FPR_Regs = 13;
3486   const unsigned Num_VR_Regs  = array_lengthof( VR);
3487
3488   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3489
3490   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3491
3492   // In 32-bit non-varargs functions, the stack space for vectors is after the
3493   // stack space for non-vectors.  We do not use this space unless we have
3494   // too many vectors to fit in registers, something that only occurs in
3495   // constructed examples:), but we have to walk the arglist to figure
3496   // that out...for the pathological case, compute VecArgOffset as the
3497   // start of the vector parameter area.  Computing VecArgOffset is the
3498   // entire point of the following loop.
3499   unsigned VecArgOffset = ArgOffset;
3500   if (!isVarArg && !isPPC64) {
3501     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3502          ++ArgNo) {
3503       EVT ObjectVT = Ins[ArgNo].VT;
3504       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3505
3506       if (Flags.isByVal()) {
3507         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3508         unsigned ObjSize = Flags.getByValSize();
3509         unsigned ArgSize =
3510                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3511         VecArgOffset += ArgSize;
3512         continue;
3513       }
3514
3515       switch(ObjectVT.getSimpleVT().SimpleTy) {
3516       default: llvm_unreachable("Unhandled argument type!");
3517       case MVT::i1:
3518       case MVT::i32:
3519       case MVT::f32:
3520         VecArgOffset += 4;
3521         break;
3522       case MVT::i64:  // PPC64
3523       case MVT::f64:
3524         // FIXME: We are guaranteed to be !isPPC64 at this point.
3525         // Does MVT::i64 apply?
3526         VecArgOffset += 8;
3527         break;
3528       case MVT::v4f32:
3529       case MVT::v4i32:
3530       case MVT::v8i16:
3531       case MVT::v16i8:
3532         // Nothing to do, we're only looking at Nonvector args here.
3533         break;
3534       }
3535     }
3536   }
3537   // We've found where the vector parameter area in memory is.  Skip the
3538   // first 12 parameters; these don't use that memory.
3539   VecArgOffset = ((VecArgOffset+15)/16)*16;
3540   VecArgOffset += 12*16;
3541
3542   // Add DAG nodes to load the arguments or copy them out of registers.  On
3543   // entry to a function on PPC, the arguments start after the linkage area,
3544   // although the first ones are often in registers.
3545
3546   SmallVector<SDValue, 8> MemOps;
3547   unsigned nAltivecParamsAtEnd = 0;
3548   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3549   unsigned CurArgIdx = 0;
3550   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3551     SDValue ArgVal;
3552     bool needsLoad = false;
3553     EVT ObjectVT = Ins[ArgNo].VT;
3554     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3555     unsigned ArgSize = ObjSize;
3556     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3557     if (Ins[ArgNo].isOrigArg()) {
3558       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3559       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3560     }
3561     unsigned CurArgOffset = ArgOffset;
3562
3563     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3564     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3565         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3566       if (isVarArg || isPPC64) {
3567         MinReservedArea = ((MinReservedArea+15)/16)*16;
3568         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3569                                                   Flags,
3570                                                   PtrByteSize);
3571       } else  nAltivecParamsAtEnd++;
3572     } else
3573       // Calculate min reserved area.
3574       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3575                                                 Flags,
3576                                                 PtrByteSize);
3577
3578     // FIXME the codegen can be much improved in some cases.
3579     // We do not have to keep everything in memory.
3580     if (Flags.isByVal()) {
3581       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3582
3583       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3584       ObjSize = Flags.getByValSize();
3585       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3586       // Objects of size 1 and 2 are right justified, everything else is
3587       // left justified.  This means the memory address is adjusted forwards.
3588       if (ObjSize==1 || ObjSize==2) {
3589         CurArgOffset = CurArgOffset + (4 - ObjSize);
3590       }
3591       // The value of the object is its address.
3592       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3593       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3594       InVals.push_back(FIN);
3595       if (ObjSize==1 || ObjSize==2) {
3596         if (GPR_idx != Num_GPR_Regs) {
3597           unsigned VReg;
3598           if (isPPC64)
3599             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3600           else
3601             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3602           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3603           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3604           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3605                                             MachinePointerInfo(FuncArg),
3606                                             ObjType, false, false, 0);
3607           MemOps.push_back(Store);
3608           ++GPR_idx;
3609         }
3610
3611         ArgOffset += PtrByteSize;
3612
3613         continue;
3614       }
3615       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3616         // Store whatever pieces of the object are in registers
3617         // to memory.  ArgOffset will be the address of the beginning
3618         // of the object.
3619         if (GPR_idx != Num_GPR_Regs) {
3620           unsigned VReg;
3621           if (isPPC64)
3622             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3623           else
3624             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3625           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3626           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3627           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3628           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3629                                        MachinePointerInfo(FuncArg, j),
3630                                        false, false, 0);
3631           MemOps.push_back(Store);
3632           ++GPR_idx;
3633           ArgOffset += PtrByteSize;
3634         } else {
3635           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3636           break;
3637         }
3638       }
3639       continue;
3640     }
3641
3642     switch (ObjectVT.getSimpleVT().SimpleTy) {
3643     default: llvm_unreachable("Unhandled argument type!");
3644     case MVT::i1:
3645     case MVT::i32:
3646       if (!isPPC64) {
3647         if (GPR_idx != Num_GPR_Regs) {
3648           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3649           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3650
3651           if (ObjectVT == MVT::i1)
3652             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3653
3654           ++GPR_idx;
3655         } else {
3656           needsLoad = true;
3657           ArgSize = PtrByteSize;
3658         }
3659         // All int arguments reserve stack space in the Darwin ABI.
3660         ArgOffset += PtrByteSize;
3661         break;
3662       }
3663       // FALLTHROUGH
3664     case MVT::i64:  // PPC64
3665       if (GPR_idx != Num_GPR_Regs) {
3666         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3667         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3668
3669         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3670           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3671           // value to MVT::i64 and then truncate to the correct register size.
3672           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3673
3674         ++GPR_idx;
3675       } else {
3676         needsLoad = true;
3677         ArgSize = PtrByteSize;
3678       }
3679       // All int arguments reserve stack space in the Darwin ABI.
3680       ArgOffset += 8;
3681       break;
3682
3683     case MVT::f32:
3684     case MVT::f64:
3685       // Every 4 bytes of argument space consumes one of the GPRs available for
3686       // argument passing.
3687       if (GPR_idx != Num_GPR_Regs) {
3688         ++GPR_idx;
3689         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3690           ++GPR_idx;
3691       }
3692       if (FPR_idx != Num_FPR_Regs) {
3693         unsigned VReg;
3694
3695         if (ObjectVT == MVT::f32)
3696           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3697         else
3698           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3699
3700         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3701         ++FPR_idx;
3702       } else {
3703         needsLoad = true;
3704       }
3705
3706       // All FP arguments reserve stack space in the Darwin ABI.
3707       ArgOffset += isPPC64 ? 8 : ObjSize;
3708       break;
3709     case MVT::v4f32:
3710     case MVT::v4i32:
3711     case MVT::v8i16:
3712     case MVT::v16i8:
3713       // Note that vector arguments in registers don't reserve stack space,
3714       // except in varargs functions.
3715       if (VR_idx != Num_VR_Regs) {
3716         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3717         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3718         if (isVarArg) {
3719           while ((ArgOffset % 16) != 0) {
3720             ArgOffset += PtrByteSize;
3721             if (GPR_idx != Num_GPR_Regs)
3722               GPR_idx++;
3723           }
3724           ArgOffset += 16;
3725           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3726         }
3727         ++VR_idx;
3728       } else {
3729         if (!isVarArg && !isPPC64) {
3730           // Vectors go after all the nonvectors.
3731           CurArgOffset = VecArgOffset;
3732           VecArgOffset += 16;
3733         } else {
3734           // Vectors are aligned.
3735           ArgOffset = ((ArgOffset+15)/16)*16;
3736           CurArgOffset = ArgOffset;
3737           ArgOffset += 16;
3738         }
3739         needsLoad = true;
3740       }
3741       break;
3742     }
3743
3744     // We need to load the argument to a virtual register if we determined above
3745     // that we ran out of physical registers of the appropriate type.
3746     if (needsLoad) {
3747       int FI = MFI->CreateFixedObject(ObjSize,
3748                                       CurArgOffset + (ArgSize - ObjSize),
3749                                       isImmutable);
3750       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3751       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3752                            false, false, false, 0);
3753     }
3754
3755     InVals.push_back(ArgVal);
3756   }
3757
3758   // Allow for Altivec parameters at the end, if needed.
3759   if (nAltivecParamsAtEnd) {
3760     MinReservedArea = ((MinReservedArea+15)/16)*16;
3761     MinReservedArea += 16*nAltivecParamsAtEnd;
3762   }
3763
3764   // Area that is at least reserved in the caller of this function.
3765   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3766
3767   // Set the size that is at least reserved in caller of this function.  Tail
3768   // call optimized functions' reserved stack space needs to be aligned so that
3769   // taking the difference between two stack areas will result in an aligned
3770   // stack.
3771   MinReservedArea =
3772       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3773   FuncInfo->setMinReservedArea(MinReservedArea);
3774
3775   // If the function takes variable number of arguments, make a frame index for
3776   // the start of the first vararg value... for expansion of llvm.va_start.
3777   if (isVarArg) {
3778     int Depth = ArgOffset;
3779
3780     FuncInfo->setVarArgsFrameIndex(
3781       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3782                              Depth, true));
3783     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3784
3785     // If this function is vararg, store any remaining integer argument regs
3786     // to their spots on the stack so that they may be loaded by deferencing the
3787     // result of va_next.
3788     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3789       unsigned VReg;
3790
3791       if (isPPC64)
3792         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3793       else
3794         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3795
3796       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3797       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3798                                    MachinePointerInfo(), false, false, 0);
3799       MemOps.push_back(Store);
3800       // Increment the address by four for the next argument to store
3801       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3802       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3803     }
3804   }
3805
3806   if (!MemOps.empty())
3807     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3808
3809   return Chain;
3810 }
3811
3812 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3813 /// adjusted to accommodate the arguments for the tailcall.
3814 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3815                                    unsigned ParamSize) {
3816
3817   if (!isTailCall) return 0;
3818
3819   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3820   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3821   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3822   // Remember only if the new adjustement is bigger.
3823   if (SPDiff < FI->getTailCallSPDelta())
3824     FI->setTailCallSPDelta(SPDiff);
3825
3826   return SPDiff;
3827 }
3828
3829 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3830 /// for tail call optimization. Targets which want to do tail call
3831 /// optimization should implement this function.
3832 bool
3833 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3834                                                      CallingConv::ID CalleeCC,
3835                                                      bool isVarArg,
3836                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3837                                                      SelectionDAG& DAG) const {
3838   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3839     return false;
3840
3841   // Variable argument functions are not supported.
3842   if (isVarArg)
3843     return false;
3844
3845   MachineFunction &MF = DAG.getMachineFunction();
3846   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3847   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3848     // Functions containing by val parameters are not supported.
3849     for (unsigned i = 0; i != Ins.size(); i++) {
3850        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3851        if (Flags.isByVal()) return false;
3852     }
3853
3854     // Non-PIC/GOT tail calls are supported.
3855     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3856       return true;
3857
3858     // At the moment we can only do local tail calls (in same module, hidden
3859     // or protected) if we are generating PIC.
3860     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3861       return G->getGlobal()->hasHiddenVisibility()
3862           || G->getGlobal()->hasProtectedVisibility();
3863   }
3864
3865   return false;
3866 }
3867
3868 /// isCallCompatibleAddress - Return the immediate to use if the specified
3869 /// 32-bit value is representable in the immediate field of a BxA instruction.
3870 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3871   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3872   if (!C) return nullptr;
3873
3874   int Addr = C->getZExtValue();
3875   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3876       SignExtend32<26>(Addr) != Addr)
3877     return nullptr;  // Top 6 bits have to be sext of immediate.
3878
3879   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3880                          DAG.getTargetLoweringInfo().getPointerTy(
3881                              DAG.getDataLayout())).getNode();
3882 }
3883
3884 namespace {
3885
3886 struct TailCallArgumentInfo {
3887   SDValue Arg;
3888   SDValue FrameIdxOp;
3889   int       FrameIdx;
3890
3891   TailCallArgumentInfo() : FrameIdx(0) {}
3892 };
3893
3894 }
3895
3896 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3897 static void
3898 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3899                                            SDValue Chain,
3900                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3901                    SmallVectorImpl<SDValue> &MemOpChains,
3902                    SDLoc dl) {
3903   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3904     SDValue Arg = TailCallArgs[i].Arg;
3905     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3906     int FI = TailCallArgs[i].FrameIdx;
3907     // Store relative to framepointer.
3908     MemOpChains.push_back(DAG.getStore(
3909         Chain, dl, Arg, FIN,
3910         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3911         false, 0));
3912   }
3913 }
3914
3915 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3916 /// the appropriate stack slot for the tail call optimized function call.
3917 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3918                                                MachineFunction &MF,
3919                                                SDValue Chain,
3920                                                SDValue OldRetAddr,
3921                                                SDValue OldFP,
3922                                                int SPDiff,
3923                                                bool isPPC64,
3924                                                bool isDarwinABI,
3925                                                SDLoc dl) {
3926   if (SPDiff) {
3927     // Calculate the new stack slot for the return address.
3928     int SlotSize = isPPC64 ? 8 : 4;
3929     const PPCFrameLowering *FL =
3930         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3931     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3932     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3933                                                           NewRetAddrLoc, true);
3934     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3935     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3936     Chain = DAG.getStore(
3937         Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3938         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewRetAddr),
3939         false, false, 0);
3940
3941     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3942     // slot as the FP is never overwritten.
3943     if (isDarwinABI) {
3944       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3945       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3946                                                           true);
3947       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3948       Chain = DAG.getStore(
3949           Chain, dl, OldFP, NewFramePtrIdx,
3950           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx),
3951           false, false, 0);
3952     }
3953   }
3954   return Chain;
3955 }
3956
3957 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3958 /// the position of the argument.
3959 static void
3960 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3961                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3962                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3963   int Offset = ArgOffset + SPDiff;
3964   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3965   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3966   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3967   SDValue FIN = DAG.getFrameIndex(FI, VT);
3968   TailCallArgumentInfo Info;
3969   Info.Arg = Arg;
3970   Info.FrameIdxOp = FIN;
3971   Info.FrameIdx = FI;
3972   TailCallArguments.push_back(Info);
3973 }
3974
3975 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3976 /// stack slot. Returns the chain as result and the loaded frame pointers in
3977 /// LROpOut/FPOpout. Used when tail calling.
3978 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3979                                                         int SPDiff,
3980                                                         SDValue Chain,
3981                                                         SDValue &LROpOut,
3982                                                         SDValue &FPOpOut,
3983                                                         bool isDarwinABI,
3984                                                         SDLoc dl) const {
3985   if (SPDiff) {
3986     // Load the LR and FP stack slot for later adjusting.
3987     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3988     LROpOut = getReturnAddrFrameIndex(DAG);
3989     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3990                           false, false, false, 0);
3991     Chain = SDValue(LROpOut.getNode(), 1);
3992
3993     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3994     // slot as the FP is never overwritten.
3995     if (isDarwinABI) {
3996       FPOpOut = getFramePointerFrameIndex(DAG);
3997       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3998                             false, false, false, 0);
3999       Chain = SDValue(FPOpOut.getNode(), 1);
4000     }
4001   }
4002   return Chain;
4003 }
4004
4005 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4006 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4007 /// specified by the specific parameter attribute. The copy will be passed as
4008 /// a byval function parameter.
4009 /// Sometimes what we are copying is the end of a larger object, the part that
4010 /// does not fit in registers.
4011 static SDValue
4012 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
4013                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
4014                           SDLoc dl) {
4015   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4016   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4017                        false, false, false, MachinePointerInfo(),
4018                        MachinePointerInfo());
4019 }
4020
4021 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4022 /// tail calls.
4023 static void
4024 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
4025                  SDValue Arg, SDValue PtrOff, int SPDiff,
4026                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
4027                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4028                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
4029                  SDLoc dl) {
4030   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4031   if (!isTailCall) {
4032     if (isVector) {
4033       SDValue StackPtr;
4034       if (isPPC64)
4035         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4036       else
4037         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4038       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4039                            DAG.getConstant(ArgOffset, dl, PtrVT));
4040     }
4041     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4042                                        MachinePointerInfo(), false, false, 0));
4043   // Calculate and remember argument location.
4044   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4045                                   TailCallArguments);
4046 }
4047
4048 static
4049 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4050                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
4051                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
4052                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4053   MachineFunction &MF = DAG.getMachineFunction();
4054
4055   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4056   // might overwrite each other in case of tail call optimization.
4057   SmallVector<SDValue, 8> MemOpChains2;
4058   // Do not flag preceding copytoreg stuff together with the following stuff.
4059   InFlag = SDValue();
4060   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4061                                     MemOpChains2, dl);
4062   if (!MemOpChains2.empty())
4063     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4064
4065   // Store the return address to the appropriate stack slot.
4066   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
4067                                         isPPC64, isDarwinABI, dl);
4068
4069   // Emit callseq_end just before tailcall node.
4070   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4071                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4072   InFlag = Chain.getValue(1);
4073 }
4074
4075 // Is this global address that of a function that can be called by name? (as
4076 // opposed to something that must hold a descriptor for an indirect call).
4077 static bool isFunctionGlobalAddress(SDValue Callee) {
4078   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4079     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4080         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4081       return false;
4082
4083     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
4084   }
4085
4086   return false;
4087 }
4088
4089 static
4090 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
4091                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
4092                      bool isTailCall, bool IsPatchPoint, bool hasNest,
4093                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
4094                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4095                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4096
4097   bool isPPC64 = Subtarget.isPPC64();
4098   bool isSVR4ABI = Subtarget.isSVR4ABI();
4099   bool isELFv2ABI = Subtarget.isELFv2ABI();
4100
4101   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4102   NodeTys.push_back(MVT::Other);   // Returns a chain
4103   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4104
4105   unsigned CallOpc = PPCISD::CALL;
4106
4107   bool needIndirectCall = true;
4108   if (!isSVR4ABI || !isPPC64)
4109     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4110       // If this is an absolute destination address, use the munged value.
4111       Callee = SDValue(Dest, 0);
4112       needIndirectCall = false;
4113     }
4114
4115   if (isFunctionGlobalAddress(Callee)) {
4116     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4117     // A call to a TLS address is actually an indirect call to a
4118     // thread-specific pointer.
4119     unsigned OpFlags = 0;
4120     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4121          (Subtarget.getTargetTriple().isMacOSX() &&
4122           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
4123          !G->getGlobal()->isStrongDefinitionForLinker()) ||
4124         (Subtarget.isTargetELF() && !isPPC64 &&
4125          !G->getGlobal()->hasLocalLinkage() &&
4126          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4127       // PC-relative references to external symbols should go through $stub,
4128       // unless we're building with the leopard linker or later, which
4129       // automatically synthesizes these stubs.
4130       OpFlags = PPCII::MO_PLT_OR_STUB;
4131     }
4132
4133     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4134     // every direct call is) turn it into a TargetGlobalAddress /
4135     // TargetExternalSymbol node so that legalize doesn't hack it.
4136     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4137                                         Callee.getValueType(), 0, OpFlags);
4138     needIndirectCall = false;
4139   }
4140
4141   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4142     unsigned char OpFlags = 0;
4143
4144     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4145          (Subtarget.getTargetTriple().isMacOSX() &&
4146           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4147         (Subtarget.isTargetELF() && !isPPC64 &&
4148          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4149       // PC-relative references to external symbols should go through $stub,
4150       // unless we're building with the leopard linker or later, which
4151       // automatically synthesizes these stubs.
4152       OpFlags = PPCII::MO_PLT_OR_STUB;
4153     }
4154
4155     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4156                                          OpFlags);
4157     needIndirectCall = false;
4158   }
4159
4160   if (IsPatchPoint) {
4161     // We'll form an invalid direct call when lowering a patchpoint; the full
4162     // sequence for an indirect call is complicated, and many of the
4163     // instructions introduced might have side effects (and, thus, can't be
4164     // removed later). The call itself will be removed as soon as the
4165     // argument/return lowering is complete, so the fact that it has the wrong
4166     // kind of operands should not really matter.
4167     needIndirectCall = false;
4168   }
4169
4170   if (needIndirectCall) {
4171     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4172     // to do the call, we can't use PPCISD::CALL.
4173     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4174
4175     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4176       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4177       // entry point, but to the function descriptor (the function entry point
4178       // address is part of the function descriptor though).
4179       // The function descriptor is a three doubleword structure with the
4180       // following fields: function entry point, TOC base address and
4181       // environment pointer.
4182       // Thus for a call through a function pointer, the following actions need
4183       // to be performed:
4184       //   1. Save the TOC of the caller in the TOC save area of its stack
4185       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4186       //   2. Load the address of the function entry point from the function
4187       //      descriptor.
4188       //   3. Load the TOC of the callee from the function descriptor into r2.
4189       //   4. Load the environment pointer from the function descriptor into
4190       //      r11.
4191       //   5. Branch to the function entry point address.
4192       //   6. On return of the callee, the TOC of the caller needs to be
4193       //      restored (this is done in FinishCall()).
4194       //
4195       // The loads are scheduled at the beginning of the call sequence, and the
4196       // register copies are flagged together to ensure that no other
4197       // operations can be scheduled in between. E.g. without flagging the
4198       // copies together, a TOC access in the caller could be scheduled between
4199       // the assignment of the callee TOC and the branch to the callee, which
4200       // results in the TOC access going through the TOC of the callee instead
4201       // of going through the TOC of the caller, which leads to incorrect code.
4202
4203       // Load the address of the function entry point from the function
4204       // descriptor.
4205       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4206       if (LDChain.getValueType() == MVT::Glue)
4207         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4208
4209       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4210
4211       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4212       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4213                                         false, false, LoadsInv, 8);
4214
4215       // Load environment pointer into r11.
4216       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4217       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4218       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4219                                        MPI.getWithOffset(16), false, false,
4220                                        LoadsInv, 8);
4221
4222       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4223       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4224       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4225                                    MPI.getWithOffset(8), false, false,
4226                                    LoadsInv, 8);
4227
4228       setUsesTOCBasePtr(DAG);
4229       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4230                                         InFlag);
4231       Chain = TOCVal.getValue(0);
4232       InFlag = TOCVal.getValue(1);
4233
4234       // If the function call has an explicit 'nest' parameter, it takes the
4235       // place of the environment pointer.
4236       if (!hasNest) {
4237         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4238                                           InFlag);
4239
4240         Chain = EnvVal.getValue(0);
4241         InFlag = EnvVal.getValue(1);
4242       }
4243
4244       MTCTROps[0] = Chain;
4245       MTCTROps[1] = LoadFuncPtr;
4246       MTCTROps[2] = InFlag;
4247     }
4248
4249     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4250                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4251     InFlag = Chain.getValue(1);
4252
4253     NodeTys.clear();
4254     NodeTys.push_back(MVT::Other);
4255     NodeTys.push_back(MVT::Glue);
4256     Ops.push_back(Chain);
4257     CallOpc = PPCISD::BCTRL;
4258     Callee.setNode(nullptr);
4259     // Add use of X11 (holding environment pointer)
4260     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4261       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4262     // Add CTR register as callee so a bctr can be emitted later.
4263     if (isTailCall)
4264       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4265   }
4266
4267   // If this is a direct call, pass the chain and the callee.
4268   if (Callee.getNode()) {
4269     Ops.push_back(Chain);
4270     Ops.push_back(Callee);
4271   }
4272   // If this is a tail call add stack pointer delta.
4273   if (isTailCall)
4274     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4275
4276   // Add argument registers to the end of the list so that they are known live
4277   // into the call.
4278   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4279     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4280                                   RegsToPass[i].second.getValueType()));
4281
4282   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4283   // into the call.
4284   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4285     setUsesTOCBasePtr(DAG);
4286     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4287   }
4288
4289   return CallOpc;
4290 }
4291
4292 static
4293 bool isLocalCall(const SDValue &Callee)
4294 {
4295   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4296     return G->getGlobal()->isStrongDefinitionForLinker();
4297   return false;
4298 }
4299
4300 SDValue
4301 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4302                                    CallingConv::ID CallConv, bool isVarArg,
4303                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4304                                    SDLoc dl, SelectionDAG &DAG,
4305                                    SmallVectorImpl<SDValue> &InVals) const {
4306
4307   SmallVector<CCValAssign, 16> RVLocs;
4308   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4309                     *DAG.getContext());
4310   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4311
4312   // Copy all of the result registers out of their specified physreg.
4313   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4314     CCValAssign &VA = RVLocs[i];
4315     assert(VA.isRegLoc() && "Can only return in registers!");
4316
4317     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4318                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4319     Chain = Val.getValue(1);
4320     InFlag = Val.getValue(2);
4321
4322     switch (VA.getLocInfo()) {
4323     default: llvm_unreachable("Unknown loc info!");
4324     case CCValAssign::Full: break;
4325     case CCValAssign::AExt:
4326       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4327       break;
4328     case CCValAssign::ZExt:
4329       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4330                         DAG.getValueType(VA.getValVT()));
4331       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4332       break;
4333     case CCValAssign::SExt:
4334       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4335                         DAG.getValueType(VA.getValVT()));
4336       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4337       break;
4338     }
4339
4340     InVals.push_back(Val);
4341   }
4342
4343   return Chain;
4344 }
4345
4346 SDValue
4347 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4348                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4349                               bool hasNest, SelectionDAG &DAG,
4350                               SmallVector<std::pair<unsigned, SDValue>, 8>
4351                                 &RegsToPass,
4352                               SDValue InFlag, SDValue Chain,
4353                               SDValue CallSeqStart, SDValue &Callee,
4354                               int SPDiff, unsigned NumBytes,
4355                               const SmallVectorImpl<ISD::InputArg> &Ins,
4356                               SmallVectorImpl<SDValue> &InVals,
4357                               ImmutableCallSite *CS) const {
4358
4359   std::vector<EVT> NodeTys;
4360   SmallVector<SDValue, 8> Ops;
4361   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4362                                  SPDiff, isTailCall, IsPatchPoint, hasNest,
4363                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4364
4365   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4366   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4367     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4368
4369   // When performing tail call optimization the callee pops its arguments off
4370   // the stack. Account for this here so these bytes can be pushed back on in
4371   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4372   int BytesCalleePops =
4373     (CallConv == CallingConv::Fast &&
4374      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4375
4376   // Add a register mask operand representing the call-preserved registers.
4377   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4378   const uint32_t *Mask =
4379       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4380   assert(Mask && "Missing call preserved mask for calling convention");
4381   Ops.push_back(DAG.getRegisterMask(Mask));
4382
4383   if (InFlag.getNode())
4384     Ops.push_back(InFlag);
4385
4386   // Emit tail call.
4387   if (isTailCall) {
4388     assert(((Callee.getOpcode() == ISD::Register &&
4389              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4390             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4391             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4392             isa<ConstantSDNode>(Callee)) &&
4393     "Expecting an global address, external symbol, absolute value or register");
4394
4395     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4396     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4397   }
4398
4399   // Add a NOP immediately after the branch instruction when using the 64-bit
4400   // SVR4 ABI. At link time, if caller and callee are in a different module and
4401   // thus have a different TOC, the call will be replaced with a call to a stub
4402   // function which saves the current TOC, loads the TOC of the callee and
4403   // branches to the callee. The NOP will be replaced with a load instruction
4404   // which restores the TOC of the caller from the TOC save slot of the current
4405   // stack frame. If caller and callee belong to the same module (and have the
4406   // same TOC), the NOP will remain unchanged.
4407
4408   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4409       !IsPatchPoint) {
4410     if (CallOpc == PPCISD::BCTRL) {
4411       // This is a call through a function pointer.
4412       // Restore the caller TOC from the save area into R2.
4413       // See PrepareCall() for more information about calls through function
4414       // pointers in the 64-bit SVR4 ABI.
4415       // We are using a target-specific load with r2 hard coded, because the
4416       // result of a target-independent load would never go directly into r2,
4417       // since r2 is a reserved register (which prevents the register allocator
4418       // from allocating it), resulting in an additional register being
4419       // allocated and an unnecessary move instruction being generated.
4420       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4421
4422       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4423       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4424       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4425       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4426       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4427
4428       // The address needs to go after the chain input but before the flag (or
4429       // any other variadic arguments).
4430       Ops.insert(std::next(Ops.begin()), AddTOC);
4431     } else if ((CallOpc == PPCISD::CALL) &&
4432                (!isLocalCall(Callee) ||
4433                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4434       // Otherwise insert NOP for non-local calls.
4435       CallOpc = PPCISD::CALL_NOP;
4436   }
4437
4438   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4439   InFlag = Chain.getValue(1);
4440
4441   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4442                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4443                              InFlag, dl);
4444   if (!Ins.empty())
4445     InFlag = Chain.getValue(1);
4446
4447   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4448                          Ins, dl, DAG, InVals);
4449 }
4450
4451 SDValue
4452 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4453                              SmallVectorImpl<SDValue> &InVals) const {
4454   SelectionDAG &DAG                     = CLI.DAG;
4455   SDLoc &dl                             = CLI.DL;
4456   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4457   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4458   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4459   SDValue Chain                         = CLI.Chain;
4460   SDValue Callee                        = CLI.Callee;
4461   bool &isTailCall                      = CLI.IsTailCall;
4462   CallingConv::ID CallConv              = CLI.CallConv;
4463   bool isVarArg                         = CLI.IsVarArg;
4464   bool IsPatchPoint                     = CLI.IsPatchPoint;
4465   ImmutableCallSite *CS                 = CLI.CS;
4466
4467   if (isTailCall)
4468     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4469                                                    Ins, DAG);
4470
4471   if (!isTailCall && CS && CS->isMustTailCall())
4472     report_fatal_error("failed to perform tail call elimination on a call "
4473                        "site marked musttail");
4474
4475   if (Subtarget.isSVR4ABI()) {
4476     if (Subtarget.isPPC64())
4477       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4478                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4479                               dl, DAG, InVals, CS);
4480     else
4481       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4482                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4483                               dl, DAG, InVals, CS);
4484   }
4485
4486   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4487                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4488                           dl, DAG, InVals, CS);
4489 }
4490
4491 SDValue
4492 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4493                                     CallingConv::ID CallConv, bool isVarArg,
4494                                     bool isTailCall, bool IsPatchPoint,
4495                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4496                                     const SmallVectorImpl<SDValue> &OutVals,
4497                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4498                                     SDLoc dl, SelectionDAG &DAG,
4499                                     SmallVectorImpl<SDValue> &InVals,
4500                                     ImmutableCallSite *CS) const {
4501   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4502   // of the 32-bit SVR4 ABI stack frame layout.
4503
4504   assert((CallConv == CallingConv::C ||
4505           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4506
4507   unsigned PtrByteSize = 4;
4508
4509   MachineFunction &MF = DAG.getMachineFunction();
4510
4511   // Mark this function as potentially containing a function that contains a
4512   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4513   // and restoring the callers stack pointer in this functions epilog. This is
4514   // done because by tail calling the called function might overwrite the value
4515   // in this function's (MF) stack pointer stack slot 0(SP).
4516   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4517       CallConv == CallingConv::Fast)
4518     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4519
4520   // Count how many bytes are to be pushed on the stack, including the linkage
4521   // area, parameter list area and the part of the local variable space which
4522   // contains copies of aggregates which are passed by value.
4523
4524   // Assign locations to all of the outgoing arguments.
4525   SmallVector<CCValAssign, 16> ArgLocs;
4526   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4527                  *DAG.getContext());
4528
4529   // Reserve space for the linkage area on the stack.
4530   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4531                        PtrByteSize);
4532
4533   if (isVarArg) {
4534     // Handle fixed and variable vector arguments differently.
4535     // Fixed vector arguments go into registers as long as registers are
4536     // available. Variable vector arguments always go into memory.
4537     unsigned NumArgs = Outs.size();
4538
4539     for (unsigned i = 0; i != NumArgs; ++i) {
4540       MVT ArgVT = Outs[i].VT;
4541       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4542       bool Result;
4543
4544       if (Outs[i].IsFixed) {
4545         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4546                                CCInfo);
4547       } else {
4548         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4549                                       ArgFlags, CCInfo);
4550       }
4551
4552       if (Result) {
4553 #ifndef NDEBUG
4554         errs() << "Call operand #" << i << " has unhandled type "
4555              << EVT(ArgVT).getEVTString() << "\n";
4556 #endif
4557         llvm_unreachable(nullptr);
4558       }
4559     }
4560   } else {
4561     // All arguments are treated the same.
4562     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4563   }
4564
4565   // Assign locations to all of the outgoing aggregate by value arguments.
4566   SmallVector<CCValAssign, 16> ByValArgLocs;
4567   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4568                       ByValArgLocs, *DAG.getContext());
4569
4570   // Reserve stack space for the allocations in CCInfo.
4571   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4572
4573   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4574
4575   // Size of the linkage area, parameter list area and the part of the local
4576   // space variable where copies of aggregates which are passed by value are
4577   // stored.
4578   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4579
4580   // Calculate by how many bytes the stack has to be adjusted in case of tail
4581   // call optimization.
4582   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4583
4584   // Adjust the stack pointer for the new arguments...
4585   // These operations are automatically eliminated by the prolog/epilog pass
4586   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4587                                dl);
4588   SDValue CallSeqStart = Chain;
4589
4590   // Load the return address and frame pointer so it can be moved somewhere else
4591   // later.
4592   SDValue LROp, FPOp;
4593   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4594                                        dl);
4595
4596   // Set up a copy of the stack pointer for use loading and storing any
4597   // arguments that may not fit in the registers available for argument
4598   // passing.
4599   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4600
4601   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4602   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4603   SmallVector<SDValue, 8> MemOpChains;
4604
4605   bool seenFloatArg = false;
4606   // Walk the register/memloc assignments, inserting copies/loads.
4607   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4608        i != e;
4609        ++i) {
4610     CCValAssign &VA = ArgLocs[i];
4611     SDValue Arg = OutVals[i];
4612     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4613
4614     if (Flags.isByVal()) {
4615       // Argument is an aggregate which is passed by value, thus we need to
4616       // create a copy of it in the local variable space of the current stack
4617       // frame (which is the stack frame of the caller) and pass the address of
4618       // this copy to the callee.
4619       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4620       CCValAssign &ByValVA = ByValArgLocs[j++];
4621       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4622
4623       // Memory reserved in the local variable space of the callers stack frame.
4624       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4625
4626       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4627       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4628                            StackPtr, PtrOff);
4629
4630       // Create a copy of the argument in the local area of the current
4631       // stack frame.
4632       SDValue MemcpyCall =
4633         CreateCopyOfByValArgument(Arg, PtrOff,
4634                                   CallSeqStart.getNode()->getOperand(0),
4635                                   Flags, DAG, dl);
4636
4637       // This must go outside the CALLSEQ_START..END.
4638       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4639                            CallSeqStart.getNode()->getOperand(1),
4640                            SDLoc(MemcpyCall));
4641       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4642                              NewCallSeqStart.getNode());
4643       Chain = CallSeqStart = NewCallSeqStart;
4644
4645       // Pass the address of the aggregate copy on the stack either in a
4646       // physical register or in the parameter list area of the current stack
4647       // frame to the callee.
4648       Arg = PtrOff;
4649     }
4650
4651     if (VA.isRegLoc()) {
4652       if (Arg.getValueType() == MVT::i1)
4653         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4654
4655       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4656       // Put argument in a physical register.
4657       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4658     } else {
4659       // Put argument in the parameter list area of the current stack frame.
4660       assert(VA.isMemLoc());
4661       unsigned LocMemOffset = VA.getLocMemOffset();
4662
4663       if (!isTailCall) {
4664         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4665         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4666                              StackPtr, PtrOff);
4667
4668         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4669                                            MachinePointerInfo(),
4670                                            false, false, 0));
4671       } else {
4672         // Calculate and remember argument location.
4673         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4674                                  TailCallArguments);
4675       }
4676     }
4677   }
4678
4679   if (!MemOpChains.empty())
4680     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4681
4682   // Build a sequence of copy-to-reg nodes chained together with token chain
4683   // and flag operands which copy the outgoing args into the appropriate regs.
4684   SDValue InFlag;
4685   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4686     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4687                              RegsToPass[i].second, InFlag);
4688     InFlag = Chain.getValue(1);
4689   }
4690
4691   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4692   // registers.
4693   if (isVarArg) {
4694     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4695     SDValue Ops[] = { Chain, InFlag };
4696
4697     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4698                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4699
4700     InFlag = Chain.getValue(1);
4701   }
4702
4703   if (isTailCall)
4704     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4705                     false, TailCallArguments);
4706
4707   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
4708                     /* unused except on PPC64 ELFv1 */ false, DAG,
4709                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4710                     NumBytes, Ins, InVals, CS);
4711 }
4712
4713 // Copy an argument into memory, being careful to do this outside the
4714 // call sequence for the call to which the argument belongs.
4715 SDValue
4716 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4717                                               SDValue CallSeqStart,
4718                                               ISD::ArgFlagsTy Flags,
4719                                               SelectionDAG &DAG,
4720                                               SDLoc dl) const {
4721   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4722                         CallSeqStart.getNode()->getOperand(0),
4723                         Flags, DAG, dl);
4724   // The MEMCPY must go outside the CALLSEQ_START..END.
4725   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4726                              CallSeqStart.getNode()->getOperand(1),
4727                              SDLoc(MemcpyCall));
4728   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4729                          NewCallSeqStart.getNode());
4730   return NewCallSeqStart;
4731 }
4732
4733 SDValue
4734 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4735                                     CallingConv::ID CallConv, bool isVarArg,
4736                                     bool isTailCall, bool IsPatchPoint,
4737                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4738                                     const SmallVectorImpl<SDValue> &OutVals,
4739                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4740                                     SDLoc dl, SelectionDAG &DAG,
4741                                     SmallVectorImpl<SDValue> &InVals,
4742                                     ImmutableCallSite *CS) const {
4743
4744   bool isELFv2ABI = Subtarget.isELFv2ABI();
4745   bool isLittleEndian = Subtarget.isLittleEndian();
4746   unsigned NumOps = Outs.size();
4747   bool hasNest = false;
4748
4749   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4750   unsigned PtrByteSize = 8;
4751
4752   MachineFunction &MF = DAG.getMachineFunction();
4753
4754   // Mark this function as potentially containing a function that contains a
4755   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4756   // and restoring the callers stack pointer in this functions epilog. This is
4757   // done because by tail calling the called function might overwrite the value
4758   // in this function's (MF) stack pointer stack slot 0(SP).
4759   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4760       CallConv == CallingConv::Fast)
4761     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4762
4763   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4764          "fastcc not supported on varargs functions");
4765
4766   // Count how many bytes are to be pushed on the stack, including the linkage
4767   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4768   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4769   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4770   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4771   unsigned NumBytes = LinkageSize;
4772   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4773   unsigned &QFPR_idx = FPR_idx;
4774
4775   static const MCPhysReg GPR[] = {
4776     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4777     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4778   };
4779   static const MCPhysReg VR[] = {
4780     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4781     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4782   };
4783   static const MCPhysReg VSRH[] = {
4784     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4785     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4786   };
4787
4788   const unsigned NumGPRs = array_lengthof(GPR);
4789   const unsigned NumFPRs = 13;
4790   const unsigned NumVRs  = array_lengthof(VR);
4791   const unsigned NumQFPRs = NumFPRs;
4792
4793   // When using the fast calling convention, we don't provide backing for
4794   // arguments that will be in registers.
4795   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4796
4797   // Add up all the space actually used.
4798   for (unsigned i = 0; i != NumOps; ++i) {
4799     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4800     EVT ArgVT = Outs[i].VT;
4801     EVT OrigVT = Outs[i].ArgVT;
4802
4803     if (Flags.isNest())
4804       continue;
4805
4806     if (CallConv == CallingConv::Fast) {
4807       if (Flags.isByVal())
4808         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4809       else
4810         switch (ArgVT.getSimpleVT().SimpleTy) {
4811         default: llvm_unreachable("Unexpected ValueType for argument!");
4812         case MVT::i1:
4813         case MVT::i32:
4814         case MVT::i64:
4815           if (++NumGPRsUsed <= NumGPRs)
4816             continue;
4817           break;
4818         case MVT::v4i32:
4819         case MVT::v8i16:
4820         case MVT::v16i8:
4821         case MVT::v2f64:
4822         case MVT::v2i64:
4823         case MVT::v1i128:
4824           if (++NumVRsUsed <= NumVRs)
4825             continue;
4826           break;
4827         case MVT::v4f32:
4828           // When using QPX, this is handled like a FP register, otherwise, it
4829           // is an Altivec register.
4830           if (Subtarget.hasQPX()) {
4831             if (++NumFPRsUsed <= NumFPRs)
4832               continue;
4833           } else {
4834             if (++NumVRsUsed <= NumVRs)
4835               continue;
4836           }
4837           break;
4838         case MVT::f32:
4839         case MVT::f64:
4840         case MVT::v4f64: // QPX
4841         case MVT::v4i1:  // QPX
4842           if (++NumFPRsUsed <= NumFPRs)
4843             continue;
4844           break;
4845         }
4846     }
4847
4848     /* Respect alignment of argument on the stack.  */
4849     unsigned Align =
4850       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4851     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4852
4853     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4854     if (Flags.isInConsecutiveRegsLast())
4855       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4856   }
4857
4858   unsigned NumBytesActuallyUsed = NumBytes;
4859
4860   // The prolog code of the callee may store up to 8 GPR argument registers to
4861   // the stack, allowing va_start to index over them in memory if its varargs.
4862   // Because we cannot tell if this is needed on the caller side, we have to
4863   // conservatively assume that it is needed.  As such, make sure we have at
4864   // least enough stack space for the caller to store the 8 GPRs.
4865   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4866   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4867
4868   // Tail call needs the stack to be aligned.
4869   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4870       CallConv == CallingConv::Fast)
4871     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4872
4873   // Calculate by how many bytes the stack has to be adjusted in case of tail
4874   // call optimization.
4875   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4876
4877   // To protect arguments on the stack from being clobbered in a tail call,
4878   // force all the loads to happen before doing any other lowering.
4879   if (isTailCall)
4880     Chain = DAG.getStackArgumentTokenFactor(Chain);
4881
4882   // Adjust the stack pointer for the new arguments...
4883   // These operations are automatically eliminated by the prolog/epilog pass
4884   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4885                                dl);
4886   SDValue CallSeqStart = Chain;
4887
4888   // Load the return address and frame pointer so it can be move somewhere else
4889   // later.
4890   SDValue LROp, FPOp;
4891   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4892                                        dl);
4893
4894   // Set up a copy of the stack pointer for use loading and storing any
4895   // arguments that may not fit in the registers available for argument
4896   // passing.
4897   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4898
4899   // Figure out which arguments are going to go in registers, and which in
4900   // memory.  Also, if this is a vararg function, floating point operations
4901   // must be stored to our stack, and loaded into integer regs as well, if
4902   // any integer regs are available for argument passing.
4903   unsigned ArgOffset = LinkageSize;
4904
4905   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4906   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4907
4908   SmallVector<SDValue, 8> MemOpChains;
4909   for (unsigned i = 0; i != NumOps; ++i) {
4910     SDValue Arg = OutVals[i];
4911     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4912     EVT ArgVT = Outs[i].VT;
4913     EVT OrigVT = Outs[i].ArgVT;
4914
4915     // PtrOff will be used to store the current argument to the stack if a
4916     // register cannot be found for it.
4917     SDValue PtrOff;
4918
4919     // We re-align the argument offset for each argument, except when using the
4920     // fast calling convention, when we need to make sure we do that only when
4921     // we'll actually use a stack slot.
4922     auto ComputePtrOff = [&]() {
4923       /* Respect alignment of argument on the stack.  */
4924       unsigned Align =
4925         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4926       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4927
4928       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4929
4930       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4931     };
4932
4933     if (CallConv != CallingConv::Fast) {
4934       ComputePtrOff();
4935
4936       /* Compute GPR index associated with argument offset.  */
4937       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4938       GPR_idx = std::min(GPR_idx, NumGPRs);
4939     }
4940
4941     // Promote integers to 64-bit values.
4942     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4943       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4944       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4945       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4946     }
4947
4948     // FIXME memcpy is used way more than necessary.  Correctness first.
4949     // Note: "by value" is code for passing a structure by value, not
4950     // basic types.
4951     if (Flags.isByVal()) {
4952       // Note: Size includes alignment padding, so
4953       //   struct x { short a; char b; }
4954       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4955       // These are the proper values we need for right-justifying the
4956       // aggregate in a parameter register.
4957       unsigned Size = Flags.getByValSize();
4958
4959       // An empty aggregate parameter takes up no storage and no
4960       // registers.
4961       if (Size == 0)
4962         continue;
4963
4964       if (CallConv == CallingConv::Fast)
4965         ComputePtrOff();
4966
4967       // All aggregates smaller than 8 bytes must be passed right-justified.
4968       if (Size==1 || Size==2 || Size==4) {
4969         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4970         if (GPR_idx != NumGPRs) {
4971           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4972                                         MachinePointerInfo(), VT,
4973                                         false, false, false, 0);
4974           MemOpChains.push_back(Load.getValue(1));
4975           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4976
4977           ArgOffset += PtrByteSize;
4978           continue;
4979         }
4980       }
4981
4982       if (GPR_idx == NumGPRs && Size < 8) {
4983         SDValue AddPtr = PtrOff;
4984         if (!isLittleEndian) {
4985           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4986                                           PtrOff.getValueType());
4987           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4988         }
4989         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4990                                                           CallSeqStart,
4991                                                           Flags, DAG, dl);
4992         ArgOffset += PtrByteSize;
4993         continue;
4994       }
4995       // Copy entire object into memory.  There are cases where gcc-generated
4996       // code assumes it is there, even if it could be put entirely into
4997       // registers.  (This is not what the doc says.)
4998
4999       // FIXME: The above statement is likely due to a misunderstanding of the
5000       // documents.  All arguments must be copied into the parameter area BY
5001       // THE CALLEE in the event that the callee takes the address of any
5002       // formal argument.  That has not yet been implemented.  However, it is
5003       // reasonable to use the stack area as a staging area for the register
5004       // load.
5005
5006       // Skip this for small aggregates, as we will use the same slot for a
5007       // right-justified copy, below.
5008       if (Size >= 8)
5009         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5010                                                           CallSeqStart,
5011                                                           Flags, DAG, dl);
5012
5013       // When a register is available, pass a small aggregate right-justified.
5014       if (Size < 8 && GPR_idx != NumGPRs) {
5015         // The easiest way to get this right-justified in a register
5016         // is to copy the structure into the rightmost portion of a
5017         // local variable slot, then load the whole slot into the
5018         // register.
5019         // FIXME: The memcpy seems to produce pretty awful code for
5020         // small aggregates, particularly for packed ones.
5021         // FIXME: It would be preferable to use the slot in the
5022         // parameter save area instead of a new local variable.
5023         SDValue AddPtr = PtrOff;
5024         if (!isLittleEndian) {
5025           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5026           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5027         }
5028         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5029                                                           CallSeqStart,
5030                                                           Flags, DAG, dl);
5031
5032         // Load the slot into the register.
5033         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5034                                    MachinePointerInfo(),
5035                                    false, false, false, 0);
5036         MemOpChains.push_back(Load.getValue(1));
5037         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5038
5039         // Done with this argument.
5040         ArgOffset += PtrByteSize;
5041         continue;
5042       }
5043
5044       // For aggregates larger than PtrByteSize, copy the pieces of the
5045       // object that fit into registers from the parameter save area.
5046       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5047         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5048         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5049         if (GPR_idx != NumGPRs) {
5050           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5051                                      MachinePointerInfo(),
5052                                      false, false, false, 0);
5053           MemOpChains.push_back(Load.getValue(1));
5054           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5055           ArgOffset += PtrByteSize;
5056         } else {
5057           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5058           break;
5059         }
5060       }
5061       continue;
5062     }
5063
5064     switch (Arg.getSimpleValueType().SimpleTy) {
5065     default: llvm_unreachable("Unexpected ValueType for argument!");
5066     case MVT::i1:
5067     case MVT::i32:
5068     case MVT::i64:
5069       if (Flags.isNest()) {
5070         // The 'nest' parameter, if any, is passed in R11.
5071         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5072         hasNest = true;
5073         break;
5074       }
5075
5076       // These can be scalar arguments or elements of an integer array type
5077       // passed directly.  Clang may use those instead of "byval" aggregate
5078       // types to avoid forcing arguments to memory unnecessarily.
5079       if (GPR_idx != NumGPRs) {
5080         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5081       } else {
5082         if (CallConv == CallingConv::Fast)
5083           ComputePtrOff();
5084
5085         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5086                          true, isTailCall, false, MemOpChains,
5087                          TailCallArguments, dl);
5088         if (CallConv == CallingConv::Fast)
5089           ArgOffset += PtrByteSize;
5090       }
5091       if (CallConv != CallingConv::Fast)
5092         ArgOffset += PtrByteSize;
5093       break;
5094     case MVT::f32:
5095     case MVT::f64: {
5096       // These can be scalar arguments or elements of a float array type
5097       // passed directly.  The latter are used to implement ELFv2 homogenous
5098       // float aggregates.
5099
5100       // Named arguments go into FPRs first, and once they overflow, the
5101       // remaining arguments go into GPRs and then the parameter save area.
5102       // Unnamed arguments for vararg functions always go to GPRs and
5103       // then the parameter save area.  For now, put all arguments to vararg
5104       // routines always in both locations (FPR *and* GPR or stack slot).
5105       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5106       bool NeededLoad = false;
5107
5108       // First load the argument into the next available FPR.
5109       if (FPR_idx != NumFPRs)
5110         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5111
5112       // Next, load the argument into GPR or stack slot if needed.
5113       if (!NeedGPROrStack)
5114         ;
5115       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5116         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5117         // once we support fp <-> gpr moves.
5118
5119         // In the non-vararg case, this can only ever happen in the
5120         // presence of f32 array types, since otherwise we never run
5121         // out of FPRs before running out of GPRs.
5122         SDValue ArgVal;
5123
5124         // Double values are always passed in a single GPR.
5125         if (Arg.getValueType() != MVT::f32) {
5126           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5127
5128         // Non-array float values are extended and passed in a GPR.
5129         } else if (!Flags.isInConsecutiveRegs()) {
5130           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5131           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5132
5133         // If we have an array of floats, we collect every odd element
5134         // together with its predecessor into one GPR.
5135         } else if (ArgOffset % PtrByteSize != 0) {
5136           SDValue Lo, Hi;
5137           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5138           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5139           if (!isLittleEndian)
5140             std::swap(Lo, Hi);
5141           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5142
5143         // The final element, if even, goes into the first half of a GPR.
5144         } else if (Flags.isInConsecutiveRegsLast()) {
5145           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5146           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5147           if (!isLittleEndian)
5148             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5149                                  DAG.getConstant(32, dl, MVT::i32));
5150
5151         // Non-final even elements are skipped; they will be handled
5152         // together the with subsequent argument on the next go-around.
5153         } else
5154           ArgVal = SDValue();
5155
5156         if (ArgVal.getNode())
5157           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5158       } else {
5159         if (CallConv == CallingConv::Fast)
5160           ComputePtrOff();
5161
5162         // Single-precision floating-point values are mapped to the
5163         // second (rightmost) word of the stack doubleword.
5164         if (Arg.getValueType() == MVT::f32 &&
5165             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5166           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5167           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5168         }
5169
5170         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5171                          true, isTailCall, false, MemOpChains,
5172                          TailCallArguments, dl);
5173
5174         NeededLoad = true;
5175       }
5176       // When passing an array of floats, the array occupies consecutive
5177       // space in the argument area; only round up to the next doubleword
5178       // at the end of the array.  Otherwise, each float takes 8 bytes.
5179       if (CallConv != CallingConv::Fast || NeededLoad) {
5180         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5181                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5182         if (Flags.isInConsecutiveRegsLast())
5183           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5184       }
5185       break;
5186     }
5187     case MVT::v4f32:
5188     case MVT::v4i32:
5189     case MVT::v8i16:
5190     case MVT::v16i8:
5191     case MVT::v2f64:
5192     case MVT::v2i64:
5193     case MVT::v1i128:
5194       if (!Subtarget.hasQPX()) {
5195       // These can be scalar arguments or elements of a vector array type
5196       // passed directly.  The latter are used to implement ELFv2 homogenous
5197       // vector aggregates.
5198
5199       // For a varargs call, named arguments go into VRs or on the stack as
5200       // usual; unnamed arguments always go to the stack or the corresponding
5201       // GPRs when within range.  For now, we always put the value in both
5202       // locations (or even all three).
5203       if (isVarArg) {
5204         // We could elide this store in the case where the object fits
5205         // entirely in R registers.  Maybe later.
5206         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5207                                      MachinePointerInfo(), false, false, 0);
5208         MemOpChains.push_back(Store);
5209         if (VR_idx != NumVRs) {
5210           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5211                                      MachinePointerInfo(),
5212                                      false, false, false, 0);
5213           MemOpChains.push_back(Load.getValue(1));
5214
5215           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5216                            Arg.getSimpleValueType() == MVT::v2i64) ?
5217                           VSRH[VR_idx] : VR[VR_idx];
5218           ++VR_idx;
5219
5220           RegsToPass.push_back(std::make_pair(VReg, Load));
5221         }
5222         ArgOffset += 16;
5223         for (unsigned i=0; i<16; i+=PtrByteSize) {
5224           if (GPR_idx == NumGPRs)
5225             break;
5226           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5227                                    DAG.getConstant(i, dl, PtrVT));
5228           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5229                                      false, false, false, 0);
5230           MemOpChains.push_back(Load.getValue(1));
5231           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5232         }
5233         break;
5234       }
5235
5236       // Non-varargs Altivec params go into VRs or on the stack.
5237       if (VR_idx != NumVRs) {
5238         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5239                          Arg.getSimpleValueType() == MVT::v2i64) ?
5240                         VSRH[VR_idx] : VR[VR_idx];
5241         ++VR_idx;
5242
5243         RegsToPass.push_back(std::make_pair(VReg, Arg));
5244       } else {
5245         if (CallConv == CallingConv::Fast)
5246           ComputePtrOff();
5247
5248         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5249                          true, isTailCall, true, MemOpChains,
5250                          TailCallArguments, dl);
5251         if (CallConv == CallingConv::Fast)
5252           ArgOffset += 16;
5253       }
5254
5255       if (CallConv != CallingConv::Fast)
5256         ArgOffset += 16;
5257       break;
5258       } // not QPX
5259
5260       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5261              "Invalid QPX parameter type");
5262
5263       /* fall through */
5264     case MVT::v4f64:
5265     case MVT::v4i1: {
5266       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5267       if (isVarArg) {
5268         // We could elide this store in the case where the object fits
5269         // entirely in R registers.  Maybe later.
5270         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5271                                      MachinePointerInfo(), false, false, 0);
5272         MemOpChains.push_back(Store);
5273         if (QFPR_idx != NumQFPRs) {
5274           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5275                                      Store, PtrOff, MachinePointerInfo(),
5276                                      false, false, false, 0);
5277           MemOpChains.push_back(Load.getValue(1));
5278           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5279         }
5280         ArgOffset += (IsF32 ? 16 : 32);
5281         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5282           if (GPR_idx == NumGPRs)
5283             break;
5284           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5285                                    DAG.getConstant(i, dl, PtrVT));
5286           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5287                                      false, false, false, 0);
5288           MemOpChains.push_back(Load.getValue(1));
5289           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5290         }
5291         break;
5292       }
5293
5294       // Non-varargs QPX params go into registers or on the stack.
5295       if (QFPR_idx != NumQFPRs) {
5296         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5297       } else {
5298         if (CallConv == CallingConv::Fast)
5299           ComputePtrOff();
5300
5301         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5302                          true, isTailCall, true, MemOpChains,
5303                          TailCallArguments, dl);
5304         if (CallConv == CallingConv::Fast)
5305           ArgOffset += (IsF32 ? 16 : 32);
5306       }
5307
5308       if (CallConv != CallingConv::Fast)
5309         ArgOffset += (IsF32 ? 16 : 32);
5310       break;
5311       }
5312     }
5313   }
5314
5315   assert(NumBytesActuallyUsed == ArgOffset);
5316   (void)NumBytesActuallyUsed;
5317
5318   if (!MemOpChains.empty())
5319     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5320
5321   // Check if this is an indirect call (MTCTR/BCTRL).
5322   // See PrepareCall() for more information about calls through function
5323   // pointers in the 64-bit SVR4 ABI.
5324   if (!isTailCall && !IsPatchPoint &&
5325       !isFunctionGlobalAddress(Callee) &&
5326       !isa<ExternalSymbolSDNode>(Callee)) {
5327     // Load r2 into a virtual register and store it to the TOC save area.
5328     setUsesTOCBasePtr(DAG);
5329     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5330     // TOC save area offset.
5331     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5332     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5333     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5334     Chain = DAG.getStore(
5335         Val.getValue(1), dl, Val, AddPtr,
5336         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset),
5337         false, false, 0);
5338     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5339     // This does not mean the MTCTR instruction must use R12; it's easier
5340     // to model this as an extra parameter, so do that.
5341     if (isELFv2ABI && !IsPatchPoint)
5342       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5343   }
5344
5345   // Build a sequence of copy-to-reg nodes chained together with token chain
5346   // and flag operands which copy the outgoing args into the appropriate regs.
5347   SDValue InFlag;
5348   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5349     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5350                              RegsToPass[i].second, InFlag);
5351     InFlag = Chain.getValue(1);
5352   }
5353
5354   if (isTailCall)
5355     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5356                     FPOp, true, TailCallArguments);
5357
5358   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5359                     hasNest, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5360                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
5361 }
5362
5363 SDValue
5364 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5365                                     CallingConv::ID CallConv, bool isVarArg,
5366                                     bool isTailCall, bool IsPatchPoint,
5367                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5368                                     const SmallVectorImpl<SDValue> &OutVals,
5369                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5370                                     SDLoc dl, SelectionDAG &DAG,
5371                                     SmallVectorImpl<SDValue> &InVals,
5372                                     ImmutableCallSite *CS) const {
5373
5374   unsigned NumOps = Outs.size();
5375
5376   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5377   bool isPPC64 = PtrVT == MVT::i64;
5378   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5379
5380   MachineFunction &MF = DAG.getMachineFunction();
5381
5382   // Mark this function as potentially containing a function that contains a
5383   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5384   // and restoring the callers stack pointer in this functions epilog. This is
5385   // done because by tail calling the called function might overwrite the value
5386   // in this function's (MF) stack pointer stack slot 0(SP).
5387   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5388       CallConv == CallingConv::Fast)
5389     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5390
5391   // Count how many bytes are to be pushed on the stack, including the linkage
5392   // area, and parameter passing area.  We start with 24/48 bytes, which is
5393   // prereserved space for [SP][CR][LR][3 x unused].
5394   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5395   unsigned NumBytes = LinkageSize;
5396
5397   // Add up all the space actually used.
5398   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5399   // they all go in registers, but we must reserve stack space for them for
5400   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5401   // assigned stack space in order, with padding so Altivec parameters are
5402   // 16-byte aligned.
5403   unsigned nAltivecParamsAtEnd = 0;
5404   for (unsigned i = 0; i != NumOps; ++i) {
5405     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5406     EVT ArgVT = Outs[i].VT;
5407     // Varargs Altivec parameters are padded to a 16 byte boundary.
5408     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5409         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5410         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5411       if (!isVarArg && !isPPC64) {
5412         // Non-varargs Altivec parameters go after all the non-Altivec
5413         // parameters; handle those later so we know how much padding we need.
5414         nAltivecParamsAtEnd++;
5415         continue;
5416       }
5417       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5418       NumBytes = ((NumBytes+15)/16)*16;
5419     }
5420     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5421   }
5422
5423   // Allow for Altivec parameters at the end, if needed.
5424   if (nAltivecParamsAtEnd) {
5425     NumBytes = ((NumBytes+15)/16)*16;
5426     NumBytes += 16*nAltivecParamsAtEnd;
5427   }
5428
5429   // The prolog code of the callee may store up to 8 GPR argument registers to
5430   // the stack, allowing va_start to index over them in memory if its varargs.
5431   // Because we cannot tell if this is needed on the caller side, we have to
5432   // conservatively assume that it is needed.  As such, make sure we have at
5433   // least enough stack space for the caller to store the 8 GPRs.
5434   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5435
5436   // Tail call needs the stack to be aligned.
5437   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5438       CallConv == CallingConv::Fast)
5439     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5440
5441   // Calculate by how many bytes the stack has to be adjusted in case of tail
5442   // call optimization.
5443   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5444
5445   // To protect arguments on the stack from being clobbered in a tail call,
5446   // force all the loads to happen before doing any other lowering.
5447   if (isTailCall)
5448     Chain = DAG.getStackArgumentTokenFactor(Chain);
5449
5450   // Adjust the stack pointer for the new arguments...
5451   // These operations are automatically eliminated by the prolog/epilog pass
5452   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5453                                dl);
5454   SDValue CallSeqStart = Chain;
5455
5456   // Load the return address and frame pointer so it can be move somewhere else
5457   // later.
5458   SDValue LROp, FPOp;
5459   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5460                                        dl);
5461
5462   // Set up a copy of the stack pointer for use loading and storing any
5463   // arguments that may not fit in the registers available for argument
5464   // passing.
5465   SDValue StackPtr;
5466   if (isPPC64)
5467     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5468   else
5469     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5470
5471   // Figure out which arguments are going to go in registers, and which in
5472   // memory.  Also, if this is a vararg function, floating point operations
5473   // must be stored to our stack, and loaded into integer regs as well, if
5474   // any integer regs are available for argument passing.
5475   unsigned ArgOffset = LinkageSize;
5476   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5477
5478   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5479     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5480     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5481   };
5482   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5483     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5484     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5485   };
5486   static const MCPhysReg VR[] = {
5487     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5488     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5489   };
5490   const unsigned NumGPRs = array_lengthof(GPR_32);
5491   const unsigned NumFPRs = 13;
5492   const unsigned NumVRs  = array_lengthof(VR);
5493
5494   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5495
5496   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5497   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5498
5499   SmallVector<SDValue, 8> MemOpChains;
5500   for (unsigned i = 0; i != NumOps; ++i) {
5501     SDValue Arg = OutVals[i];
5502     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5503
5504     // PtrOff will be used to store the current argument to the stack if a
5505     // register cannot be found for it.
5506     SDValue PtrOff;
5507
5508     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5509
5510     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5511
5512     // On PPC64, promote integers to 64-bit values.
5513     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5514       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5515       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5516       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5517     }
5518
5519     // FIXME memcpy is used way more than necessary.  Correctness first.
5520     // Note: "by value" is code for passing a structure by value, not
5521     // basic types.
5522     if (Flags.isByVal()) {
5523       unsigned Size = Flags.getByValSize();
5524       // Very small objects are passed right-justified.  Everything else is
5525       // passed left-justified.
5526       if (Size==1 || Size==2) {
5527         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5528         if (GPR_idx != NumGPRs) {
5529           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5530                                         MachinePointerInfo(), VT,
5531                                         false, false, false, 0);
5532           MemOpChains.push_back(Load.getValue(1));
5533           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5534
5535           ArgOffset += PtrByteSize;
5536         } else {
5537           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5538                                           PtrOff.getValueType());
5539           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5540           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5541                                                             CallSeqStart,
5542                                                             Flags, DAG, dl);
5543           ArgOffset += PtrByteSize;
5544         }
5545         continue;
5546       }
5547       // Copy entire object into memory.  There are cases where gcc-generated
5548       // code assumes it is there, even if it could be put entirely into
5549       // registers.  (This is not what the doc says.)
5550       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5551                                                         CallSeqStart,
5552                                                         Flags, DAG, dl);
5553
5554       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5555       // copy the pieces of the object that fit into registers from the
5556       // parameter save area.
5557       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5558         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5559         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5560         if (GPR_idx != NumGPRs) {
5561           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5562                                      MachinePointerInfo(),
5563                                      false, false, false, 0);
5564           MemOpChains.push_back(Load.getValue(1));
5565           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5566           ArgOffset += PtrByteSize;
5567         } else {
5568           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5569           break;
5570         }
5571       }
5572       continue;
5573     }
5574
5575     switch (Arg.getSimpleValueType().SimpleTy) {
5576     default: llvm_unreachable("Unexpected ValueType for argument!");
5577     case MVT::i1:
5578     case MVT::i32:
5579     case MVT::i64:
5580       if (GPR_idx != NumGPRs) {
5581         if (Arg.getValueType() == MVT::i1)
5582           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5583
5584         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5585       } else {
5586         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5587                          isPPC64, isTailCall, false, MemOpChains,
5588                          TailCallArguments, dl);
5589       }
5590       ArgOffset += PtrByteSize;
5591       break;
5592     case MVT::f32:
5593     case MVT::f64:
5594       if (FPR_idx != NumFPRs) {
5595         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5596
5597         if (isVarArg) {
5598           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5599                                        MachinePointerInfo(), false, false, 0);
5600           MemOpChains.push_back(Store);
5601
5602           // Float varargs are always shadowed in available integer registers
5603           if (GPR_idx != NumGPRs) {
5604             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5605                                        MachinePointerInfo(), false, false,
5606                                        false, 0);
5607             MemOpChains.push_back(Load.getValue(1));
5608             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5609           }
5610           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5611             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5612             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5613             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5614                                        MachinePointerInfo(),
5615                                        false, false, false, 0);
5616             MemOpChains.push_back(Load.getValue(1));
5617             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5618           }
5619         } else {
5620           // If we have any FPRs remaining, we may also have GPRs remaining.
5621           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5622           // GPRs.
5623           if (GPR_idx != NumGPRs)
5624             ++GPR_idx;
5625           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5626               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5627             ++GPR_idx;
5628         }
5629       } else
5630         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5631                          isPPC64, isTailCall, false, MemOpChains,
5632                          TailCallArguments, dl);
5633       if (isPPC64)
5634         ArgOffset += 8;
5635       else
5636         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5637       break;
5638     case MVT::v4f32:
5639     case MVT::v4i32:
5640     case MVT::v8i16:
5641     case MVT::v16i8:
5642       if (isVarArg) {
5643         // These go aligned on the stack, or in the corresponding R registers
5644         // when within range.  The Darwin PPC ABI doc claims they also go in
5645         // V registers; in fact gcc does this only for arguments that are
5646         // prototyped, not for those that match the ...  We do it for all
5647         // arguments, seems to work.
5648         while (ArgOffset % 16 !=0) {
5649           ArgOffset += PtrByteSize;
5650           if (GPR_idx != NumGPRs)
5651             GPR_idx++;
5652         }
5653         // We could elide this store in the case where the object fits
5654         // entirely in R registers.  Maybe later.
5655         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5656                              DAG.getConstant(ArgOffset, dl, PtrVT));
5657         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5658                                      MachinePointerInfo(), false, false, 0);
5659         MemOpChains.push_back(Store);
5660         if (VR_idx != NumVRs) {
5661           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5662                                      MachinePointerInfo(),
5663                                      false, false, false, 0);
5664           MemOpChains.push_back(Load.getValue(1));
5665           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5666         }
5667         ArgOffset += 16;
5668         for (unsigned i=0; i<16; i+=PtrByteSize) {
5669           if (GPR_idx == NumGPRs)
5670             break;
5671           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5672                                    DAG.getConstant(i, dl, PtrVT));
5673           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5674                                      false, false, false, 0);
5675           MemOpChains.push_back(Load.getValue(1));
5676           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5677         }
5678         break;
5679       }
5680
5681       // Non-varargs Altivec params generally go in registers, but have
5682       // stack space allocated at the end.
5683       if (VR_idx != NumVRs) {
5684         // Doesn't have GPR space allocated.
5685         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5686       } else if (nAltivecParamsAtEnd==0) {
5687         // We are emitting Altivec params in order.
5688         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5689                          isPPC64, isTailCall, true, MemOpChains,
5690                          TailCallArguments, dl);
5691         ArgOffset += 16;
5692       }
5693       break;
5694     }
5695   }
5696   // If all Altivec parameters fit in registers, as they usually do,
5697   // they get stack space following the non-Altivec parameters.  We
5698   // don't track this here because nobody below needs it.
5699   // If there are more Altivec parameters than fit in registers emit
5700   // the stores here.
5701   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5702     unsigned j = 0;
5703     // Offset is aligned; skip 1st 12 params which go in V registers.
5704     ArgOffset = ((ArgOffset+15)/16)*16;
5705     ArgOffset += 12*16;
5706     for (unsigned i = 0; i != NumOps; ++i) {
5707       SDValue Arg = OutVals[i];
5708       EVT ArgType = Outs[i].VT;
5709       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5710           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5711         if (++j > NumVRs) {
5712           SDValue PtrOff;
5713           // We are emitting Altivec params in order.
5714           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5715                            isPPC64, isTailCall, true, MemOpChains,
5716                            TailCallArguments, dl);
5717           ArgOffset += 16;
5718         }
5719       }
5720     }
5721   }
5722
5723   if (!MemOpChains.empty())
5724     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5725
5726   // On Darwin, R12 must contain the address of an indirect callee.  This does
5727   // not mean the MTCTR instruction must use R12; it's easier to model this as
5728   // an extra parameter, so do that.
5729   if (!isTailCall &&
5730       !isFunctionGlobalAddress(Callee) &&
5731       !isa<ExternalSymbolSDNode>(Callee) &&
5732       !isBLACompatibleAddress(Callee, DAG))
5733     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5734                                                    PPC::R12), Callee));
5735
5736   // Build a sequence of copy-to-reg nodes chained together with token chain
5737   // and flag operands which copy the outgoing args into the appropriate regs.
5738   SDValue InFlag;
5739   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5740     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5741                              RegsToPass[i].second, InFlag);
5742     InFlag = Chain.getValue(1);
5743   }
5744
5745   if (isTailCall)
5746     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5747                     FPOp, true, TailCallArguments);
5748
5749   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5750                     /* unused except on PPC64 ELFv1 */ false, DAG,
5751                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5752                     NumBytes, Ins, InVals, CS);
5753 }
5754
5755 bool
5756 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5757                                   MachineFunction &MF, bool isVarArg,
5758                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5759                                   LLVMContext &Context) const {
5760   SmallVector<CCValAssign, 16> RVLocs;
5761   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5762   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5763 }
5764
5765 SDValue
5766 PPCTargetLowering::LowerReturn(SDValue Chain,
5767                                CallingConv::ID CallConv, bool isVarArg,
5768                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5769                                const SmallVectorImpl<SDValue> &OutVals,
5770                                SDLoc dl, SelectionDAG &DAG) const {
5771
5772   SmallVector<CCValAssign, 16> RVLocs;
5773   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5774                  *DAG.getContext());
5775   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5776
5777   SDValue Flag;
5778   SmallVector<SDValue, 4> RetOps(1, Chain);
5779
5780   // Copy the result values into the output registers.
5781   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5782     CCValAssign &VA = RVLocs[i];
5783     assert(VA.isRegLoc() && "Can only return in registers!");
5784
5785     SDValue Arg = OutVals[i];
5786
5787     switch (VA.getLocInfo()) {
5788     default: llvm_unreachable("Unknown loc info!");
5789     case CCValAssign::Full: break;
5790     case CCValAssign::AExt:
5791       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5792       break;
5793     case CCValAssign::ZExt:
5794       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5795       break;
5796     case CCValAssign::SExt:
5797       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5798       break;
5799     }
5800
5801     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5802     Flag = Chain.getValue(1);
5803     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5804   }
5805
5806   RetOps[0] = Chain;  // Update chain.
5807
5808   // Add the flag if we have it.
5809   if (Flag.getNode())
5810     RetOps.push_back(Flag);
5811
5812   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5813 }
5814
5815 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5816                                    const PPCSubtarget &Subtarget) const {
5817   // When we pop the dynamic allocation we need to restore the SP link.
5818   SDLoc dl(Op);
5819
5820   // Get the corect type for pointers.
5821   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5822
5823   // Construct the stack pointer operand.
5824   bool isPPC64 = Subtarget.isPPC64();
5825   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5826   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5827
5828   // Get the operands for the STACKRESTORE.
5829   SDValue Chain = Op.getOperand(0);
5830   SDValue SaveSP = Op.getOperand(1);
5831
5832   // Load the old link SP.
5833   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5834                                    MachinePointerInfo(),
5835                                    false, false, false, 0);
5836
5837   // Restore the stack pointer.
5838   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5839
5840   // Store the old link SP.
5841   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5842                       false, false, 0);
5843 }
5844
5845
5846
5847 SDValue
5848 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5849   MachineFunction &MF = DAG.getMachineFunction();
5850   bool isPPC64 = Subtarget.isPPC64();
5851   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5852
5853   // Get current frame pointer save index.  The users of this index will be
5854   // primarily DYNALLOC instructions.
5855   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5856   int RASI = FI->getReturnAddrSaveIndex();
5857
5858   // If the frame pointer save index hasn't been defined yet.
5859   if (!RASI) {
5860     // Find out what the fix offset of the frame pointer save area.
5861     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5862     // Allocate the frame index for frame pointer save area.
5863     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5864     // Save the result.
5865     FI->setReturnAddrSaveIndex(RASI);
5866   }
5867   return DAG.getFrameIndex(RASI, PtrVT);
5868 }
5869
5870 SDValue
5871 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5872   MachineFunction &MF = DAG.getMachineFunction();
5873   bool isPPC64 = Subtarget.isPPC64();
5874   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5875
5876   // Get current frame pointer save index.  The users of this index will be
5877   // primarily DYNALLOC instructions.
5878   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5879   int FPSI = FI->getFramePointerSaveIndex();
5880
5881   // If the frame pointer save index hasn't been defined yet.
5882   if (!FPSI) {
5883     // Find out what the fix offset of the frame pointer save area.
5884     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5885     // Allocate the frame index for frame pointer save area.
5886     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5887     // Save the result.
5888     FI->setFramePointerSaveIndex(FPSI);
5889   }
5890   return DAG.getFrameIndex(FPSI, PtrVT);
5891 }
5892
5893 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5894                                          SelectionDAG &DAG,
5895                                          const PPCSubtarget &Subtarget) const {
5896   // Get the inputs.
5897   SDValue Chain = Op.getOperand(0);
5898   SDValue Size  = Op.getOperand(1);
5899   SDLoc dl(Op);
5900
5901   // Get the corect type for pointers.
5902   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5903   // Negate the size.
5904   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5905                                 DAG.getConstant(0, dl, PtrVT), Size);
5906   // Construct a node for the frame pointer save index.
5907   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5908   // Build a DYNALLOC node.
5909   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5910   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5911   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5912 }
5913
5914 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5915                                                SelectionDAG &DAG) const {
5916   SDLoc DL(Op);
5917   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5918                      DAG.getVTList(MVT::i32, MVT::Other),
5919                      Op.getOperand(0), Op.getOperand(1));
5920 }
5921
5922 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5923                                                 SelectionDAG &DAG) const {
5924   SDLoc DL(Op);
5925   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5926                      Op.getOperand(0), Op.getOperand(1));
5927 }
5928
5929 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5930   if (Op.getValueType().isVector())
5931     return LowerVectorLoad(Op, DAG);
5932
5933   assert(Op.getValueType() == MVT::i1 &&
5934          "Custom lowering only for i1 loads");
5935
5936   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5937
5938   SDLoc dl(Op);
5939   LoadSDNode *LD = cast<LoadSDNode>(Op);
5940
5941   SDValue Chain = LD->getChain();
5942   SDValue BasePtr = LD->getBasePtr();
5943   MachineMemOperand *MMO = LD->getMemOperand();
5944
5945   SDValue NewLD =
5946       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
5947                      BasePtr, MVT::i8, MMO);
5948   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5949
5950   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5951   return DAG.getMergeValues(Ops, dl);
5952 }
5953
5954 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5955   if (Op.getOperand(1).getValueType().isVector())
5956     return LowerVectorStore(Op, DAG);
5957
5958   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5959          "Custom lowering only for i1 stores");
5960
5961   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5962
5963   SDLoc dl(Op);
5964   StoreSDNode *ST = cast<StoreSDNode>(Op);
5965
5966   SDValue Chain = ST->getChain();
5967   SDValue BasePtr = ST->getBasePtr();
5968   SDValue Value = ST->getValue();
5969   MachineMemOperand *MMO = ST->getMemOperand();
5970
5971   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
5972                       Value);
5973   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5974 }
5975
5976 // FIXME: Remove this once the ANDI glue bug is fixed:
5977 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5978   assert(Op.getValueType() == MVT::i1 &&
5979          "Custom lowering only for i1 results");
5980
5981   SDLoc DL(Op);
5982   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5983                      Op.getOperand(0));
5984 }
5985
5986 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5987 /// possible.
5988 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5989   // Not FP? Not a fsel.
5990   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5991       !Op.getOperand(2).getValueType().isFloatingPoint())
5992     return Op;
5993
5994   // We might be able to do better than this under some circumstances, but in
5995   // general, fsel-based lowering of select is a finite-math-only optimization.
5996   // For more information, see section F.3 of the 2.06 ISA specification.
5997   if (!DAG.getTarget().Options.NoInfsFPMath ||
5998       !DAG.getTarget().Options.NoNaNsFPMath)
5999     return Op;
6000
6001   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6002
6003   EVT ResVT = Op.getValueType();
6004   EVT CmpVT = Op.getOperand(0).getValueType();
6005   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6006   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6007   SDLoc dl(Op);
6008
6009   // If the RHS of the comparison is a 0.0, we don't need to do the
6010   // subtraction at all.
6011   SDValue Sel1;
6012   if (isFloatingPointZero(RHS))
6013     switch (CC) {
6014     default: break;       // SETUO etc aren't handled by fsel.
6015     case ISD::SETNE:
6016       std::swap(TV, FV);
6017     case ISD::SETEQ:
6018       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6019         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6020       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6021       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6022         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6023       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6024                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6025     case ISD::SETULT:
6026     case ISD::SETLT:
6027       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6028     case ISD::SETOGE:
6029     case ISD::SETGE:
6030       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6031         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6032       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6033     case ISD::SETUGT:
6034     case ISD::SETGT:
6035       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6036     case ISD::SETOLE:
6037     case ISD::SETLE:
6038       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6039         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6040       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6041                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6042     }
6043
6044   SDValue Cmp;
6045   switch (CC) {
6046   default: break;       // SETUO etc aren't handled by fsel.
6047   case ISD::SETNE:
6048     std::swap(TV, FV);
6049   case ISD::SETEQ:
6050     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
6051     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6052       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6053     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6054     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6055       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6056     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6057                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6058   case ISD::SETULT:
6059   case ISD::SETLT:
6060     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
6061     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6062       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6063     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6064   case ISD::SETOGE:
6065   case ISD::SETGE:
6066     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
6067     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6068       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6069     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6070   case ISD::SETUGT:
6071   case ISD::SETGT:
6072     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
6073     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6074       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6075     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6076   case ISD::SETOLE:
6077   case ISD::SETLE:
6078     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
6079     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6080       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6081     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6082   }
6083   return Op;
6084 }
6085
6086 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6087                                                SelectionDAG &DAG,
6088                                                SDLoc dl) const {
6089   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6090   SDValue Src = Op.getOperand(0);
6091   if (Src.getValueType() == MVT::f32)
6092     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6093
6094   SDValue Tmp;
6095   switch (Op.getSimpleValueType().SimpleTy) {
6096   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6097   case MVT::i32:
6098     Tmp = DAG.getNode(
6099         Op.getOpcode() == ISD::FP_TO_SINT
6100             ? PPCISD::FCTIWZ
6101             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6102         dl, MVT::f64, Src);
6103     break;
6104   case MVT::i64:
6105     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6106            "i64 FP_TO_UINT is supported only with FPCVT");
6107     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6108                                                         PPCISD::FCTIDUZ,
6109                       dl, MVT::f64, Src);
6110     break;
6111   }
6112
6113   // Convert the FP value to an int value through memory.
6114   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6115     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6116   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6117   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6118   MachinePointerInfo MPI =
6119       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6120
6121   // Emit a store to the stack slot.
6122   SDValue Chain;
6123   if (i32Stack) {
6124     MachineFunction &MF = DAG.getMachineFunction();
6125     MachineMemOperand *MMO =
6126       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6127     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6128     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6129               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6130   } else
6131     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6132                          MPI, false, false, 0);
6133
6134   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6135   // add in a bias.
6136   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6137     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6138                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6139     MPI = MPI.getWithOffset(4);
6140   }
6141
6142   RLI.Chain = Chain;
6143   RLI.Ptr = FIPtr;
6144   RLI.MPI = MPI;
6145 }
6146
6147 /// \brief Custom lowers floating point to integer conversions to use
6148 /// the direct move instructions available in ISA 2.07 to avoid the
6149 /// need for load/store combinations.
6150 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6151                                                     SelectionDAG &DAG,
6152                                                     SDLoc dl) const {
6153   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6154   SDValue Src = Op.getOperand(0);
6155
6156   if (Src.getValueType() == MVT::f32)
6157     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6158
6159   SDValue Tmp;
6160   switch (Op.getSimpleValueType().SimpleTy) {
6161   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6162   case MVT::i32:
6163     Tmp = DAG.getNode(
6164         Op.getOpcode() == ISD::FP_TO_SINT
6165             ? PPCISD::FCTIWZ
6166             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6167         dl, MVT::f64, Src);
6168     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6169     break;
6170   case MVT::i64:
6171     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6172            "i64 FP_TO_UINT is supported only with FPCVT");
6173     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6174                                                         PPCISD::FCTIDUZ,
6175                       dl, MVT::f64, Src);
6176     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6177     break;
6178   }
6179   return Tmp;
6180 }
6181
6182 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6183                                           SDLoc dl) const {
6184   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6185     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6186
6187   ReuseLoadInfo RLI;
6188   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6189
6190   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6191                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6192                      RLI.Ranges);
6193 }
6194
6195 // We're trying to insert a regular store, S, and then a load, L. If the
6196 // incoming value, O, is a load, we might just be able to have our load use the
6197 // address used by O. However, we don't know if anything else will store to
6198 // that address before we can load from it. To prevent this situation, we need
6199 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6200 // the same chain operand as O, we create a token factor from the chain results
6201 // of O and L, and we replace all uses of O's chain result with that token
6202 // factor (see spliceIntoChain below for this last part).
6203 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6204                                             ReuseLoadInfo &RLI,
6205                                             SelectionDAG &DAG,
6206                                             ISD::LoadExtType ET) const {
6207   SDLoc dl(Op);
6208   if (ET == ISD::NON_EXTLOAD &&
6209       (Op.getOpcode() == ISD::FP_TO_UINT ||
6210        Op.getOpcode() == ISD::FP_TO_SINT) &&
6211       isOperationLegalOrCustom(Op.getOpcode(),
6212                                Op.getOperand(0).getValueType())) {
6213
6214     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6215     return true;
6216   }
6217
6218   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6219   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6220       LD->isNonTemporal())
6221     return false;
6222   if (LD->getMemoryVT() != MemVT)
6223     return false;
6224
6225   RLI.Ptr = LD->getBasePtr();
6226   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6227     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6228            "Non-pre-inc AM on PPC?");
6229     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6230                           LD->getOffset());
6231   }
6232
6233   RLI.Chain = LD->getChain();
6234   RLI.MPI = LD->getPointerInfo();
6235   RLI.IsInvariant = LD->isInvariant();
6236   RLI.Alignment = LD->getAlignment();
6237   RLI.AAInfo = LD->getAAInfo();
6238   RLI.Ranges = LD->getRanges();
6239
6240   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6241   return true;
6242 }
6243
6244 // Given the head of the old chain, ResChain, insert a token factor containing
6245 // it and NewResChain, and make users of ResChain now be users of that token
6246 // factor.
6247 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6248                                         SDValue NewResChain,
6249                                         SelectionDAG &DAG) const {
6250   if (!ResChain)
6251     return;
6252
6253   SDLoc dl(NewResChain);
6254
6255   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6256                            NewResChain, DAG.getUNDEF(MVT::Other));
6257   assert(TF.getNode() != NewResChain.getNode() &&
6258          "A new TF really is required here");
6259
6260   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6261   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6262 }
6263
6264 /// \brief Custom lowers integer to floating point conversions to use
6265 /// the direct move instructions available in ISA 2.07 to avoid the
6266 /// need for load/store combinations.
6267 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6268                                                     SelectionDAG &DAG,
6269                                                     SDLoc dl) const {
6270   assert((Op.getValueType() == MVT::f32 ||
6271           Op.getValueType() == MVT::f64) &&
6272          "Invalid floating point type as target of conversion");
6273   assert(Subtarget.hasFPCVT() &&
6274          "Int to FP conversions with direct moves require FPCVT");
6275   SDValue FP;
6276   SDValue Src = Op.getOperand(0);
6277   bool SinglePrec = Op.getValueType() == MVT::f32;
6278   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6279   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6280   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6281                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6282
6283   if (WordInt) {
6284     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6285                      dl, MVT::f64, Src);
6286     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6287   }
6288   else {
6289     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6290     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6291   }
6292
6293   return FP;
6294 }
6295
6296 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6297                                           SelectionDAG &DAG) const {
6298   SDLoc dl(Op);
6299
6300   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6301     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6302       return SDValue();
6303
6304     SDValue Value = Op.getOperand(0);
6305     // The values are now known to be -1 (false) or 1 (true). To convert this
6306     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6307     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6308     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6309   
6310     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6311     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6312                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6313   
6314     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6315
6316     if (Op.getValueType() != MVT::v4f64)
6317       Value = DAG.getNode(ISD::FP_ROUND, dl,
6318                           Op.getValueType(), Value,
6319                           DAG.getIntPtrConstant(1, dl));
6320     return Value;
6321   }
6322
6323   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6324   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6325     return SDValue();
6326
6327   if (Op.getOperand(0).getValueType() == MVT::i1)
6328     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6329                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6330                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6331
6332   // If we have direct moves, we can do all the conversion, skip the store/load
6333   // however, without FPCVT we can't do most conversions.
6334   if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6335     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6336
6337   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6338          "UINT_TO_FP is supported only with FPCVT");
6339
6340   // If we have FCFIDS, then use it when converting to single-precision.
6341   // Otherwise, convert to double-precision and then round.
6342   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6343                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6344                                                             : PPCISD::FCFIDS)
6345                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6346                                                             : PPCISD::FCFID);
6347   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6348                   ? MVT::f32
6349                   : MVT::f64;
6350
6351   if (Op.getOperand(0).getValueType() == MVT::i64) {
6352     SDValue SINT = Op.getOperand(0);
6353     // When converting to single-precision, we actually need to convert
6354     // to double-precision first and then round to single-precision.
6355     // To avoid double-rounding effects during that operation, we have
6356     // to prepare the input operand.  Bits that might be truncated when
6357     // converting to double-precision are replaced by a bit that won't
6358     // be lost at this stage, but is below the single-precision rounding
6359     // position.
6360     //
6361     // However, if -enable-unsafe-fp-math is in effect, accept double
6362     // rounding to avoid the extra overhead.
6363     if (Op.getValueType() == MVT::f32 &&
6364         !Subtarget.hasFPCVT() &&
6365         !DAG.getTarget().Options.UnsafeFPMath) {
6366
6367       // Twiddle input to make sure the low 11 bits are zero.  (If this
6368       // is the case, we are guaranteed the value will fit into the 53 bit
6369       // mantissa of an IEEE double-precision value without rounding.)
6370       // If any of those low 11 bits were not zero originally, make sure
6371       // bit 12 (value 2048) is set instead, so that the final rounding
6372       // to single-precision gets the correct result.
6373       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6374                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6375       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6376                           Round, DAG.getConstant(2047, dl, MVT::i64));
6377       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6378       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6379                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6380
6381       // However, we cannot use that value unconditionally: if the magnitude
6382       // of the input value is small, the bit-twiddling we did above might
6383       // end up visibly changing the output.  Fortunately, in that case, we
6384       // don't need to twiddle bits since the original input will convert
6385       // exactly to double-precision floating-point already.  Therefore,
6386       // construct a conditional to use the original value if the top 11
6387       // bits are all sign-bit copies, and use the rounded value computed
6388       // above otherwise.
6389       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6390                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6391       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6392                          Cond, DAG.getConstant(1, dl, MVT::i64));
6393       Cond = DAG.getSetCC(dl, MVT::i32,
6394                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6395
6396       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6397     }
6398
6399     ReuseLoadInfo RLI;
6400     SDValue Bits;
6401
6402     MachineFunction &MF = DAG.getMachineFunction();
6403     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6404       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6405                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6406                          RLI.Ranges);
6407       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6408     } else if (Subtarget.hasLFIWAX() &&
6409                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6410       MachineMemOperand *MMO =
6411         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6412                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6413       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6414       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6415                                      DAG.getVTList(MVT::f64, MVT::Other),
6416                                      Ops, MVT::i32, MMO);
6417       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6418     } else if (Subtarget.hasFPCVT() &&
6419                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6420       MachineMemOperand *MMO =
6421         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6422                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6423       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6424       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6425                                      DAG.getVTList(MVT::f64, MVT::Other),
6426                                      Ops, MVT::i32, MMO);
6427       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6428     } else if (((Subtarget.hasLFIWAX() &&
6429                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6430                 (Subtarget.hasFPCVT() &&
6431                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6432                SINT.getOperand(0).getValueType() == MVT::i32) {
6433       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6434       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6435
6436       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6437       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6438
6439       SDValue Store = DAG.getStore(
6440           DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6441           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6442           false, false, 0);
6443
6444       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6445              "Expected an i32 store");
6446
6447       RLI.Ptr = FIdx;
6448       RLI.Chain = Store;
6449       RLI.MPI =
6450           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6451       RLI.Alignment = 4;
6452
6453       MachineMemOperand *MMO =
6454         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6455                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6456       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6457       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6458                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6459                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6460                                      Ops, MVT::i32, MMO);
6461     } else
6462       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6463
6464     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6465
6466     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6467       FP = DAG.getNode(ISD::FP_ROUND, dl,
6468                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6469     return FP;
6470   }
6471
6472   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6473          "Unhandled INT_TO_FP type in custom expander!");
6474   // Since we only generate this in 64-bit mode, we can take advantage of
6475   // 64-bit registers.  In particular, sign extend the input value into the
6476   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6477   // then lfd it and fcfid it.
6478   MachineFunction &MF = DAG.getMachineFunction();
6479   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6480   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6481
6482   SDValue Ld;
6483   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6484     ReuseLoadInfo RLI;
6485     bool ReusingLoad;
6486     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6487                                             DAG))) {
6488       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6489       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6490
6491       SDValue Store = DAG.getStore(
6492           DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6493           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6494           false, false, 0);
6495
6496       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6497              "Expected an i32 store");
6498
6499       RLI.Ptr = FIdx;
6500       RLI.Chain = Store;
6501       RLI.MPI =
6502           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6503       RLI.Alignment = 4;
6504     }
6505
6506     MachineMemOperand *MMO =
6507       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6508                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6509     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6510     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6511                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6512                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6513                                  Ops, MVT::i32, MMO);
6514     if (ReusingLoad)
6515       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6516   } else {
6517     assert(Subtarget.isPPC64() &&
6518            "i32->FP without LFIWAX supported only on PPC64");
6519
6520     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6521     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6522
6523     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6524                                 Op.getOperand(0));
6525
6526     // STD the extended value into the stack slot.
6527     SDValue Store = DAG.getStore(
6528         DAG.getEntryNode(), dl, Ext64, FIdx,
6529         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6530         false, false, 0);
6531
6532     // Load the value as a double.
6533     Ld = DAG.getLoad(
6534         MVT::f64, dl, Store, FIdx,
6535         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6536         false, false, false, 0);
6537   }
6538
6539   // FCFID it and return it.
6540   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6541   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6542     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6543                      DAG.getIntPtrConstant(0, dl));
6544   return FP;
6545 }
6546
6547 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6548                                             SelectionDAG &DAG) const {
6549   SDLoc dl(Op);
6550   /*
6551    The rounding mode is in bits 30:31 of FPSR, and has the following
6552    settings:
6553      00 Round to nearest
6554      01 Round to 0
6555      10 Round to +inf
6556      11 Round to -inf
6557
6558   FLT_ROUNDS, on the other hand, expects the following:
6559     -1 Undefined
6560      0 Round to 0
6561      1 Round to nearest
6562      2 Round to +inf
6563      3 Round to -inf
6564
6565   To perform the conversion, we do:
6566     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6567   */
6568
6569   MachineFunction &MF = DAG.getMachineFunction();
6570   EVT VT = Op.getValueType();
6571   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6572
6573   // Save FP Control Word to register
6574   EVT NodeTys[] = {
6575     MVT::f64,    // return register
6576     MVT::Glue    // unused in this context
6577   };
6578   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6579
6580   // Save FP register to stack slot
6581   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6582   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6583   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6584                                StackSlot, MachinePointerInfo(), false, false,0);
6585
6586   // Load FP Control Word from low 32 bits of stack slot.
6587   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6588   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6589   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6590                             false, false, false, 0);
6591
6592   // Transform as necessary
6593   SDValue CWD1 =
6594     DAG.getNode(ISD::AND, dl, MVT::i32,
6595                 CWD, DAG.getConstant(3, dl, MVT::i32));
6596   SDValue CWD2 =
6597     DAG.getNode(ISD::SRL, dl, MVT::i32,
6598                 DAG.getNode(ISD::AND, dl, MVT::i32,
6599                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6600                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6601                             DAG.getConstant(3, dl, MVT::i32)),
6602                 DAG.getConstant(1, dl, MVT::i32));
6603
6604   SDValue RetVal =
6605     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6606
6607   return DAG.getNode((VT.getSizeInBits() < 16 ?
6608                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6609 }
6610
6611 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6612   EVT VT = Op.getValueType();
6613   unsigned BitWidth = VT.getSizeInBits();
6614   SDLoc dl(Op);
6615   assert(Op.getNumOperands() == 3 &&
6616          VT == Op.getOperand(1).getValueType() &&
6617          "Unexpected SHL!");
6618
6619   // Expand into a bunch of logical ops.  Note that these ops
6620   // depend on the PPC behavior for oversized shift amounts.
6621   SDValue Lo = Op.getOperand(0);
6622   SDValue Hi = Op.getOperand(1);
6623   SDValue Amt = Op.getOperand(2);
6624   EVT AmtVT = Amt.getValueType();
6625
6626   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6627                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6628   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6629   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6630   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6631   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6632                              DAG.getConstant(-BitWidth, dl, AmtVT));
6633   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6634   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6635   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6636   SDValue OutOps[] = { OutLo, OutHi };
6637   return DAG.getMergeValues(OutOps, dl);
6638 }
6639
6640 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6641   EVT VT = Op.getValueType();
6642   SDLoc dl(Op);
6643   unsigned BitWidth = VT.getSizeInBits();
6644   assert(Op.getNumOperands() == 3 &&
6645          VT == Op.getOperand(1).getValueType() &&
6646          "Unexpected SRL!");
6647
6648   // Expand into a bunch of logical ops.  Note that these ops
6649   // depend on the PPC behavior for oversized shift amounts.
6650   SDValue Lo = Op.getOperand(0);
6651   SDValue Hi = Op.getOperand(1);
6652   SDValue Amt = Op.getOperand(2);
6653   EVT AmtVT = Amt.getValueType();
6654
6655   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6656                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6657   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6658   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6659   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6660   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6661                              DAG.getConstant(-BitWidth, dl, AmtVT));
6662   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6663   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6664   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6665   SDValue OutOps[] = { OutLo, OutHi };
6666   return DAG.getMergeValues(OutOps, dl);
6667 }
6668
6669 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6670   SDLoc dl(Op);
6671   EVT VT = Op.getValueType();
6672   unsigned BitWidth = VT.getSizeInBits();
6673   assert(Op.getNumOperands() == 3 &&
6674          VT == Op.getOperand(1).getValueType() &&
6675          "Unexpected SRA!");
6676
6677   // Expand into a bunch of logical ops, followed by a select_cc.
6678   SDValue Lo = Op.getOperand(0);
6679   SDValue Hi = Op.getOperand(1);
6680   SDValue Amt = Op.getOperand(2);
6681   EVT AmtVT = Amt.getValueType();
6682
6683   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6684                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6685   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6686   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6687   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6688   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6689                              DAG.getConstant(-BitWidth, dl, AmtVT));
6690   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6691   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6692   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6693                                   Tmp4, Tmp6, ISD::SETLE);
6694   SDValue OutOps[] = { OutLo, OutHi };
6695   return DAG.getMergeValues(OutOps, dl);
6696 }
6697
6698 //===----------------------------------------------------------------------===//
6699 // Vector related lowering.
6700 //
6701
6702 /// BuildSplatI - Build a canonical splati of Val with an element size of
6703 /// SplatSize.  Cast the result to VT.
6704 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6705                              SelectionDAG &DAG, SDLoc dl) {
6706   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6707
6708   static const MVT VTys[] = { // canonical VT to use for each size.
6709     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6710   };
6711
6712   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6713
6714   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6715   if (Val == -1)
6716     SplatSize = 1;
6717
6718   EVT CanonicalVT = VTys[SplatSize-1];
6719
6720   // Build a canonical splat for this value.
6721   SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6722   SmallVector<SDValue, 8> Ops;
6723   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6724   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6725   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6726 }
6727
6728 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6729 /// specified intrinsic ID.
6730 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6731                                 SelectionDAG &DAG, SDLoc dl,
6732                                 EVT DestVT = MVT::Other) {
6733   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6734   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6735                      DAG.getConstant(IID, dl, MVT::i32), Op);
6736 }
6737
6738 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6739 /// specified intrinsic ID.
6740 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6741                                 SelectionDAG &DAG, SDLoc dl,
6742                                 EVT DestVT = MVT::Other) {
6743   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6744   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6745                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6746 }
6747
6748 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6749 /// specified intrinsic ID.
6750 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6751                                 SDValue Op2, SelectionDAG &DAG,
6752                                 SDLoc dl, EVT DestVT = MVT::Other) {
6753   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6754   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6755                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6756 }
6757
6758
6759 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6760 /// amount.  The result has the specified value type.
6761 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6762                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6763   // Force LHS/RHS to be the right type.
6764   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6765   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6766
6767   int Ops[16];
6768   for (unsigned i = 0; i != 16; ++i)
6769     Ops[i] = i + Amt;
6770   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6771   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6772 }
6773
6774 // If this is a case we can't handle, return null and let the default
6775 // expansion code take care of it.  If we CAN select this case, and if it
6776 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6777 // this case more efficiently than a constant pool load, lower it to the
6778 // sequence of ops that should be used.
6779 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6780                                              SelectionDAG &DAG) const {
6781   SDLoc dl(Op);
6782   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6783   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6784
6785   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6786     // We first build an i32 vector, load it into a QPX register,
6787     // then convert it to a floating-point vector and compare it
6788     // to a zero vector to get the boolean result.
6789     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6790     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6791     MachinePointerInfo PtrInfo =
6792         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6793     EVT PtrVT = getPointerTy(DAG.getDataLayout());
6794     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6795
6796     assert(BVN->getNumOperands() == 4 &&
6797       "BUILD_VECTOR for v4i1 does not have 4 operands");
6798
6799     bool IsConst = true;
6800     for (unsigned i = 0; i < 4; ++i) {
6801       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6802       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6803         IsConst = false;
6804         break;
6805       }
6806     }
6807
6808     if (IsConst) {
6809       Constant *One =
6810         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6811       Constant *NegOne =
6812         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6813
6814       SmallVector<Constant*, 4> CV(4, NegOne);
6815       for (unsigned i = 0; i < 4; ++i) {
6816         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6817           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6818         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6819                    getConstantIntValue()->isZero())
6820           continue;
6821         else
6822           CV[i] = One;
6823       }
6824
6825       Constant *CP = ConstantVector::get(CV);
6826       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
6827                                           16 /* alignment */);
6828
6829       SmallVector<SDValue, 2> Ops;
6830       Ops.push_back(DAG.getEntryNode());
6831       Ops.push_back(CPIdx);
6832
6833       SmallVector<EVT, 2> ValueVTs;
6834       ValueVTs.push_back(MVT::v4i1);
6835       ValueVTs.push_back(MVT::Other); // chain
6836       SDVTList VTs = DAG.getVTList(ValueVTs);
6837
6838       return DAG.getMemIntrinsicNode(
6839           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
6840           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
6841     }
6842
6843     SmallVector<SDValue, 4> Stores;
6844     for (unsigned i = 0; i < 4; ++i) {
6845       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6846
6847       unsigned Offset = 4*i;
6848       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6849       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6850
6851       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6852       if (StoreSize > 4) {
6853         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6854                                            BVN->getOperand(i), Idx,
6855                                            PtrInfo.getWithOffset(Offset),
6856                                            MVT::i32, false, false, 0));
6857       } else {
6858         SDValue StoreValue = BVN->getOperand(i);
6859         if (StoreSize < 4)
6860           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6861
6862         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6863                                       StoreValue, Idx,
6864                                       PtrInfo.getWithOffset(Offset),
6865                                       false, false, 0));
6866       }
6867     }
6868
6869     SDValue StoreChain;
6870     if (!Stores.empty())
6871       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6872     else
6873       StoreChain = DAG.getEntryNode();
6874
6875     // Now load from v4i32 into the QPX register; this will extend it to
6876     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6877     // is typed as v4f64 because the QPX register integer states are not
6878     // explicitly represented.
6879
6880     SmallVector<SDValue, 2> Ops;
6881     Ops.push_back(StoreChain);
6882     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6883     Ops.push_back(FIdx);
6884
6885     SmallVector<EVT, 2> ValueVTs;
6886     ValueVTs.push_back(MVT::v4f64);
6887     ValueVTs.push_back(MVT::Other); // chain
6888     SDVTList VTs = DAG.getVTList(ValueVTs);
6889
6890     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6891       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6892     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6893       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6894       LoadedVect);
6895
6896     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6897     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6898                           FPZeros, FPZeros, FPZeros, FPZeros);
6899
6900     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6901   }
6902
6903   // All other QPX vectors are handled by generic code.
6904   if (Subtarget.hasQPX())
6905     return SDValue();
6906
6907   // Check if this is a splat of a constant value.
6908   APInt APSplatBits, APSplatUndef;
6909   unsigned SplatBitSize;
6910   bool HasAnyUndefs;
6911   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6912                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6913       SplatBitSize > 32)
6914     return SDValue();
6915
6916   unsigned SplatBits = APSplatBits.getZExtValue();
6917   unsigned SplatUndef = APSplatUndef.getZExtValue();
6918   unsigned SplatSize = SplatBitSize / 8;
6919
6920   // First, handle single instruction cases.
6921
6922   // All zeros?
6923   if (SplatBits == 0) {
6924     // Canonicalize all zero vectors to be v4i32.
6925     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6926       SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6927       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6928       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6929     }
6930     return Op;
6931   }
6932
6933   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6934   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6935                     (32-SplatBitSize));
6936   if (SextVal >= -16 && SextVal <= 15)
6937     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6938
6939
6940   // Two instruction sequences.
6941
6942   // If this value is in the range [-32,30] and is even, use:
6943   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6944   // If this value is in the range [17,31] and is odd, use:
6945   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6946   // If this value is in the range [-31,-17] and is odd, use:
6947   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6948   // Note the last two are three-instruction sequences.
6949   if (SextVal >= -32 && SextVal <= 31) {
6950     // To avoid having these optimizations undone by constant folding,
6951     // we convert to a pseudo that will be expanded later into one of
6952     // the above forms.
6953     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6954     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6955               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6956     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6957     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6958     if (VT == Op.getValueType())
6959       return RetVal;
6960     else
6961       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6962   }
6963
6964   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6965   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6966   // for fneg/fabs.
6967   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6968     // Make -1 and vspltisw -1:
6969     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6970
6971     // Make the VSLW intrinsic, computing 0x8000_0000.
6972     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6973                                    OnesV, DAG, dl);
6974
6975     // xor by OnesV to invert it.
6976     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6977     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6978   }
6979
6980   // Check to see if this is a wide variety of vsplti*, binop self cases.
6981   static const signed char SplatCsts[] = {
6982     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6983     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6984   };
6985
6986   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6987     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6988     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6989     int i = SplatCsts[idx];
6990
6991     // Figure out what shift amount will be used by altivec if shifted by i in
6992     // this splat size.
6993     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6994
6995     // vsplti + shl self.
6996     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6997       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6998       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6999         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7000         Intrinsic::ppc_altivec_vslw
7001       };
7002       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7003       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7004     }
7005
7006     // vsplti + srl self.
7007     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7008       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7009       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7010         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7011         Intrinsic::ppc_altivec_vsrw
7012       };
7013       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7014       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7015     }
7016
7017     // vsplti + sra self.
7018     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7019       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7020       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7021         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7022         Intrinsic::ppc_altivec_vsraw
7023       };
7024       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7025       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7026     }
7027
7028     // vsplti + rol self.
7029     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7030                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7031       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7032       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7033         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7034         Intrinsic::ppc_altivec_vrlw
7035       };
7036       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7037       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7038     }
7039
7040     // t = vsplti c, result = vsldoi t, t, 1
7041     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7042       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7043       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7044       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7045     }
7046     // t = vsplti c, result = vsldoi t, t, 2
7047     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7048       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7049       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7050       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7051     }
7052     // t = vsplti c, result = vsldoi t, t, 3
7053     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7054       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7055       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7056       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7057     }
7058   }
7059
7060   return SDValue();
7061 }
7062
7063 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7064 /// the specified operations to build the shuffle.
7065 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7066                                       SDValue RHS, SelectionDAG &DAG,
7067                                       SDLoc dl) {
7068   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7069   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7070   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7071
7072   enum {
7073     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7074     OP_VMRGHW,
7075     OP_VMRGLW,
7076     OP_VSPLTISW0,
7077     OP_VSPLTISW1,
7078     OP_VSPLTISW2,
7079     OP_VSPLTISW3,
7080     OP_VSLDOI4,
7081     OP_VSLDOI8,
7082     OP_VSLDOI12
7083   };
7084
7085   if (OpNum == OP_COPY) {
7086     if (LHSID == (1*9+2)*9+3) return LHS;
7087     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7088     return RHS;
7089   }
7090
7091   SDValue OpLHS, OpRHS;
7092   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7093   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7094
7095   int ShufIdxs[16];
7096   switch (OpNum) {
7097   default: llvm_unreachable("Unknown i32 permute!");
7098   case OP_VMRGHW:
7099     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7100     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7101     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7102     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7103     break;
7104   case OP_VMRGLW:
7105     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7106     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7107     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7108     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7109     break;
7110   case OP_VSPLTISW0:
7111     for (unsigned i = 0; i != 16; ++i)
7112       ShufIdxs[i] = (i&3)+0;
7113     break;
7114   case OP_VSPLTISW1:
7115     for (unsigned i = 0; i != 16; ++i)
7116       ShufIdxs[i] = (i&3)+4;
7117     break;
7118   case OP_VSPLTISW2:
7119     for (unsigned i = 0; i != 16; ++i)
7120       ShufIdxs[i] = (i&3)+8;
7121     break;
7122   case OP_VSPLTISW3:
7123     for (unsigned i = 0; i != 16; ++i)
7124       ShufIdxs[i] = (i&3)+12;
7125     break;
7126   case OP_VSLDOI4:
7127     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7128   case OP_VSLDOI8:
7129     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7130   case OP_VSLDOI12:
7131     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7132   }
7133   EVT VT = OpLHS.getValueType();
7134   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7135   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7136   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7137   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7138 }
7139
7140 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7141 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7142 /// return the code it can be lowered into.  Worst case, it can always be
7143 /// lowered into a vperm.
7144 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7145                                                SelectionDAG &DAG) const {
7146   SDLoc dl(Op);
7147   SDValue V1 = Op.getOperand(0);
7148   SDValue V2 = Op.getOperand(1);
7149   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7150   EVT VT = Op.getValueType();
7151   bool isLittleEndian = Subtarget.isLittleEndian();
7152
7153   if (Subtarget.hasQPX()) {
7154     if (VT.getVectorNumElements() != 4)
7155       return SDValue();
7156
7157     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7158
7159     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7160     if (AlignIdx != -1) {
7161       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7162                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7163     } else if (SVOp->isSplat()) {
7164       int SplatIdx = SVOp->getSplatIndex();
7165       if (SplatIdx >= 4) {
7166         std::swap(V1, V2);
7167         SplatIdx -= 4;
7168       }
7169
7170       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7171       // nothing to do.
7172
7173       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7174                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7175     }
7176
7177     // Lower this into a qvgpci/qvfperm pair.
7178
7179     // Compute the qvgpci literal
7180     unsigned idx = 0;
7181     for (unsigned i = 0; i < 4; ++i) {
7182       int m = SVOp->getMaskElt(i);
7183       unsigned mm = m >= 0 ? (unsigned) m : i;
7184       idx |= mm << (3-i)*3;
7185     }
7186
7187     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7188                              DAG.getConstant(idx, dl, MVT::i32));
7189     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7190   }
7191
7192   // Cases that are handled by instructions that take permute immediates
7193   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7194   // selected by the instruction selector.
7195   if (V2.getOpcode() == ISD::UNDEF) {
7196     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7197         PPC::isSplatShuffleMask(SVOp, 2) ||
7198         PPC::isSplatShuffleMask(SVOp, 4) ||
7199         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7200         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7201         PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7202         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7203         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7204         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7205         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7206         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7207         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7208         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7209         PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG)   ||
7210         PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)) {
7211       return Op;
7212     }
7213   }
7214
7215   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7216   // and produce a fixed permutation.  If any of these match, do not lower to
7217   // VPERM.
7218   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7219   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7220       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7221       PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7222       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7223       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7224       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7225       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7226       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7227       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7228       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7229       PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG)             ||
7230       PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))
7231     return Op;
7232
7233   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7234   // perfect shuffle table to emit an optimal matching sequence.
7235   ArrayRef<int> PermMask = SVOp->getMask();
7236
7237   unsigned PFIndexes[4];
7238   bool isFourElementShuffle = true;
7239   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7240     unsigned EltNo = 8;   // Start out undef.
7241     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7242       if (PermMask[i*4+j] < 0)
7243         continue;   // Undef, ignore it.
7244
7245       unsigned ByteSource = PermMask[i*4+j];
7246       if ((ByteSource & 3) != j) {
7247         isFourElementShuffle = false;
7248         break;
7249       }
7250
7251       if (EltNo == 8) {
7252         EltNo = ByteSource/4;
7253       } else if (EltNo != ByteSource/4) {
7254         isFourElementShuffle = false;
7255         break;
7256       }
7257     }
7258     PFIndexes[i] = EltNo;
7259   }
7260
7261   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7262   // perfect shuffle vector to determine if it is cost effective to do this as
7263   // discrete instructions, or whether we should use a vperm.
7264   // For now, we skip this for little endian until such time as we have a
7265   // little-endian perfect shuffle table.
7266   if (isFourElementShuffle && !isLittleEndian) {
7267     // Compute the index in the perfect shuffle table.
7268     unsigned PFTableIndex =
7269       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7270
7271     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7272     unsigned Cost  = (PFEntry >> 30);
7273
7274     // Determining when to avoid vperm is tricky.  Many things affect the cost
7275     // of vperm, particularly how many times the perm mask needs to be computed.
7276     // For example, if the perm mask can be hoisted out of a loop or is already
7277     // used (perhaps because there are multiple permutes with the same shuffle
7278     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7279     // the loop requires an extra register.
7280     //
7281     // As a compromise, we only emit discrete instructions if the shuffle can be
7282     // generated in 3 or fewer operations.  When we have loop information
7283     // available, if this block is within a loop, we should avoid using vperm
7284     // for 3-operation perms and use a constant pool load instead.
7285     if (Cost < 3)
7286       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7287   }
7288
7289   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7290   // vector that will get spilled to the constant pool.
7291   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7292
7293   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7294   // that it is in input element units, not in bytes.  Convert now.
7295
7296   // For little endian, the order of the input vectors is reversed, and
7297   // the permutation mask is complemented with respect to 31.  This is
7298   // necessary to produce proper semantics with the big-endian-biased vperm
7299   // instruction.
7300   EVT EltVT = V1.getValueType().getVectorElementType();
7301   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7302
7303   SmallVector<SDValue, 16> ResultMask;
7304   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7305     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7306
7307     for (unsigned j = 0; j != BytesPerElement; ++j)
7308       if (isLittleEndian)
7309         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7310                                              dl, MVT::i32));
7311       else
7312         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7313                                              MVT::i32));
7314   }
7315
7316   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7317                                   ResultMask);
7318   if (isLittleEndian)
7319     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7320                        V2, V1, VPermMask);
7321   else
7322     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7323                        V1, V2, VPermMask);
7324 }
7325
7326 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7327 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7328 /// information about the intrinsic.
7329 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7330                                   bool &isDot, const PPCSubtarget &Subtarget) {
7331   unsigned IntrinsicID =
7332     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7333   CompareOpc = -1;
7334   isDot = false;
7335   switch (IntrinsicID) {
7336   default: return false;
7337     // Comparison predicates.
7338   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7339   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7340   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7341   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7342   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7343   case Intrinsic::ppc_altivec_vcmpequd_p: 
7344     if (Subtarget.hasP8Altivec()) {
7345       CompareOpc = 199; 
7346       isDot = 1; 
7347     }
7348     else 
7349       return false;
7350
7351     break;
7352   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7353   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7354   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7355   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7356   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7357   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7358     if (Subtarget.hasP8Altivec()) {
7359       CompareOpc = 967; 
7360       isDot = 1; 
7361     }
7362     else 
7363       return false;
7364
7365     break;
7366   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7367   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7368   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7369   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7370     if (Subtarget.hasP8Altivec()) {
7371       CompareOpc = 711; 
7372       isDot = 1; 
7373     }
7374     else 
7375       return false;
7376
7377     break;
7378       
7379     // Normal Comparisons.
7380   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7381   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7382   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7383   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7384   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7385   case Intrinsic::ppc_altivec_vcmpequd:
7386     if (Subtarget.hasP8Altivec()) {
7387       CompareOpc = 199; 
7388       isDot = 0; 
7389     }
7390     else
7391       return false;
7392
7393     break;
7394   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7395   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7396   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7397   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7398   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7399   case Intrinsic::ppc_altivec_vcmpgtsd:   
7400     if (Subtarget.hasP8Altivec()) {
7401       CompareOpc = 967; 
7402       isDot = 0; 
7403     }
7404     else
7405       return false;
7406
7407     break;
7408   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7409   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7410   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7411   case Intrinsic::ppc_altivec_vcmpgtud:   
7412     if (Subtarget.hasP8Altivec()) {
7413       CompareOpc = 711; 
7414       isDot = 0; 
7415     }
7416     else
7417       return false;
7418
7419     break;
7420   }
7421   return true;
7422 }
7423
7424 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7425 /// lower, do it, otherwise return null.
7426 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7427                                                    SelectionDAG &DAG) const {
7428   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7429   // opcode number of the comparison.
7430   SDLoc dl(Op);
7431   int CompareOpc;
7432   bool isDot;
7433   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7434     return SDValue();    // Don't custom lower most intrinsics.
7435
7436   // If this is a non-dot comparison, make the VCMP node and we are done.
7437   if (!isDot) {
7438     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7439                               Op.getOperand(1), Op.getOperand(2),
7440                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7441     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7442   }
7443
7444   // Create the PPCISD altivec 'dot' comparison node.
7445   SDValue Ops[] = {
7446     Op.getOperand(2),  // LHS
7447     Op.getOperand(3),  // RHS
7448     DAG.getConstant(CompareOpc, dl, MVT::i32)
7449   };
7450   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7451   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7452
7453   // Now that we have the comparison, emit a copy from the CR to a GPR.
7454   // This is flagged to the above dot comparison.
7455   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7456                                 DAG.getRegister(PPC::CR6, MVT::i32),
7457                                 CompNode.getValue(1));
7458
7459   // Unpack the result based on how the target uses it.
7460   unsigned BitNo;   // Bit # of CR6.
7461   bool InvertBit;   // Invert result?
7462   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7463   default:  // Can't happen, don't crash on invalid number though.
7464   case 0:   // Return the value of the EQ bit of CR6.
7465     BitNo = 0; InvertBit = false;
7466     break;
7467   case 1:   // Return the inverted value of the EQ bit of CR6.
7468     BitNo = 0; InvertBit = true;
7469     break;
7470   case 2:   // Return the value of the LT bit of CR6.
7471     BitNo = 2; InvertBit = false;
7472     break;
7473   case 3:   // Return the inverted value of the LT bit of CR6.
7474     BitNo = 2; InvertBit = true;
7475     break;
7476   }
7477
7478   // Shift the bit into the low position.
7479   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7480                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7481   // Isolate the bit.
7482   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7483                       DAG.getConstant(1, dl, MVT::i32));
7484
7485   // If we are supposed to, toggle the bit.
7486   if (InvertBit)
7487     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7488                         DAG.getConstant(1, dl, MVT::i32));
7489   return Flags;
7490 }
7491
7492 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7493                                                   SelectionDAG &DAG) const {
7494   SDLoc dl(Op);
7495   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7496   // instructions), but for smaller types, we need to first extend up to v2i32
7497   // before doing going farther.
7498   if (Op.getValueType() == MVT::v2i64) {
7499     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7500     if (ExtVT != MVT::v2i32) {
7501       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7502       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7503                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7504                                         ExtVT.getVectorElementType(), 4)));
7505       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7506       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7507                        DAG.getValueType(MVT::v2i32));
7508     }
7509
7510     return Op;
7511   }
7512
7513   return SDValue();
7514 }
7515
7516 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7517                                                    SelectionDAG &DAG) const {
7518   SDLoc dl(Op);
7519   // Create a stack slot that is 16-byte aligned.
7520   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7521   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7522   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7523   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7524
7525   // Store the input value into Value#0 of the stack slot.
7526   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7527                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7528                                false, false, 0);
7529   // Load it out.
7530   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7531                      false, false, false, 0);
7532 }
7533
7534 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7535                                                    SelectionDAG &DAG) const {
7536   SDLoc dl(Op);
7537   SDNode *N = Op.getNode();
7538
7539   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7540          "Unknown extract_vector_elt type");
7541
7542   SDValue Value = N->getOperand(0);
7543
7544   // The first part of this is like the store lowering except that we don't
7545   // need to track the chain.
7546
7547   // The values are now known to be -1 (false) or 1 (true). To convert this
7548   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7549   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7550   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7551
7552   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7553   // understand how to form the extending load.
7554   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7555   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7556                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7557
7558   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7559
7560   // Now convert to an integer and store.
7561   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7562     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7563     Value);
7564
7565   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7566   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7567   MachinePointerInfo PtrInfo =
7568       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7569   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7570   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7571
7572   SDValue StoreChain = DAG.getEntryNode();
7573   SmallVector<SDValue, 2> Ops;
7574   Ops.push_back(StoreChain);
7575   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7576   Ops.push_back(Value);
7577   Ops.push_back(FIdx);
7578
7579   SmallVector<EVT, 2> ValueVTs;
7580   ValueVTs.push_back(MVT::Other); // chain
7581   SDVTList VTs = DAG.getVTList(ValueVTs);
7582
7583   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7584     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7585
7586   // Extract the value requested.
7587   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7588   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7589   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7590
7591   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7592                                PtrInfo.getWithOffset(Offset),
7593                                false, false, false, 0);
7594
7595   if (!Subtarget.useCRBits())
7596     return IntVal;
7597
7598   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7599 }
7600
7601 /// Lowering for QPX v4i1 loads
7602 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7603                                            SelectionDAG &DAG) const {
7604   SDLoc dl(Op);
7605   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7606   SDValue LoadChain = LN->getChain();
7607   SDValue BasePtr = LN->getBasePtr();
7608
7609   if (Op.getValueType() == MVT::v4f64 ||
7610       Op.getValueType() == MVT::v4f32) {
7611     EVT MemVT = LN->getMemoryVT();
7612     unsigned Alignment = LN->getAlignment();
7613
7614     // If this load is properly aligned, then it is legal.
7615     if (Alignment >= MemVT.getStoreSize())
7616       return Op;
7617
7618     EVT ScalarVT = Op.getValueType().getScalarType(),
7619         ScalarMemVT = MemVT.getScalarType();
7620     unsigned Stride = ScalarMemVT.getStoreSize();
7621
7622     SmallVector<SDValue, 8> Vals, LoadChains;
7623     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7624       SDValue Load;
7625       if (ScalarVT != ScalarMemVT)
7626         Load =
7627           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7628                          BasePtr,
7629                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7630                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7631                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7632                          LN->getAAInfo());
7633       else
7634         Load =
7635           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7636                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7637                        LN->isVolatile(), LN->isNonTemporal(),
7638                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7639                        LN->getAAInfo());
7640
7641       if (Idx == 0 && LN->isIndexed()) {
7642         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7643                "Unknown addressing mode on vector load");
7644         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7645                                   LN->getAddressingMode());
7646       }
7647
7648       Vals.push_back(Load);
7649       LoadChains.push_back(Load.getValue(1));
7650
7651       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7652                             DAG.getConstant(Stride, dl,
7653                                             BasePtr.getValueType()));
7654     }
7655
7656     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7657     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7658                                 Op.getValueType(), Vals);
7659
7660     if (LN->isIndexed()) {
7661       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7662       return DAG.getMergeValues(RetOps, dl);
7663     }
7664
7665     SDValue RetOps[] = { Value, TF };
7666     return DAG.getMergeValues(RetOps, dl);
7667   }
7668
7669   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7670   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7671
7672   // To lower v4i1 from a byte array, we load the byte elements of the
7673   // vector and then reuse the BUILD_VECTOR logic.
7674
7675   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7676   for (unsigned i = 0; i < 4; ++i) {
7677     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7678     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7679
7680     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7681                         dl, MVT::i32, LoadChain, Idx,
7682                         LN->getPointerInfo().getWithOffset(i),
7683                         MVT::i8 /* memory type */,
7684                         LN->isVolatile(), LN->isNonTemporal(),
7685                         LN->isInvariant(),
7686                         1 /* alignment */, LN->getAAInfo()));
7687     VectElmtChains.push_back(VectElmts[i].getValue(1));
7688   }
7689
7690   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7691   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7692
7693   SDValue RVals[] = { Value, LoadChain };
7694   return DAG.getMergeValues(RVals, dl);
7695 }
7696
7697 /// Lowering for QPX v4i1 stores
7698 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7699                                             SelectionDAG &DAG) const {
7700   SDLoc dl(Op);
7701   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7702   SDValue StoreChain = SN->getChain();
7703   SDValue BasePtr = SN->getBasePtr();
7704   SDValue Value = SN->getValue();
7705
7706   if (Value.getValueType() == MVT::v4f64 ||
7707       Value.getValueType() == MVT::v4f32) {
7708     EVT MemVT = SN->getMemoryVT();
7709     unsigned Alignment = SN->getAlignment();
7710
7711     // If this store is properly aligned, then it is legal.
7712     if (Alignment >= MemVT.getStoreSize())
7713       return Op;
7714
7715     EVT ScalarVT = Value.getValueType().getScalarType(),
7716         ScalarMemVT = MemVT.getScalarType();
7717     unsigned Stride = ScalarMemVT.getStoreSize();
7718
7719     SmallVector<SDValue, 8> Stores;
7720     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7721       SDValue Ex = DAG.getNode(
7722           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7723           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
7724       SDValue Store;
7725       if (ScalarVT != ScalarMemVT)
7726         Store =
7727           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7728                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7729                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7730                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7731       else
7732         Store =
7733           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7734                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7735                        SN->isVolatile(), SN->isNonTemporal(),
7736                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7737
7738       if (Idx == 0 && SN->isIndexed()) {
7739         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7740                "Unknown addressing mode on vector store");
7741         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7742                                     SN->getAddressingMode());
7743       }
7744
7745       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7746                             DAG.getConstant(Stride, dl,
7747                                             BasePtr.getValueType()));
7748       Stores.push_back(Store);
7749     }
7750
7751     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7752
7753     if (SN->isIndexed()) {
7754       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7755       return DAG.getMergeValues(RetOps, dl);
7756     }
7757
7758     return TF;
7759   }
7760
7761   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7762   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7763
7764   // The values are now known to be -1 (false) or 1 (true). To convert this
7765   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7766   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7767   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7768
7769   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7770   // understand how to form the extending load.
7771   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7772   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7773                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7774
7775   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7776
7777   // Now convert to an integer and store.
7778   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7779     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7780     Value);
7781
7782   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7783   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7784   MachinePointerInfo PtrInfo =
7785       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7786   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7787   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7788
7789   SmallVector<SDValue, 2> Ops;
7790   Ops.push_back(StoreChain);
7791   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7792   Ops.push_back(Value);
7793   Ops.push_back(FIdx);
7794
7795   SmallVector<EVT, 2> ValueVTs;
7796   ValueVTs.push_back(MVT::Other); // chain
7797   SDVTList VTs = DAG.getVTList(ValueVTs);
7798
7799   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7800     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7801
7802   // Move data into the byte array.
7803   SmallVector<SDValue, 4> Loads, LoadChains;
7804   for (unsigned i = 0; i < 4; ++i) {
7805     unsigned Offset = 4*i;
7806     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7807     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7808
7809     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7810                                    PtrInfo.getWithOffset(Offset),
7811                                    false, false, false, 0));
7812     LoadChains.push_back(Loads[i].getValue(1));
7813   }
7814
7815   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7816
7817   SmallVector<SDValue, 4> Stores;
7818   for (unsigned i = 0; i < 4; ++i) {
7819     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7820     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7821
7822     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7823                                        SN->getPointerInfo().getWithOffset(i),
7824                                        MVT::i8 /* memory type */,
7825                                        SN->isNonTemporal(), SN->isVolatile(), 
7826                                        1 /* alignment */, SN->getAAInfo()));
7827   }
7828
7829   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7830
7831   return StoreChain;
7832 }
7833
7834 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7835   SDLoc dl(Op);
7836   if (Op.getValueType() == MVT::v4i32) {
7837     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7838
7839     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7840     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7841
7842     SDValue RHSSwap =   // = vrlw RHS, 16
7843       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7844
7845     // Shrinkify inputs to v8i16.
7846     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7847     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7848     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7849
7850     // Low parts multiplied together, generating 32-bit results (we ignore the
7851     // top parts).
7852     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7853                                         LHS, RHS, DAG, dl, MVT::v4i32);
7854
7855     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7856                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7857     // Shift the high parts up 16 bits.
7858     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7859                               Neg16, DAG, dl);
7860     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7861   } else if (Op.getValueType() == MVT::v8i16) {
7862     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7863
7864     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7865
7866     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7867                             LHS, RHS, Zero, DAG, dl);
7868   } else if (Op.getValueType() == MVT::v16i8) {
7869     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7870     bool isLittleEndian = Subtarget.isLittleEndian();
7871
7872     // Multiply the even 8-bit parts, producing 16-bit sums.
7873     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7874                                            LHS, RHS, DAG, dl, MVT::v8i16);
7875     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7876
7877     // Multiply the odd 8-bit parts, producing 16-bit sums.
7878     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7879                                           LHS, RHS, DAG, dl, MVT::v8i16);
7880     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7881
7882     // Merge the results together.  Because vmuleub and vmuloub are
7883     // instructions with a big-endian bias, we must reverse the
7884     // element numbering and reverse the meaning of "odd" and "even"
7885     // when generating little endian code.
7886     int Ops[16];
7887     for (unsigned i = 0; i != 8; ++i) {
7888       if (isLittleEndian) {
7889         Ops[i*2  ] = 2*i;
7890         Ops[i*2+1] = 2*i+16;
7891       } else {
7892         Ops[i*2  ] = 2*i+1;
7893         Ops[i*2+1] = 2*i+1+16;
7894       }
7895     }
7896     if (isLittleEndian)
7897       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7898     else
7899       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7900   } else {
7901     llvm_unreachable("Unknown mul to lower!");
7902   }
7903 }
7904
7905 /// LowerOperation - Provide custom lowering hooks for some operations.
7906 ///
7907 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7908   switch (Op.getOpcode()) {
7909   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7910   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7911   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7912   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7913   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7914   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7915   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7916   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7917   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7918   case ISD::VASTART:
7919     return LowerVASTART(Op, DAG, Subtarget);
7920
7921   case ISD::VAARG:
7922     return LowerVAARG(Op, DAG, Subtarget);
7923
7924   case ISD::VACOPY:
7925     return LowerVACOPY(Op, DAG, Subtarget);
7926
7927   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7928   case ISD::DYNAMIC_STACKALLOC:
7929     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7930
7931   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7932   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7933
7934   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7935   case ISD::STORE:              return LowerSTORE(Op, DAG);
7936   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7937   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7938   case ISD::FP_TO_UINT:
7939   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7940                                                       SDLoc(Op));
7941   case ISD::UINT_TO_FP:
7942   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7943   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7944
7945   // Lower 64-bit shifts.
7946   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7947   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7948   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7949
7950   // Vector-related lowering.
7951   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7952   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7953   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7954   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7955   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7956   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7957   case ISD::MUL:                return LowerMUL(Op, DAG);
7958
7959   // For counter-based loop handling.
7960   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7961
7962   // Frame & Return address.
7963   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7964   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7965   }
7966 }
7967
7968 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7969                                            SmallVectorImpl<SDValue>&Results,
7970                                            SelectionDAG &DAG) const {
7971   SDLoc dl(N);
7972   switch (N->getOpcode()) {
7973   default:
7974     llvm_unreachable("Do not know how to custom type legalize this operation!");
7975   case ISD::READCYCLECOUNTER: {
7976     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7977     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7978
7979     Results.push_back(RTB);
7980     Results.push_back(RTB.getValue(1));
7981     Results.push_back(RTB.getValue(2));
7982     break;
7983   }
7984   case ISD::INTRINSIC_W_CHAIN: {
7985     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7986         Intrinsic::ppc_is_decremented_ctr_nonzero)
7987       break;
7988
7989     assert(N->getValueType(0) == MVT::i1 &&
7990            "Unexpected result type for CTR decrement intrinsic");
7991     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
7992                                  N->getValueType(0));
7993     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7994     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7995                                  N->getOperand(1)); 
7996
7997     Results.push_back(NewInt);
7998     Results.push_back(NewInt.getValue(1));
7999     break;
8000   }
8001   case ISD::VAARG: {
8002     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8003       return;
8004
8005     EVT VT = N->getValueType(0);
8006
8007     if (VT == MVT::i64) {
8008       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
8009
8010       Results.push_back(NewNode);
8011       Results.push_back(NewNode.getValue(1));
8012     }
8013     return;
8014   }
8015   case ISD::FP_ROUND_INREG: {
8016     assert(N->getValueType(0) == MVT::ppcf128);
8017     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8018     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8019                              MVT::f64, N->getOperand(0),
8020                              DAG.getIntPtrConstant(0, dl));
8021     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8022                              MVT::f64, N->getOperand(0),
8023                              DAG.getIntPtrConstant(1, dl));
8024
8025     // Add the two halves of the long double in round-to-zero mode.
8026     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8027
8028     // We know the low half is about to be thrown away, so just use something
8029     // convenient.
8030     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8031                                 FPreg, FPreg));
8032     return;
8033   }
8034   case ISD::FP_TO_SINT:
8035   case ISD::FP_TO_UINT:
8036     // LowerFP_TO_INT() can only handle f32 and f64.
8037     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8038       return;
8039     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8040     return;
8041   }
8042 }
8043
8044
8045 //===----------------------------------------------------------------------===//
8046 //  Other Lowering Code
8047 //===----------------------------------------------------------------------===//
8048
8049 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8050   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8051   Function *Func = Intrinsic::getDeclaration(M, Id);
8052   return Builder.CreateCall(Func, {});
8053 }
8054
8055 // The mappings for emitLeading/TrailingFence is taken from
8056 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8057 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8058                                          AtomicOrdering Ord, bool IsStore,
8059                                          bool IsLoad) const {
8060   if (Ord == SequentiallyConsistent)
8061     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8062   if (isAtLeastRelease(Ord))
8063     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8064   return nullptr;
8065 }
8066
8067 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8068                                           AtomicOrdering Ord, bool IsStore,
8069                                           bool IsLoad) const {
8070   if (IsLoad && isAtLeastAcquire(Ord))
8071     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8072   // FIXME: this is too conservative, a dependent branch + isync is enough.
8073   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8074   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8075   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8076   return nullptr;
8077 }
8078
8079 MachineBasicBlock *
8080 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
8081                                     unsigned AtomicSize,
8082                                     unsigned BinOpcode) const {
8083   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8084   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8085
8086   auto LoadMnemonic = PPC::LDARX;
8087   auto StoreMnemonic = PPC::STDCX;
8088   switch (AtomicSize) {
8089   default:
8090     llvm_unreachable("Unexpected size of atomic entity");
8091   case 1:
8092     LoadMnemonic = PPC::LBARX;
8093     StoreMnemonic = PPC::STBCX;
8094     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8095     break;
8096   case 2:
8097     LoadMnemonic = PPC::LHARX;
8098     StoreMnemonic = PPC::STHCX;
8099     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8100     break;
8101   case 4:
8102     LoadMnemonic = PPC::LWARX;
8103     StoreMnemonic = PPC::STWCX;
8104     break;
8105   case 8:
8106     LoadMnemonic = PPC::LDARX;
8107     StoreMnemonic = PPC::STDCX;
8108     break;
8109   }
8110
8111   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8112   MachineFunction *F = BB->getParent();
8113   MachineFunction::iterator It = BB;
8114   ++It;
8115
8116   unsigned dest = MI->getOperand(0).getReg();
8117   unsigned ptrA = MI->getOperand(1).getReg();
8118   unsigned ptrB = MI->getOperand(2).getReg();
8119   unsigned incr = MI->getOperand(3).getReg();
8120   DebugLoc dl = MI->getDebugLoc();
8121
8122   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8123   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8124   F->insert(It, loopMBB);
8125   F->insert(It, exitMBB);
8126   exitMBB->splice(exitMBB->begin(), BB,
8127                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8128   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8129
8130   MachineRegisterInfo &RegInfo = F->getRegInfo();
8131   unsigned TmpReg = (!BinOpcode) ? incr :
8132     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8133                                            : &PPC::GPRCRegClass);
8134
8135   //  thisMBB:
8136   //   ...
8137   //   fallthrough --> loopMBB
8138   BB->addSuccessor(loopMBB);
8139
8140   //  loopMBB:
8141   //   l[wd]arx dest, ptr
8142   //   add r0, dest, incr
8143   //   st[wd]cx. r0, ptr
8144   //   bne- loopMBB
8145   //   fallthrough --> exitMBB
8146   BB = loopMBB;
8147   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8148     .addReg(ptrA).addReg(ptrB);
8149   if (BinOpcode)
8150     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8151   BuildMI(BB, dl, TII->get(StoreMnemonic))
8152     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8153   BuildMI(BB, dl, TII->get(PPC::BCC))
8154     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8155   BB->addSuccessor(loopMBB);
8156   BB->addSuccessor(exitMBB);
8157
8158   //  exitMBB:
8159   //   ...
8160   BB = exitMBB;
8161   return BB;
8162 }
8163
8164 MachineBasicBlock *
8165 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8166                                             MachineBasicBlock *BB,
8167                                             bool is8bit,    // operation
8168                                             unsigned BinOpcode) const {
8169   // If we support part-word atomic mnemonics, just use them
8170   if (Subtarget.hasPartwordAtomics())
8171     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8172
8173   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8174   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8175   // In 64 bit mode we have to use 64 bits for addresses, even though the
8176   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8177   // registers without caring whether they're 32 or 64, but here we're
8178   // doing actual arithmetic on the addresses.
8179   bool is64bit = Subtarget.isPPC64();
8180   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8181
8182   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8183   MachineFunction *F = BB->getParent();
8184   MachineFunction::iterator It = BB;
8185   ++It;
8186
8187   unsigned dest = MI->getOperand(0).getReg();
8188   unsigned ptrA = MI->getOperand(1).getReg();
8189   unsigned ptrB = MI->getOperand(2).getReg();
8190   unsigned incr = MI->getOperand(3).getReg();
8191   DebugLoc dl = MI->getDebugLoc();
8192
8193   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8194   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8195   F->insert(It, loopMBB);
8196   F->insert(It, exitMBB);
8197   exitMBB->splice(exitMBB->begin(), BB,
8198                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8199   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8200
8201   MachineRegisterInfo &RegInfo = F->getRegInfo();
8202   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8203                                           : &PPC::GPRCRegClass;
8204   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8205   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8206   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8207   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8208   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8209   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8210   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8211   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8212   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8213   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8214   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8215   unsigned Ptr1Reg;
8216   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8217
8218   //  thisMBB:
8219   //   ...
8220   //   fallthrough --> loopMBB
8221   BB->addSuccessor(loopMBB);
8222
8223   // The 4-byte load must be aligned, while a char or short may be
8224   // anywhere in the word.  Hence all this nasty bookkeeping code.
8225   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8226   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8227   //   xori shift, shift1, 24 [16]
8228   //   rlwinm ptr, ptr1, 0, 0, 29
8229   //   slw incr2, incr, shift
8230   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8231   //   slw mask, mask2, shift
8232   //  loopMBB:
8233   //   lwarx tmpDest, ptr
8234   //   add tmp, tmpDest, incr2
8235   //   andc tmp2, tmpDest, mask
8236   //   and tmp3, tmp, mask
8237   //   or tmp4, tmp3, tmp2
8238   //   stwcx. tmp4, ptr
8239   //   bne- loopMBB
8240   //   fallthrough --> exitMBB
8241   //   srw dest, tmpDest, shift
8242   if (ptrA != ZeroReg) {
8243     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8244     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8245       .addReg(ptrA).addReg(ptrB);
8246   } else {
8247     Ptr1Reg = ptrB;
8248   }
8249   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8250       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8251   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8252       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8253   if (is64bit)
8254     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8255       .addReg(Ptr1Reg).addImm(0).addImm(61);
8256   else
8257     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8258       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8259   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8260       .addReg(incr).addReg(ShiftReg);
8261   if (is8bit)
8262     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8263   else {
8264     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8265     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8266   }
8267   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8268       .addReg(Mask2Reg).addReg(ShiftReg);
8269
8270   BB = loopMBB;
8271   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8272     .addReg(ZeroReg).addReg(PtrReg);
8273   if (BinOpcode)
8274     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8275       .addReg(Incr2Reg).addReg(TmpDestReg);
8276   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8277     .addReg(TmpDestReg).addReg(MaskReg);
8278   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8279     .addReg(TmpReg).addReg(MaskReg);
8280   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8281     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8282   BuildMI(BB, dl, TII->get(PPC::STWCX))
8283     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8284   BuildMI(BB, dl, TII->get(PPC::BCC))
8285     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8286   BB->addSuccessor(loopMBB);
8287   BB->addSuccessor(exitMBB);
8288
8289   //  exitMBB:
8290   //   ...
8291   BB = exitMBB;
8292   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8293     .addReg(ShiftReg);
8294   return BB;
8295 }
8296
8297 llvm::MachineBasicBlock*
8298 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8299                                     MachineBasicBlock *MBB) const {
8300   DebugLoc DL = MI->getDebugLoc();
8301   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8302
8303   MachineFunction *MF = MBB->getParent();
8304   MachineRegisterInfo &MRI = MF->getRegInfo();
8305
8306   const BasicBlock *BB = MBB->getBasicBlock();
8307   MachineFunction::iterator I = MBB;
8308   ++I;
8309
8310   // Memory Reference
8311   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8312   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8313
8314   unsigned DstReg = MI->getOperand(0).getReg();
8315   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8316   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8317   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8318   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8319
8320   MVT PVT = getPointerTy(MF->getDataLayout());
8321   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8322          "Invalid Pointer Size!");
8323   // For v = setjmp(buf), we generate
8324   //
8325   // thisMBB:
8326   //  SjLjSetup mainMBB
8327   //  bl mainMBB
8328   //  v_restore = 1
8329   //  b sinkMBB
8330   //
8331   // mainMBB:
8332   //  buf[LabelOffset] = LR
8333   //  v_main = 0
8334   //
8335   // sinkMBB:
8336   //  v = phi(main, restore)
8337   //
8338
8339   MachineBasicBlock *thisMBB = MBB;
8340   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8341   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8342   MF->insert(I, mainMBB);
8343   MF->insert(I, sinkMBB);
8344
8345   MachineInstrBuilder MIB;
8346
8347   // Transfer the remainder of BB and its successor edges to sinkMBB.
8348   sinkMBB->splice(sinkMBB->begin(), MBB,
8349                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8350   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8351
8352   // Note that the structure of the jmp_buf used here is not compatible
8353   // with that used by libc, and is not designed to be. Specifically, it
8354   // stores only those 'reserved' registers that LLVM does not otherwise
8355   // understand how to spill. Also, by convention, by the time this
8356   // intrinsic is called, Clang has already stored the frame address in the
8357   // first slot of the buffer and stack address in the third. Following the
8358   // X86 target code, we'll store the jump address in the second slot. We also
8359   // need to save the TOC pointer (R2) to handle jumps between shared
8360   // libraries, and that will be stored in the fourth slot. The thread
8361   // identifier (R13) is not affected.
8362
8363   // thisMBB:
8364   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8365   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8366   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8367
8368   // Prepare IP either in reg.
8369   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8370   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8371   unsigned BufReg = MI->getOperand(1).getReg();
8372
8373   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8374     setUsesTOCBasePtr(*MBB->getParent());
8375     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8376             .addReg(PPC::X2)
8377             .addImm(TOCOffset)
8378             .addReg(BufReg);
8379     MIB.setMemRefs(MMOBegin, MMOEnd);
8380   }
8381
8382   // Naked functions never have a base pointer, and so we use r1. For all
8383   // other functions, this decision must be delayed until during PEI.
8384   unsigned BaseReg;
8385   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8386     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8387   else
8388     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8389
8390   MIB = BuildMI(*thisMBB, MI, DL,
8391                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8392             .addReg(BaseReg)
8393             .addImm(BPOffset)
8394             .addReg(BufReg);
8395   MIB.setMemRefs(MMOBegin, MMOEnd);
8396
8397   // Setup
8398   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8399   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8400   MIB.addRegMask(TRI->getNoPreservedMask());
8401
8402   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8403
8404   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8405           .addMBB(mainMBB);
8406   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8407
8408   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8409   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8410
8411   // mainMBB:
8412   //  mainDstReg = 0
8413   MIB =
8414       BuildMI(mainMBB, DL,
8415               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8416
8417   // Store IP
8418   if (Subtarget.isPPC64()) {
8419     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8420             .addReg(LabelReg)
8421             .addImm(LabelOffset)
8422             .addReg(BufReg);
8423   } else {
8424     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8425             .addReg(LabelReg)
8426             .addImm(LabelOffset)
8427             .addReg(BufReg);
8428   }
8429
8430   MIB.setMemRefs(MMOBegin, MMOEnd);
8431
8432   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8433   mainMBB->addSuccessor(sinkMBB);
8434
8435   // sinkMBB:
8436   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8437           TII->get(PPC::PHI), DstReg)
8438     .addReg(mainDstReg).addMBB(mainMBB)
8439     .addReg(restoreDstReg).addMBB(thisMBB);
8440
8441   MI->eraseFromParent();
8442   return sinkMBB;
8443 }
8444
8445 MachineBasicBlock *
8446 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8447                                      MachineBasicBlock *MBB) const {
8448   DebugLoc DL = MI->getDebugLoc();
8449   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8450
8451   MachineFunction *MF = MBB->getParent();
8452   MachineRegisterInfo &MRI = MF->getRegInfo();
8453
8454   // Memory Reference
8455   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8456   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8457
8458   MVT PVT = getPointerTy(MF->getDataLayout());
8459   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8460          "Invalid Pointer Size!");
8461
8462   const TargetRegisterClass *RC =
8463     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8464   unsigned Tmp = MRI.createVirtualRegister(RC);
8465   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8466   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8467   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8468   unsigned BP =
8469       (PVT == MVT::i64)
8470           ? PPC::X30
8471           : (Subtarget.isSVR4ABI() &&
8472                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8473                  ? PPC::R29
8474                  : PPC::R30);
8475
8476   MachineInstrBuilder MIB;
8477
8478   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8479   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8480   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8481   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8482
8483   unsigned BufReg = MI->getOperand(0).getReg();
8484
8485   // Reload FP (the jumped-to function may not have had a
8486   // frame pointer, and if so, then its r31 will be restored
8487   // as necessary).
8488   if (PVT == MVT::i64) {
8489     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8490             .addImm(0)
8491             .addReg(BufReg);
8492   } else {
8493     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8494             .addImm(0)
8495             .addReg(BufReg);
8496   }
8497   MIB.setMemRefs(MMOBegin, MMOEnd);
8498
8499   // Reload IP
8500   if (PVT == MVT::i64) {
8501     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8502             .addImm(LabelOffset)
8503             .addReg(BufReg);
8504   } else {
8505     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8506             .addImm(LabelOffset)
8507             .addReg(BufReg);
8508   }
8509   MIB.setMemRefs(MMOBegin, MMOEnd);
8510
8511   // Reload SP
8512   if (PVT == MVT::i64) {
8513     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8514             .addImm(SPOffset)
8515             .addReg(BufReg);
8516   } else {
8517     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8518             .addImm(SPOffset)
8519             .addReg(BufReg);
8520   }
8521   MIB.setMemRefs(MMOBegin, MMOEnd);
8522
8523   // Reload BP
8524   if (PVT == MVT::i64) {
8525     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8526             .addImm(BPOffset)
8527             .addReg(BufReg);
8528   } else {
8529     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8530             .addImm(BPOffset)
8531             .addReg(BufReg);
8532   }
8533   MIB.setMemRefs(MMOBegin, MMOEnd);
8534
8535   // Reload TOC
8536   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8537     setUsesTOCBasePtr(*MBB->getParent());
8538     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8539             .addImm(TOCOffset)
8540             .addReg(BufReg);
8541
8542     MIB.setMemRefs(MMOBegin, MMOEnd);
8543   }
8544
8545   // Jump
8546   BuildMI(*MBB, MI, DL,
8547           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8548   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8549
8550   MI->eraseFromParent();
8551   return MBB;
8552 }
8553
8554 MachineBasicBlock *
8555 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8556                                                MachineBasicBlock *BB) const {
8557   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8558       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8559     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8560         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8561       // Call lowering should have added an r2 operand to indicate a dependence
8562       // on the TOC base pointer value. It can't however, because there is no
8563       // way to mark the dependence as implicit there, and so the stackmap code
8564       // will confuse it with a regular operand. Instead, add the dependence
8565       // here.
8566       setUsesTOCBasePtr(*BB->getParent());
8567       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8568     }
8569
8570     return emitPatchPoint(MI, BB);
8571   }
8572
8573   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8574       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8575     return emitEHSjLjSetJmp(MI, BB);
8576   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8577              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8578     return emitEHSjLjLongJmp(MI, BB);
8579   }
8580
8581   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8582
8583   // To "insert" these instructions we actually have to insert their
8584   // control-flow patterns.
8585   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8586   MachineFunction::iterator It = BB;
8587   ++It;
8588
8589   MachineFunction *F = BB->getParent();
8590
8591   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8592                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8593                               MI->getOpcode() == PPC::SELECT_I4 ||
8594                               MI->getOpcode() == PPC::SELECT_I8)) {
8595     SmallVector<MachineOperand, 2> Cond;
8596     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8597         MI->getOpcode() == PPC::SELECT_CC_I8)
8598       Cond.push_back(MI->getOperand(4));
8599     else
8600       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8601     Cond.push_back(MI->getOperand(1));
8602
8603     DebugLoc dl = MI->getDebugLoc();
8604     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8605                       Cond, MI->getOperand(2).getReg(),
8606                       MI->getOperand(3).getReg());
8607   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8608              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8609              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8610              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8611              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8612              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8613              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8614              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8615              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8616              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8617              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8618              MI->getOpcode() == PPC::SELECT_I4 ||
8619              MI->getOpcode() == PPC::SELECT_I8 ||
8620              MI->getOpcode() == PPC::SELECT_F4 ||
8621              MI->getOpcode() == PPC::SELECT_F8 ||
8622              MI->getOpcode() == PPC::SELECT_QFRC ||
8623              MI->getOpcode() == PPC::SELECT_QSRC ||
8624              MI->getOpcode() == PPC::SELECT_QBRC ||
8625              MI->getOpcode() == PPC::SELECT_VRRC ||
8626              MI->getOpcode() == PPC::SELECT_VSFRC ||
8627              MI->getOpcode() == PPC::SELECT_VSSRC ||
8628              MI->getOpcode() == PPC::SELECT_VSRC) {
8629     // The incoming instruction knows the destination vreg to set, the
8630     // condition code register to branch on, the true/false values to
8631     // select between, and a branch opcode to use.
8632
8633     //  thisMBB:
8634     //  ...
8635     //   TrueVal = ...
8636     //   cmpTY ccX, r1, r2
8637     //   bCC copy1MBB
8638     //   fallthrough --> copy0MBB
8639     MachineBasicBlock *thisMBB = BB;
8640     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8641     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8642     DebugLoc dl = MI->getDebugLoc();
8643     F->insert(It, copy0MBB);
8644     F->insert(It, sinkMBB);
8645
8646     // Transfer the remainder of BB and its successor edges to sinkMBB.
8647     sinkMBB->splice(sinkMBB->begin(), BB,
8648                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8649     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8650
8651     // Next, add the true and fallthrough blocks as its successors.
8652     BB->addSuccessor(copy0MBB);
8653     BB->addSuccessor(sinkMBB);
8654
8655     if (MI->getOpcode() == PPC::SELECT_I4 ||
8656         MI->getOpcode() == PPC::SELECT_I8 ||
8657         MI->getOpcode() == PPC::SELECT_F4 ||
8658         MI->getOpcode() == PPC::SELECT_F8 ||
8659         MI->getOpcode() == PPC::SELECT_QFRC ||
8660         MI->getOpcode() == PPC::SELECT_QSRC ||
8661         MI->getOpcode() == PPC::SELECT_QBRC ||
8662         MI->getOpcode() == PPC::SELECT_VRRC ||
8663         MI->getOpcode() == PPC::SELECT_VSFRC ||
8664         MI->getOpcode() == PPC::SELECT_VSSRC ||
8665         MI->getOpcode() == PPC::SELECT_VSRC) {
8666       BuildMI(BB, dl, TII->get(PPC::BC))
8667         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8668     } else {
8669       unsigned SelectPred = MI->getOperand(4).getImm();
8670       BuildMI(BB, dl, TII->get(PPC::BCC))
8671         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8672     }
8673
8674     //  copy0MBB:
8675     //   %FalseValue = ...
8676     //   # fallthrough to sinkMBB
8677     BB = copy0MBB;
8678
8679     // Update machine-CFG edges
8680     BB->addSuccessor(sinkMBB);
8681
8682     //  sinkMBB:
8683     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8684     //  ...
8685     BB = sinkMBB;
8686     BuildMI(*BB, BB->begin(), dl,
8687             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8688       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8689       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8690   } else if (MI->getOpcode() == PPC::ReadTB) {
8691     // To read the 64-bit time-base register on a 32-bit target, we read the
8692     // two halves. Should the counter have wrapped while it was being read, we
8693     // need to try again.
8694     // ...
8695     // readLoop:
8696     // mfspr Rx,TBU # load from TBU
8697     // mfspr Ry,TB  # load from TB
8698     // mfspr Rz,TBU # load from TBU
8699     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8700     // bne readLoop   # branch if they're not equal
8701     // ...
8702
8703     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8704     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8705     DebugLoc dl = MI->getDebugLoc();
8706     F->insert(It, readMBB);
8707     F->insert(It, sinkMBB);
8708
8709     // Transfer the remainder of BB and its successor edges to sinkMBB.
8710     sinkMBB->splice(sinkMBB->begin(), BB,
8711                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8712     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8713
8714     BB->addSuccessor(readMBB);
8715     BB = readMBB;
8716
8717     MachineRegisterInfo &RegInfo = F->getRegInfo();
8718     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8719     unsigned LoReg = MI->getOperand(0).getReg();
8720     unsigned HiReg = MI->getOperand(1).getReg();
8721
8722     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8723     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8724     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8725
8726     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8727
8728     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8729       .addReg(HiReg).addReg(ReadAgainReg);
8730     BuildMI(BB, dl, TII->get(PPC::BCC))
8731       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8732
8733     BB->addSuccessor(readMBB);
8734     BB->addSuccessor(sinkMBB);
8735   }
8736   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8737     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8738   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8739     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8740   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8741     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8742   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8743     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8744
8745   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8746     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8747   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8748     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8749   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8750     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8751   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8752     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8753
8754   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8755     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8756   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8757     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8758   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8759     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8760   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8761     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8762
8763   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8764     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8765   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8766     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8767   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8768     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8769   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8770     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8771
8772   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8773     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8774   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8775     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8776   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8777     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8778   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8779     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8780
8781   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8782     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8783   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8784     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8785   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8786     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8787   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8788     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8789
8790   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8791     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8792   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8793     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8794   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8795     BB = EmitAtomicBinary(MI, BB, 4, 0);
8796   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8797     BB = EmitAtomicBinary(MI, BB, 8, 0);
8798
8799   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8800            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8801            (Subtarget.hasPartwordAtomics() &&
8802             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8803            (Subtarget.hasPartwordAtomics() &&
8804             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8805     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8806
8807     auto LoadMnemonic = PPC::LDARX;
8808     auto StoreMnemonic = PPC::STDCX;
8809     switch(MI->getOpcode()) {
8810     default:
8811       llvm_unreachable("Compare and swap of unknown size");
8812     case PPC::ATOMIC_CMP_SWAP_I8:
8813       LoadMnemonic = PPC::LBARX;
8814       StoreMnemonic = PPC::STBCX;
8815       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8816       break;
8817     case PPC::ATOMIC_CMP_SWAP_I16:
8818       LoadMnemonic = PPC::LHARX;
8819       StoreMnemonic = PPC::STHCX;
8820       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8821       break;
8822     case PPC::ATOMIC_CMP_SWAP_I32:
8823       LoadMnemonic = PPC::LWARX;
8824       StoreMnemonic = PPC::STWCX;
8825       break;
8826     case PPC::ATOMIC_CMP_SWAP_I64:
8827       LoadMnemonic = PPC::LDARX;
8828       StoreMnemonic = PPC::STDCX;
8829       break;
8830     }
8831     unsigned dest   = MI->getOperand(0).getReg();
8832     unsigned ptrA   = MI->getOperand(1).getReg();
8833     unsigned ptrB   = MI->getOperand(2).getReg();
8834     unsigned oldval = MI->getOperand(3).getReg();
8835     unsigned newval = MI->getOperand(4).getReg();
8836     DebugLoc dl     = MI->getDebugLoc();
8837
8838     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8839     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8840     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8841     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8842     F->insert(It, loop1MBB);
8843     F->insert(It, loop2MBB);
8844     F->insert(It, midMBB);
8845     F->insert(It, exitMBB);
8846     exitMBB->splice(exitMBB->begin(), BB,
8847                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8848     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8849
8850     //  thisMBB:
8851     //   ...
8852     //   fallthrough --> loopMBB
8853     BB->addSuccessor(loop1MBB);
8854
8855     // loop1MBB:
8856     //   l[bhwd]arx dest, ptr
8857     //   cmp[wd] dest, oldval
8858     //   bne- midMBB
8859     // loop2MBB:
8860     //   st[bhwd]cx. newval, ptr
8861     //   bne- loopMBB
8862     //   b exitBB
8863     // midMBB:
8864     //   st[bhwd]cx. dest, ptr
8865     // exitBB:
8866     BB = loop1MBB;
8867     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8868       .addReg(ptrA).addReg(ptrB);
8869     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8870       .addReg(oldval).addReg(dest);
8871     BuildMI(BB, dl, TII->get(PPC::BCC))
8872       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8873     BB->addSuccessor(loop2MBB);
8874     BB->addSuccessor(midMBB);
8875
8876     BB = loop2MBB;
8877     BuildMI(BB, dl, TII->get(StoreMnemonic))
8878       .addReg(newval).addReg(ptrA).addReg(ptrB);
8879     BuildMI(BB, dl, TII->get(PPC::BCC))
8880       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8881     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8882     BB->addSuccessor(loop1MBB);
8883     BB->addSuccessor(exitMBB);
8884
8885     BB = midMBB;
8886     BuildMI(BB, dl, TII->get(StoreMnemonic))
8887       .addReg(dest).addReg(ptrA).addReg(ptrB);
8888     BB->addSuccessor(exitMBB);
8889
8890     //  exitMBB:
8891     //   ...
8892     BB = exitMBB;
8893   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8894              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8895     // We must use 64-bit registers for addresses when targeting 64-bit,
8896     // since we're actually doing arithmetic on them.  Other registers
8897     // can be 32-bit.
8898     bool is64bit = Subtarget.isPPC64();
8899     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8900
8901     unsigned dest   = MI->getOperand(0).getReg();
8902     unsigned ptrA   = MI->getOperand(1).getReg();
8903     unsigned ptrB   = MI->getOperand(2).getReg();
8904     unsigned oldval = MI->getOperand(3).getReg();
8905     unsigned newval = MI->getOperand(4).getReg();
8906     DebugLoc dl     = MI->getDebugLoc();
8907
8908     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8909     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8910     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8911     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8912     F->insert(It, loop1MBB);
8913     F->insert(It, loop2MBB);
8914     F->insert(It, midMBB);
8915     F->insert(It, exitMBB);
8916     exitMBB->splice(exitMBB->begin(), BB,
8917                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8918     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8919
8920     MachineRegisterInfo &RegInfo = F->getRegInfo();
8921     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8922                                             : &PPC::GPRCRegClass;
8923     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8924     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8925     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8926     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8927     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8928     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8929     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8930     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8931     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8932     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8933     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8934     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8935     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8936     unsigned Ptr1Reg;
8937     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8938     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8939     //  thisMBB:
8940     //   ...
8941     //   fallthrough --> loopMBB
8942     BB->addSuccessor(loop1MBB);
8943
8944     // The 4-byte load must be aligned, while a char or short may be
8945     // anywhere in the word.  Hence all this nasty bookkeeping code.
8946     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8947     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8948     //   xori shift, shift1, 24 [16]
8949     //   rlwinm ptr, ptr1, 0, 0, 29
8950     //   slw newval2, newval, shift
8951     //   slw oldval2, oldval,shift
8952     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8953     //   slw mask, mask2, shift
8954     //   and newval3, newval2, mask
8955     //   and oldval3, oldval2, mask
8956     // loop1MBB:
8957     //   lwarx tmpDest, ptr
8958     //   and tmp, tmpDest, mask
8959     //   cmpw tmp, oldval3
8960     //   bne- midMBB
8961     // loop2MBB:
8962     //   andc tmp2, tmpDest, mask
8963     //   or tmp4, tmp2, newval3
8964     //   stwcx. tmp4, ptr
8965     //   bne- loop1MBB
8966     //   b exitBB
8967     // midMBB:
8968     //   stwcx. tmpDest, ptr
8969     // exitBB:
8970     //   srw dest, tmpDest, shift
8971     if (ptrA != ZeroReg) {
8972       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8973       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8974         .addReg(ptrA).addReg(ptrB);
8975     } else {
8976       Ptr1Reg = ptrB;
8977     }
8978     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8979         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8980     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8981         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8982     if (is64bit)
8983       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8984         .addReg(Ptr1Reg).addImm(0).addImm(61);
8985     else
8986       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8987         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8988     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8989         .addReg(newval).addReg(ShiftReg);
8990     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8991         .addReg(oldval).addReg(ShiftReg);
8992     if (is8bit)
8993       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8994     else {
8995       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8996       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8997         .addReg(Mask3Reg).addImm(65535);
8998     }
8999     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9000         .addReg(Mask2Reg).addReg(ShiftReg);
9001     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9002         .addReg(NewVal2Reg).addReg(MaskReg);
9003     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9004         .addReg(OldVal2Reg).addReg(MaskReg);
9005
9006     BB = loop1MBB;
9007     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9008         .addReg(ZeroReg).addReg(PtrReg);
9009     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9010         .addReg(TmpDestReg).addReg(MaskReg);
9011     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9012         .addReg(TmpReg).addReg(OldVal3Reg);
9013     BuildMI(BB, dl, TII->get(PPC::BCC))
9014         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9015     BB->addSuccessor(loop2MBB);
9016     BB->addSuccessor(midMBB);
9017
9018     BB = loop2MBB;
9019     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9020         .addReg(TmpDestReg).addReg(MaskReg);
9021     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9022         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9023     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9024         .addReg(ZeroReg).addReg(PtrReg);
9025     BuildMI(BB, dl, TII->get(PPC::BCC))
9026       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9027     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9028     BB->addSuccessor(loop1MBB);
9029     BB->addSuccessor(exitMBB);
9030
9031     BB = midMBB;
9032     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9033       .addReg(ZeroReg).addReg(PtrReg);
9034     BB->addSuccessor(exitMBB);
9035
9036     //  exitMBB:
9037     //   ...
9038     BB = exitMBB;
9039     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9040       .addReg(ShiftReg);
9041   } else if (MI->getOpcode() == PPC::FADDrtz) {
9042     // This pseudo performs an FADD with rounding mode temporarily forced
9043     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9044     // is not modeled at the SelectionDAG level.
9045     unsigned Dest = MI->getOperand(0).getReg();
9046     unsigned Src1 = MI->getOperand(1).getReg();
9047     unsigned Src2 = MI->getOperand(2).getReg();
9048     DebugLoc dl   = MI->getDebugLoc();
9049
9050     MachineRegisterInfo &RegInfo = F->getRegInfo();
9051     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9052
9053     // Save FPSCR value.
9054     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9055
9056     // Set rounding mode to round-to-zero.
9057     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9058     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9059
9060     // Perform addition.
9061     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9062
9063     // Restore FPSCR value.
9064     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9065   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9066              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
9067              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9068              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9069     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9070                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
9071                       PPC::ANDIo8 : PPC::ANDIo;
9072     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9073                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9074
9075     MachineRegisterInfo &RegInfo = F->getRegInfo();
9076     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9077                                                   &PPC::GPRCRegClass :
9078                                                   &PPC::G8RCRegClass);
9079
9080     DebugLoc dl   = MI->getDebugLoc();
9081     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9082       .addReg(MI->getOperand(1).getReg()).addImm(1);
9083     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9084             MI->getOperand(0).getReg())
9085       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9086   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
9087     DebugLoc Dl = MI->getDebugLoc();
9088     MachineRegisterInfo &RegInfo = F->getRegInfo();
9089     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9090     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9091     return BB;
9092   } else {
9093     llvm_unreachable("Unexpected instr type to insert");
9094   }
9095
9096   MI->eraseFromParent();   // The pseudo instruction is gone now.
9097   return BB;
9098 }
9099
9100 //===----------------------------------------------------------------------===//
9101 // Target Optimization Hooks
9102 //===----------------------------------------------------------------------===//
9103
9104 static std::string getRecipOp(const char *Base, EVT VT) {
9105   std::string RecipOp(Base);
9106   if (VT.getScalarType() == MVT::f64)
9107     RecipOp += "d";
9108   else
9109     RecipOp += "f";
9110
9111   if (VT.isVector())
9112     RecipOp = "vec-" + RecipOp;
9113
9114   return RecipOp;
9115 }
9116
9117 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9118                                             DAGCombinerInfo &DCI,
9119                                             unsigned &RefinementSteps,
9120                                             bool &UseOneConstNR) const {
9121   EVT VT = Operand.getValueType();
9122   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9123       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9124       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9125       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9126       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9127       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9128     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9129     std::string RecipOp = getRecipOp("sqrt", VT);
9130     if (!Recips.isEnabled(RecipOp))
9131       return SDValue();
9132
9133     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9134     UseOneConstNR = true;
9135     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9136   }
9137   return SDValue();
9138 }
9139
9140 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9141                                             DAGCombinerInfo &DCI,
9142                                             unsigned &RefinementSteps) const {
9143   EVT VT = Operand.getValueType();
9144   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9145       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9146       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9147       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9148       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9149       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9150     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9151     std::string RecipOp = getRecipOp("div", VT);
9152     if (!Recips.isEnabled(RecipOp))
9153       return SDValue();
9154
9155     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9156     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9157   }
9158   return SDValue();
9159 }
9160
9161 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9162   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9163   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9164   // enabled for division), this functionality is redundant with the default
9165   // combiner logic (once the division -> reciprocal/multiply transformation
9166   // has taken place). As a result, this matters more for older cores than for
9167   // newer ones.
9168
9169   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9170   // reciprocal if there are two or more FDIVs (for embedded cores with only
9171   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9172   switch (Subtarget.getDarwinDirective()) {
9173   default:
9174     return 3;
9175   case PPC::DIR_440:
9176   case PPC::DIR_A2:
9177   case PPC::DIR_E500mc:
9178   case PPC::DIR_E5500:
9179     return 2;
9180   }
9181 }
9182
9183 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9184                             unsigned Bytes, int Dist,
9185                             SelectionDAG &DAG) {
9186   if (VT.getSizeInBits() / 8 != Bytes)
9187     return false;
9188
9189   SDValue BaseLoc = Base->getBasePtr();
9190   if (Loc.getOpcode() == ISD::FrameIndex) {
9191     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9192       return false;
9193     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9194     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9195     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9196     int FS  = MFI->getObjectSize(FI);
9197     int BFS = MFI->getObjectSize(BFI);
9198     if (FS != BFS || FS != (int)Bytes) return false;
9199     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9200   }
9201
9202   // Handle X+C
9203   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
9204       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
9205     return true;
9206
9207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9208   const GlobalValue *GV1 = nullptr;
9209   const GlobalValue *GV2 = nullptr;
9210   int64_t Offset1 = 0;
9211   int64_t Offset2 = 0;
9212   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9213   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9214   if (isGA1 && isGA2 && GV1 == GV2)
9215     return Offset1 == (Offset2 + Dist*Bytes);
9216   return false;
9217 }
9218
9219 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9220 // not enforce equality of the chain operands.
9221 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9222                             unsigned Bytes, int Dist,
9223                             SelectionDAG &DAG) {
9224   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9225     EVT VT = LS->getMemoryVT();
9226     SDValue Loc = LS->getBasePtr();
9227     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9228   }
9229
9230   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9231     EVT VT;
9232     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9233     default: return false;
9234     case Intrinsic::ppc_qpx_qvlfd:
9235     case Intrinsic::ppc_qpx_qvlfda:
9236       VT = MVT::v4f64;
9237       break;
9238     case Intrinsic::ppc_qpx_qvlfs:
9239     case Intrinsic::ppc_qpx_qvlfsa:
9240       VT = MVT::v4f32;
9241       break;
9242     case Intrinsic::ppc_qpx_qvlfcd:
9243     case Intrinsic::ppc_qpx_qvlfcda:
9244       VT = MVT::v2f64;
9245       break;
9246     case Intrinsic::ppc_qpx_qvlfcs:
9247     case Intrinsic::ppc_qpx_qvlfcsa:
9248       VT = MVT::v2f32;
9249       break;
9250     case Intrinsic::ppc_qpx_qvlfiwa:
9251     case Intrinsic::ppc_qpx_qvlfiwz:
9252     case Intrinsic::ppc_altivec_lvx:
9253     case Intrinsic::ppc_altivec_lvxl:
9254     case Intrinsic::ppc_vsx_lxvw4x:
9255       VT = MVT::v4i32;
9256       break;
9257     case Intrinsic::ppc_vsx_lxvd2x:
9258       VT = MVT::v2f64;
9259       break;
9260     case Intrinsic::ppc_altivec_lvebx:
9261       VT = MVT::i8;
9262       break;
9263     case Intrinsic::ppc_altivec_lvehx:
9264       VT = MVT::i16;
9265       break;
9266     case Intrinsic::ppc_altivec_lvewx:
9267       VT = MVT::i32;
9268       break;
9269     }
9270
9271     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9272   }
9273
9274   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9275     EVT VT;
9276     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9277     default: return false;
9278     case Intrinsic::ppc_qpx_qvstfd:
9279     case Intrinsic::ppc_qpx_qvstfda:
9280       VT = MVT::v4f64;
9281       break;
9282     case Intrinsic::ppc_qpx_qvstfs:
9283     case Intrinsic::ppc_qpx_qvstfsa:
9284       VT = MVT::v4f32;
9285       break;
9286     case Intrinsic::ppc_qpx_qvstfcd:
9287     case Intrinsic::ppc_qpx_qvstfcda:
9288       VT = MVT::v2f64;
9289       break;
9290     case Intrinsic::ppc_qpx_qvstfcs:
9291     case Intrinsic::ppc_qpx_qvstfcsa:
9292       VT = MVT::v2f32;
9293       break;
9294     case Intrinsic::ppc_qpx_qvstfiw:
9295     case Intrinsic::ppc_qpx_qvstfiwa:
9296     case Intrinsic::ppc_altivec_stvx:
9297     case Intrinsic::ppc_altivec_stvxl:
9298     case Intrinsic::ppc_vsx_stxvw4x:
9299       VT = MVT::v4i32;
9300       break;
9301     case Intrinsic::ppc_vsx_stxvd2x:
9302       VT = MVT::v2f64;
9303       break;
9304     case Intrinsic::ppc_altivec_stvebx:
9305       VT = MVT::i8;
9306       break;
9307     case Intrinsic::ppc_altivec_stvehx:
9308       VT = MVT::i16;
9309       break;
9310     case Intrinsic::ppc_altivec_stvewx:
9311       VT = MVT::i32;
9312       break;
9313     }
9314
9315     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9316   }
9317
9318   return false;
9319 }
9320
9321 // Return true is there is a nearyby consecutive load to the one provided
9322 // (regardless of alignment). We search up and down the chain, looking though
9323 // token factors and other loads (but nothing else). As a result, a true result
9324 // indicates that it is safe to create a new consecutive load adjacent to the
9325 // load provided.
9326 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9327   SDValue Chain = LD->getChain();
9328   EVT VT = LD->getMemoryVT();
9329
9330   SmallSet<SDNode *, 16> LoadRoots;
9331   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9332   SmallSet<SDNode *, 16> Visited;
9333
9334   // First, search up the chain, branching to follow all token-factor operands.
9335   // If we find a consecutive load, then we're done, otherwise, record all
9336   // nodes just above the top-level loads and token factors.
9337   while (!Queue.empty()) {
9338     SDNode *ChainNext = Queue.pop_back_val();
9339     if (!Visited.insert(ChainNext).second)
9340       continue;
9341
9342     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9343       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9344         return true;
9345
9346       if (!Visited.count(ChainLD->getChain().getNode()))
9347         Queue.push_back(ChainLD->getChain().getNode());
9348     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9349       for (const SDUse &O : ChainNext->ops())
9350         if (!Visited.count(O.getNode()))
9351           Queue.push_back(O.getNode());
9352     } else
9353       LoadRoots.insert(ChainNext);
9354   }
9355
9356   // Second, search down the chain, starting from the top-level nodes recorded
9357   // in the first phase. These top-level nodes are the nodes just above all
9358   // loads and token factors. Starting with their uses, recursively look though
9359   // all loads (just the chain uses) and token factors to find a consecutive
9360   // load.
9361   Visited.clear();
9362   Queue.clear();
9363
9364   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9365        IE = LoadRoots.end(); I != IE; ++I) {
9366     Queue.push_back(*I);
9367        
9368     while (!Queue.empty()) {
9369       SDNode *LoadRoot = Queue.pop_back_val();
9370       if (!Visited.insert(LoadRoot).second)
9371         continue;
9372
9373       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9374         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9375           return true;
9376
9377       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9378            UE = LoadRoot->use_end(); UI != UE; ++UI)
9379         if (((isa<MemSDNode>(*UI) &&
9380             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9381             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9382           Queue.push_back(*UI);
9383     }
9384   }
9385
9386   return false;
9387 }
9388
9389 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9390                                                   DAGCombinerInfo &DCI) const {
9391   SelectionDAG &DAG = DCI.DAG;
9392   SDLoc dl(N);
9393
9394   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9395   // If we're tracking CR bits, we need to be careful that we don't have:
9396   //   trunc(binary-ops(zext(x), zext(y)))
9397   // or
9398   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9399   // such that we're unnecessarily moving things into GPRs when it would be
9400   // better to keep them in CR bits.
9401
9402   // Note that trunc here can be an actual i1 trunc, or can be the effective
9403   // truncation that comes from a setcc or select_cc.
9404   if (N->getOpcode() == ISD::TRUNCATE &&
9405       N->getValueType(0) != MVT::i1)
9406     return SDValue();
9407
9408   if (N->getOperand(0).getValueType() != MVT::i32 &&
9409       N->getOperand(0).getValueType() != MVT::i64)
9410     return SDValue();
9411
9412   if (N->getOpcode() == ISD::SETCC ||
9413       N->getOpcode() == ISD::SELECT_CC) {
9414     // If we're looking at a comparison, then we need to make sure that the
9415     // high bits (all except for the first) don't matter the result.
9416     ISD::CondCode CC =
9417       cast<CondCodeSDNode>(N->getOperand(
9418         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9419     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9420
9421     if (ISD::isSignedIntSetCC(CC)) {
9422       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9423           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9424         return SDValue();
9425     } else if (ISD::isUnsignedIntSetCC(CC)) {
9426       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9427                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9428           !DAG.MaskedValueIsZero(N->getOperand(1),
9429                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9430         return SDValue();
9431     } else {
9432       // This is neither a signed nor an unsigned comparison, just make sure
9433       // that the high bits are equal.
9434       APInt Op1Zero, Op1One;
9435       APInt Op2Zero, Op2One;
9436       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9437       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9438
9439       // We don't really care about what is known about the first bit (if
9440       // anything), so clear it in all masks prior to comparing them.
9441       Op1Zero.clearBit(0); Op1One.clearBit(0);
9442       Op2Zero.clearBit(0); Op2One.clearBit(0);
9443
9444       if (Op1Zero != Op2Zero || Op1One != Op2One)
9445         return SDValue();
9446     }
9447   }
9448
9449   // We now know that the higher-order bits are irrelevant, we just need to
9450   // make sure that all of the intermediate operations are bit operations, and
9451   // all inputs are extensions.
9452   if (N->getOperand(0).getOpcode() != ISD::AND &&
9453       N->getOperand(0).getOpcode() != ISD::OR  &&
9454       N->getOperand(0).getOpcode() != ISD::XOR &&
9455       N->getOperand(0).getOpcode() != ISD::SELECT &&
9456       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9457       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9458       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9459       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9460       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9461     return SDValue();
9462
9463   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9464       N->getOperand(1).getOpcode() != ISD::AND &&
9465       N->getOperand(1).getOpcode() != ISD::OR  &&
9466       N->getOperand(1).getOpcode() != ISD::XOR &&
9467       N->getOperand(1).getOpcode() != ISD::SELECT &&
9468       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9469       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9470       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9471       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9472       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9473     return SDValue();
9474
9475   SmallVector<SDValue, 4> Inputs;
9476   SmallVector<SDValue, 8> BinOps, PromOps;
9477   SmallPtrSet<SDNode *, 16> Visited;
9478
9479   for (unsigned i = 0; i < 2; ++i) {
9480     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9481           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9482           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9483           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9484         isa<ConstantSDNode>(N->getOperand(i)))
9485       Inputs.push_back(N->getOperand(i));
9486     else
9487       BinOps.push_back(N->getOperand(i));
9488
9489     if (N->getOpcode() == ISD::TRUNCATE)
9490       break;
9491   }
9492
9493   // Visit all inputs, collect all binary operations (and, or, xor and
9494   // select) that are all fed by extensions. 
9495   while (!BinOps.empty()) {
9496     SDValue BinOp = BinOps.back();
9497     BinOps.pop_back();
9498
9499     if (!Visited.insert(BinOp.getNode()).second)
9500       continue;
9501
9502     PromOps.push_back(BinOp);
9503
9504     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9505       // The condition of the select is not promoted.
9506       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9507         continue;
9508       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9509         continue;
9510
9511       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9512             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9513             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9514            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9515           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9516         Inputs.push_back(BinOp.getOperand(i)); 
9517       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9518                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9519                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9520                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9521                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9522                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9523                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9524                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9525                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9526         BinOps.push_back(BinOp.getOperand(i));
9527       } else {
9528         // We have an input that is not an extension or another binary
9529         // operation; we'll abort this transformation.
9530         return SDValue();
9531       }
9532     }
9533   }
9534
9535   // Make sure that this is a self-contained cluster of operations (which
9536   // is not quite the same thing as saying that everything has only one
9537   // use).
9538   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9539     if (isa<ConstantSDNode>(Inputs[i]))
9540       continue;
9541
9542     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9543                               UE = Inputs[i].getNode()->use_end();
9544          UI != UE; ++UI) {
9545       SDNode *User = *UI;
9546       if (User != N && !Visited.count(User))
9547         return SDValue();
9548
9549       // Make sure that we're not going to promote the non-output-value
9550       // operand(s) or SELECT or SELECT_CC.
9551       // FIXME: Although we could sometimes handle this, and it does occur in
9552       // practice that one of the condition inputs to the select is also one of
9553       // the outputs, we currently can't deal with this.
9554       if (User->getOpcode() == ISD::SELECT) {
9555         if (User->getOperand(0) == Inputs[i])
9556           return SDValue();
9557       } else if (User->getOpcode() == ISD::SELECT_CC) {
9558         if (User->getOperand(0) == Inputs[i] ||
9559             User->getOperand(1) == Inputs[i])
9560           return SDValue();
9561       }
9562     }
9563   }
9564
9565   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9566     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9567                               UE = PromOps[i].getNode()->use_end();
9568          UI != UE; ++UI) {
9569       SDNode *User = *UI;
9570       if (User != N && !Visited.count(User))
9571         return SDValue();
9572
9573       // Make sure that we're not going to promote the non-output-value
9574       // operand(s) or SELECT or SELECT_CC.
9575       // FIXME: Although we could sometimes handle this, and it does occur in
9576       // practice that one of the condition inputs to the select is also one of
9577       // the outputs, we currently can't deal with this.
9578       if (User->getOpcode() == ISD::SELECT) {
9579         if (User->getOperand(0) == PromOps[i])
9580           return SDValue();
9581       } else if (User->getOpcode() == ISD::SELECT_CC) {
9582         if (User->getOperand(0) == PromOps[i] ||
9583             User->getOperand(1) == PromOps[i])
9584           return SDValue();
9585       }
9586     }
9587   }
9588
9589   // Replace all inputs with the extension operand.
9590   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9591     // Constants may have users outside the cluster of to-be-promoted nodes,
9592     // and so we need to replace those as we do the promotions.
9593     if (isa<ConstantSDNode>(Inputs[i]))
9594       continue;
9595     else
9596       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9597   }
9598
9599   // Replace all operations (these are all the same, but have a different
9600   // (i1) return type). DAG.getNode will validate that the types of
9601   // a binary operator match, so go through the list in reverse so that
9602   // we've likely promoted both operands first. Any intermediate truncations or
9603   // extensions disappear.
9604   while (!PromOps.empty()) {
9605     SDValue PromOp = PromOps.back();
9606     PromOps.pop_back();
9607
9608     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9609         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9610         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9611         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9612       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9613           PromOp.getOperand(0).getValueType() != MVT::i1) {
9614         // The operand is not yet ready (see comment below).
9615         PromOps.insert(PromOps.begin(), PromOp);
9616         continue;
9617       }
9618
9619       SDValue RepValue = PromOp.getOperand(0);
9620       if (isa<ConstantSDNode>(RepValue))
9621         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9622
9623       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9624       continue;
9625     }
9626
9627     unsigned C;
9628     switch (PromOp.getOpcode()) {
9629     default:             C = 0; break;
9630     case ISD::SELECT:    C = 1; break;
9631     case ISD::SELECT_CC: C = 2; break;
9632     }
9633
9634     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9635          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9636         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9637          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9638       // The to-be-promoted operands of this node have not yet been
9639       // promoted (this should be rare because we're going through the
9640       // list backward, but if one of the operands has several users in
9641       // this cluster of to-be-promoted nodes, it is possible).
9642       PromOps.insert(PromOps.begin(), PromOp);
9643       continue;
9644     }
9645
9646     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9647                                 PromOp.getNode()->op_end());
9648
9649     // If there are any constant inputs, make sure they're replaced now.
9650     for (unsigned i = 0; i < 2; ++i)
9651       if (isa<ConstantSDNode>(Ops[C+i]))
9652         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9653
9654     DAG.ReplaceAllUsesOfValueWith(PromOp,
9655       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9656   }
9657
9658   // Now we're left with the initial truncation itself.
9659   if (N->getOpcode() == ISD::TRUNCATE)
9660     return N->getOperand(0);
9661
9662   // Otherwise, this is a comparison. The operands to be compared have just
9663   // changed type (to i1), but everything else is the same.
9664   return SDValue(N, 0);
9665 }
9666
9667 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9668                                                   DAGCombinerInfo &DCI) const {
9669   SelectionDAG &DAG = DCI.DAG;
9670   SDLoc dl(N);
9671
9672   // If we're tracking CR bits, we need to be careful that we don't have:
9673   //   zext(binary-ops(trunc(x), trunc(y)))
9674   // or
9675   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9676   // such that we're unnecessarily moving things into CR bits that can more
9677   // efficiently stay in GPRs. Note that if we're not certain that the high
9678   // bits are set as required by the final extension, we still may need to do
9679   // some masking to get the proper behavior.
9680
9681   // This same functionality is important on PPC64 when dealing with
9682   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9683   // the return values of functions. Because it is so similar, it is handled
9684   // here as well.
9685
9686   if (N->getValueType(0) != MVT::i32 &&
9687       N->getValueType(0) != MVT::i64)
9688     return SDValue();
9689
9690   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9691         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9692     return SDValue();
9693
9694   if (N->getOperand(0).getOpcode() != ISD::AND &&
9695       N->getOperand(0).getOpcode() != ISD::OR  &&
9696       N->getOperand(0).getOpcode() != ISD::XOR &&
9697       N->getOperand(0).getOpcode() != ISD::SELECT &&
9698       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9699     return SDValue();
9700
9701   SmallVector<SDValue, 4> Inputs;
9702   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9703   SmallPtrSet<SDNode *, 16> Visited;
9704
9705   // Visit all inputs, collect all binary operations (and, or, xor and
9706   // select) that are all fed by truncations. 
9707   while (!BinOps.empty()) {
9708     SDValue BinOp = BinOps.back();
9709     BinOps.pop_back();
9710
9711     if (!Visited.insert(BinOp.getNode()).second)
9712       continue;
9713
9714     PromOps.push_back(BinOp);
9715
9716     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9717       // The condition of the select is not promoted.
9718       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9719         continue;
9720       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9721         continue;
9722
9723       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9724           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9725         Inputs.push_back(BinOp.getOperand(i)); 
9726       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9727                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9728                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9729                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9730                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9731         BinOps.push_back(BinOp.getOperand(i));
9732       } else {
9733         // We have an input that is not a truncation or another binary
9734         // operation; we'll abort this transformation.
9735         return SDValue();
9736       }
9737     }
9738   }
9739
9740   // The operands of a select that must be truncated when the select is
9741   // promoted because the operand is actually part of the to-be-promoted set.
9742   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9743
9744   // Make sure that this is a self-contained cluster of operations (which
9745   // is not quite the same thing as saying that everything has only one
9746   // use).
9747   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9748     if (isa<ConstantSDNode>(Inputs[i]))
9749       continue;
9750
9751     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9752                               UE = Inputs[i].getNode()->use_end();
9753          UI != UE; ++UI) {
9754       SDNode *User = *UI;
9755       if (User != N && !Visited.count(User))
9756         return SDValue();
9757
9758       // If we're going to promote the non-output-value operand(s) or SELECT or
9759       // SELECT_CC, record them for truncation.
9760       if (User->getOpcode() == ISD::SELECT) {
9761         if (User->getOperand(0) == Inputs[i])
9762           SelectTruncOp[0].insert(std::make_pair(User,
9763                                     User->getOperand(0).getValueType()));
9764       } else if (User->getOpcode() == ISD::SELECT_CC) {
9765         if (User->getOperand(0) == Inputs[i])
9766           SelectTruncOp[0].insert(std::make_pair(User,
9767                                     User->getOperand(0).getValueType()));
9768         if (User->getOperand(1) == Inputs[i])
9769           SelectTruncOp[1].insert(std::make_pair(User,
9770                                     User->getOperand(1).getValueType()));
9771       }
9772     }
9773   }
9774
9775   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9776     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9777                               UE = PromOps[i].getNode()->use_end();
9778          UI != UE; ++UI) {
9779       SDNode *User = *UI;
9780       if (User != N && !Visited.count(User))
9781         return SDValue();
9782
9783       // If we're going to promote the non-output-value operand(s) or SELECT or
9784       // SELECT_CC, record them for truncation.
9785       if (User->getOpcode() == ISD::SELECT) {
9786         if (User->getOperand(0) == PromOps[i])
9787           SelectTruncOp[0].insert(std::make_pair(User,
9788                                     User->getOperand(0).getValueType()));
9789       } else if (User->getOpcode() == ISD::SELECT_CC) {
9790         if (User->getOperand(0) == PromOps[i])
9791           SelectTruncOp[0].insert(std::make_pair(User,
9792                                     User->getOperand(0).getValueType()));
9793         if (User->getOperand(1) == PromOps[i])
9794           SelectTruncOp[1].insert(std::make_pair(User,
9795                                     User->getOperand(1).getValueType()));
9796       }
9797     }
9798   }
9799
9800   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9801   bool ReallyNeedsExt = false;
9802   if (N->getOpcode() != ISD::ANY_EXTEND) {
9803     // If all of the inputs are not already sign/zero extended, then
9804     // we'll still need to do that at the end.
9805     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9806       if (isa<ConstantSDNode>(Inputs[i]))
9807         continue;
9808
9809       unsigned OpBits =
9810         Inputs[i].getOperand(0).getValueSizeInBits();
9811       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9812
9813       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9814            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9815                                   APInt::getHighBitsSet(OpBits,
9816                                                         OpBits-PromBits))) ||
9817           (N->getOpcode() == ISD::SIGN_EXTEND &&
9818            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9819              (OpBits-(PromBits-1)))) {
9820         ReallyNeedsExt = true;
9821         break;
9822       }
9823     }
9824   }
9825
9826   // Replace all inputs, either with the truncation operand, or a
9827   // truncation or extension to the final output type.
9828   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9829     // Constant inputs need to be replaced with the to-be-promoted nodes that
9830     // use them because they might have users outside of the cluster of
9831     // promoted nodes.
9832     if (isa<ConstantSDNode>(Inputs[i]))
9833       continue;
9834
9835     SDValue InSrc = Inputs[i].getOperand(0);
9836     if (Inputs[i].getValueType() == N->getValueType(0))
9837       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9838     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9839       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9840         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9841     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9842       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9843         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9844     else
9845       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9846         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9847   }
9848
9849   // Replace all operations (these are all the same, but have a different
9850   // (promoted) return type). DAG.getNode will validate that the types of
9851   // a binary operator match, so go through the list in reverse so that
9852   // we've likely promoted both operands first.
9853   while (!PromOps.empty()) {
9854     SDValue PromOp = PromOps.back();
9855     PromOps.pop_back();
9856
9857     unsigned C;
9858     switch (PromOp.getOpcode()) {
9859     default:             C = 0; break;
9860     case ISD::SELECT:    C = 1; break;
9861     case ISD::SELECT_CC: C = 2; break;
9862     }
9863
9864     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9865          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9866         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9867          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9868       // The to-be-promoted operands of this node have not yet been
9869       // promoted (this should be rare because we're going through the
9870       // list backward, but if one of the operands has several users in
9871       // this cluster of to-be-promoted nodes, it is possible).
9872       PromOps.insert(PromOps.begin(), PromOp);
9873       continue;
9874     }
9875
9876     // For SELECT and SELECT_CC nodes, we do a similar check for any
9877     // to-be-promoted comparison inputs.
9878     if (PromOp.getOpcode() == ISD::SELECT ||
9879         PromOp.getOpcode() == ISD::SELECT_CC) {
9880       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9881            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9882           (SelectTruncOp[1].count(PromOp.getNode()) &&
9883            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9884         PromOps.insert(PromOps.begin(), PromOp);
9885         continue;
9886       }
9887     }
9888
9889     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9890                                 PromOp.getNode()->op_end());
9891
9892     // If this node has constant inputs, then they'll need to be promoted here.
9893     for (unsigned i = 0; i < 2; ++i) {
9894       if (!isa<ConstantSDNode>(Ops[C+i]))
9895         continue;
9896       if (Ops[C+i].getValueType() == N->getValueType(0))
9897         continue;
9898
9899       if (N->getOpcode() == ISD::SIGN_EXTEND)
9900         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9901       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9902         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9903       else
9904         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9905     }
9906
9907     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9908     // truncate them again to the original value type.
9909     if (PromOp.getOpcode() == ISD::SELECT ||
9910         PromOp.getOpcode() == ISD::SELECT_CC) {
9911       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9912       if (SI0 != SelectTruncOp[0].end())
9913         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9914       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9915       if (SI1 != SelectTruncOp[1].end())
9916         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9917     }
9918
9919     DAG.ReplaceAllUsesOfValueWith(PromOp,
9920       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9921   }
9922
9923   // Now we're left with the initial extension itself.
9924   if (!ReallyNeedsExt)
9925     return N->getOperand(0);
9926
9927   // To zero extend, just mask off everything except for the first bit (in the
9928   // i1 case).
9929   if (N->getOpcode() == ISD::ZERO_EXTEND)
9930     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9931                        DAG.getConstant(APInt::getLowBitsSet(
9932                                          N->getValueSizeInBits(0), PromBits),
9933                                        dl, N->getValueType(0)));
9934
9935   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9936          "Invalid extension type");
9937   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
9938   SDValue ShiftCst =
9939     DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9940   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9941                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9942                                  N->getOperand(0), ShiftCst), ShiftCst);
9943 }
9944
9945 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9946                                               DAGCombinerInfo &DCI) const {
9947   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9948           N->getOpcode() == ISD::UINT_TO_FP) &&
9949          "Need an int -> FP conversion node here");
9950
9951   if (!Subtarget.has64BitSupport())
9952     return SDValue();
9953
9954   SelectionDAG &DAG = DCI.DAG;
9955   SDLoc dl(N);
9956   SDValue Op(N, 0);
9957
9958   // Don't handle ppc_fp128 here or i1 conversions.
9959   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9960     return SDValue();
9961   if (Op.getOperand(0).getValueType() == MVT::i1)
9962     return SDValue();
9963
9964   // For i32 intermediate values, unfortunately, the conversion functions
9965   // leave the upper 32 bits of the value are undefined. Within the set of
9966   // scalar instructions, we have no method for zero- or sign-extending the
9967   // value. Thus, we cannot handle i32 intermediate values here.
9968   if (Op.getOperand(0).getValueType() == MVT::i32)
9969     return SDValue();
9970
9971   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9972          "UINT_TO_FP is supported only with FPCVT");
9973
9974   // If we have FCFIDS, then use it when converting to single-precision.
9975   // Otherwise, convert to double-precision and then round.
9976   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9977                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9978                                                             : PPCISD::FCFIDS)
9979                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9980                                                             : PPCISD::FCFID);
9981   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9982                   ? MVT::f32
9983                   : MVT::f64;
9984
9985   // If we're converting from a float, to an int, and back to a float again,
9986   // then we don't need the store/load pair at all.
9987   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9988        Subtarget.hasFPCVT()) ||
9989       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9990     SDValue Src = Op.getOperand(0).getOperand(0);
9991     if (Src.getValueType() == MVT::f32) {
9992       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9993       DCI.AddToWorklist(Src.getNode());
9994     } else if (Src.getValueType() != MVT::f64) {
9995       // Make sure that we don't pick up a ppc_fp128 source value.
9996       return SDValue();
9997     }
9998
9999     unsigned FCTOp =
10000       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10001                                                         PPCISD::FCTIDUZ;
10002
10003     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10004     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10005
10006     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10007       FP = DAG.getNode(ISD::FP_ROUND, dl,
10008                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10009       DCI.AddToWorklist(FP.getNode());
10010     }
10011
10012     return FP;
10013   }
10014
10015   return SDValue();
10016 }
10017
10018 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10019 // builtins) into loads with swaps.
10020 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10021                                               DAGCombinerInfo &DCI) const {
10022   SelectionDAG &DAG = DCI.DAG;
10023   SDLoc dl(N);
10024   SDValue Chain;
10025   SDValue Base;
10026   MachineMemOperand *MMO;
10027
10028   switch (N->getOpcode()) {
10029   default:
10030     llvm_unreachable("Unexpected opcode for little endian VSX load");
10031   case ISD::LOAD: {
10032     LoadSDNode *LD = cast<LoadSDNode>(N);
10033     Chain = LD->getChain();
10034     Base = LD->getBasePtr();
10035     MMO = LD->getMemOperand();
10036     // If the MMO suggests this isn't a load of a full vector, leave
10037     // things alone.  For a built-in, we have to make the change for
10038     // correctness, so if there is a size problem that will be a bug.
10039     if (MMO->getSize() < 16)
10040       return SDValue();
10041     break;
10042   }
10043   case ISD::INTRINSIC_W_CHAIN: {
10044     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10045     Chain = Intrin->getChain();
10046     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10047     // us what we want. Get operand 2 instead.
10048     Base = Intrin->getOperand(2);
10049     MMO = Intrin->getMemOperand();
10050     break;
10051   }
10052   }
10053
10054   MVT VecTy = N->getValueType(0).getSimpleVT();
10055   SDValue LoadOps[] = { Chain, Base };
10056   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10057                                          DAG.getVTList(VecTy, MVT::Other),
10058                                          LoadOps, VecTy, MMO);
10059   DCI.AddToWorklist(Load.getNode());
10060   Chain = Load.getValue(1);
10061   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10062                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
10063   DCI.AddToWorklist(Swap.getNode());
10064   return Swap;
10065 }
10066
10067 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10068 // builtins) into stores with swaps.
10069 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10070                                                DAGCombinerInfo &DCI) const {
10071   SelectionDAG &DAG = DCI.DAG;
10072   SDLoc dl(N);
10073   SDValue Chain;
10074   SDValue Base;
10075   unsigned SrcOpnd;
10076   MachineMemOperand *MMO;
10077
10078   switch (N->getOpcode()) {
10079   default:
10080     llvm_unreachable("Unexpected opcode for little endian VSX store");
10081   case ISD::STORE: {
10082     StoreSDNode *ST = cast<StoreSDNode>(N);
10083     Chain = ST->getChain();
10084     Base = ST->getBasePtr();
10085     MMO = ST->getMemOperand();
10086     SrcOpnd = 1;
10087     // If the MMO suggests this isn't a store of a full vector, leave
10088     // things alone.  For a built-in, we have to make the change for
10089     // correctness, so if there is a size problem that will be a bug.
10090     if (MMO->getSize() < 16)
10091       return SDValue();
10092     break;
10093   }
10094   case ISD::INTRINSIC_VOID: {
10095     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10096     Chain = Intrin->getChain();
10097     // Intrin->getBasePtr() oddly does not get what we want.
10098     Base = Intrin->getOperand(3);
10099     MMO = Intrin->getMemOperand();
10100     SrcOpnd = 2;
10101     break;
10102   }
10103   }
10104
10105   SDValue Src = N->getOperand(SrcOpnd);
10106   MVT VecTy = Src.getValueType().getSimpleVT();
10107   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10108                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
10109   DCI.AddToWorklist(Swap.getNode());
10110   Chain = Swap.getValue(1);
10111   SDValue StoreOps[] = { Chain, Swap, Base };
10112   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10113                                           DAG.getVTList(MVT::Other),
10114                                           StoreOps, VecTy, MMO);
10115   DCI.AddToWorklist(Store.getNode());
10116   return Store;
10117 }
10118
10119 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10120                                              DAGCombinerInfo &DCI) const {
10121   SelectionDAG &DAG = DCI.DAG;
10122   SDLoc dl(N);
10123   switch (N->getOpcode()) {
10124   default: break;
10125   case PPCISD::SHL:
10126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10127       if (C->isNullValue())   // 0 << V -> 0.
10128         return N->getOperand(0);
10129     }
10130     break;
10131   case PPCISD::SRL:
10132     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10133       if (C->isNullValue())   // 0 >>u V -> 0.
10134         return N->getOperand(0);
10135     }
10136     break;
10137   case PPCISD::SRA:
10138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10139       if (C->isNullValue() ||   //  0 >>s V -> 0.
10140           C->isAllOnesValue())    // -1 >>s V -> -1.
10141         return N->getOperand(0);
10142     }
10143     break;
10144   case ISD::SIGN_EXTEND:
10145   case ISD::ZERO_EXTEND:
10146   case ISD::ANY_EXTEND: 
10147     return DAGCombineExtBoolTrunc(N, DCI);
10148   case ISD::TRUNCATE:
10149   case ISD::SETCC:
10150   case ISD::SELECT_CC:
10151     return DAGCombineTruncBoolExt(N, DCI);
10152   case ISD::SINT_TO_FP:
10153   case ISD::UINT_TO_FP:
10154     return combineFPToIntToFP(N, DCI);
10155   case ISD::STORE: {
10156     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10157     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10158         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10159         N->getOperand(1).getValueType() == MVT::i32 &&
10160         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10161       SDValue Val = N->getOperand(1).getOperand(0);
10162       if (Val.getValueType() == MVT::f32) {
10163         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10164         DCI.AddToWorklist(Val.getNode());
10165       }
10166       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10167       DCI.AddToWorklist(Val.getNode());
10168
10169       SDValue Ops[] = {
10170         N->getOperand(0), Val, N->getOperand(2),
10171         DAG.getValueType(N->getOperand(1).getValueType())
10172       };
10173
10174       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10175               DAG.getVTList(MVT::Other), Ops,
10176               cast<StoreSDNode>(N)->getMemoryVT(),
10177               cast<StoreSDNode>(N)->getMemOperand());
10178       DCI.AddToWorklist(Val.getNode());
10179       return Val;
10180     }
10181
10182     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10183     if (cast<StoreSDNode>(N)->isUnindexed() &&
10184         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10185         N->getOperand(1).getNode()->hasOneUse() &&
10186         (N->getOperand(1).getValueType() == MVT::i32 ||
10187          N->getOperand(1).getValueType() == MVT::i16 ||
10188          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10189           N->getOperand(1).getValueType() == MVT::i64))) {
10190       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10191       // Do an any-extend to 32-bits if this is a half-word input.
10192       if (BSwapOp.getValueType() == MVT::i16)
10193         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10194
10195       SDValue Ops[] = {
10196         N->getOperand(0), BSwapOp, N->getOperand(2),
10197         DAG.getValueType(N->getOperand(1).getValueType())
10198       };
10199       return
10200         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10201                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10202                                 cast<StoreSDNode>(N)->getMemOperand());
10203     }
10204
10205     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10206     EVT VT = N->getOperand(1).getValueType();
10207     if (VT.isSimple()) {
10208       MVT StoreVT = VT.getSimpleVT();
10209       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10210           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10211            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10212         return expandVSXStoreForLE(N, DCI);
10213     }
10214     break;
10215   }
10216   case ISD::LOAD: {
10217     LoadSDNode *LD = cast<LoadSDNode>(N);
10218     EVT VT = LD->getValueType(0);
10219
10220     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10221     if (VT.isSimple()) {
10222       MVT LoadVT = VT.getSimpleVT();
10223       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10224           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10225            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10226         return expandVSXLoadForLE(N, DCI);
10227     }
10228
10229     EVT MemVT = LD->getMemoryVT();
10230     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10231     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10232     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10233     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10234     if (LD->isUnindexed() && VT.isVector() &&
10235         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10236           // P8 and later hardware should just use LOAD.
10237           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10238                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10239          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10240           LD->getAlignment() >= ScalarABIAlignment)) &&
10241         LD->getAlignment() < ABIAlignment) {
10242       // This is a type-legal unaligned Altivec or QPX load.
10243       SDValue Chain = LD->getChain();
10244       SDValue Ptr = LD->getBasePtr();
10245       bool isLittleEndian = Subtarget.isLittleEndian();
10246
10247       // This implements the loading of unaligned vectors as described in
10248       // the venerable Apple Velocity Engine overview. Specifically:
10249       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10250       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10251       //
10252       // The general idea is to expand a sequence of one or more unaligned
10253       // loads into an alignment-based permutation-control instruction (lvsl
10254       // or lvsr), a series of regular vector loads (which always truncate
10255       // their input address to an aligned address), and a series of
10256       // permutations.  The results of these permutations are the requested
10257       // loaded values.  The trick is that the last "extra" load is not taken
10258       // from the address you might suspect (sizeof(vector) bytes after the
10259       // last requested load), but rather sizeof(vector) - 1 bytes after the
10260       // last requested vector. The point of this is to avoid a page fault if
10261       // the base address happened to be aligned. This works because if the
10262       // base address is aligned, then adding less than a full vector length
10263       // will cause the last vector in the sequence to be (re)loaded.
10264       // Otherwise, the next vector will be fetched as you might suspect was
10265       // necessary.
10266
10267       // We might be able to reuse the permutation generation from
10268       // a different base address offset from this one by an aligned amount.
10269       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10270       // optimization later.
10271       Intrinsic::ID Intr, IntrLD, IntrPerm;
10272       MVT PermCntlTy, PermTy, LDTy;
10273       if (Subtarget.hasAltivec()) {
10274         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10275                                  Intrinsic::ppc_altivec_lvsl;
10276         IntrLD = Intrinsic::ppc_altivec_lvx;
10277         IntrPerm = Intrinsic::ppc_altivec_vperm;
10278         PermCntlTy = MVT::v16i8;
10279         PermTy = MVT::v4i32;
10280         LDTy = MVT::v4i32;
10281       } else {
10282         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10283                                        Intrinsic::ppc_qpx_qvlpcls;
10284         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10285                                        Intrinsic::ppc_qpx_qvlfs;
10286         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10287         PermCntlTy = MVT::v4f64;
10288         PermTy = MVT::v4f64;
10289         LDTy = MemVT.getSimpleVT();
10290       }
10291
10292       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10293
10294       // Create the new MMO for the new base load. It is like the original MMO,
10295       // but represents an area in memory almost twice the vector size centered
10296       // on the original address. If the address is unaligned, we might start
10297       // reading up to (sizeof(vector)-1) bytes below the address of the
10298       // original unaligned load.
10299       MachineFunction &MF = DAG.getMachineFunction();
10300       MachineMemOperand *BaseMMO =
10301         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10302                                 2*MemVT.getStoreSize()-1);
10303
10304       // Create the new base load.
10305       SDValue LDXIntID =
10306           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10307       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10308       SDValue BaseLoad =
10309         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10310                                 DAG.getVTList(PermTy, MVT::Other),
10311                                 BaseLoadOps, LDTy, BaseMMO);
10312
10313       // Note that the value of IncOffset (which is provided to the next
10314       // load's pointer info offset value, and thus used to calculate the
10315       // alignment), and the value of IncValue (which is actually used to
10316       // increment the pointer value) are different! This is because we
10317       // require the next load to appear to be aligned, even though it
10318       // is actually offset from the base pointer by a lesser amount.
10319       int IncOffset = VT.getSizeInBits() / 8;
10320       int IncValue = IncOffset;
10321
10322       // Walk (both up and down) the chain looking for another load at the real
10323       // (aligned) offset (the alignment of the other load does not matter in
10324       // this case). If found, then do not use the offset reduction trick, as
10325       // that will prevent the loads from being later combined (as they would
10326       // otherwise be duplicates).
10327       if (!findConsecutiveLoad(LD, DAG))
10328         --IncValue;
10329
10330       SDValue Increment =
10331           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10332       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10333
10334       MachineMemOperand *ExtraMMO =
10335         MF.getMachineMemOperand(LD->getMemOperand(),
10336                                 1, 2*MemVT.getStoreSize()-1);
10337       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10338       SDValue ExtraLoad =
10339         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10340                                 DAG.getVTList(PermTy, MVT::Other),
10341                                 ExtraLoadOps, LDTy, ExtraMMO);
10342
10343       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10344         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10345
10346       // Because vperm has a big-endian bias, we must reverse the order
10347       // of the input vectors and complement the permute control vector
10348       // when generating little endian code.  We have already handled the
10349       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10350       // and ExtraLoad here.
10351       SDValue Perm;
10352       if (isLittleEndian)
10353         Perm = BuildIntrinsicOp(IntrPerm,
10354                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10355       else
10356         Perm = BuildIntrinsicOp(IntrPerm,
10357                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10358
10359       if (VT != PermTy)
10360         Perm = Subtarget.hasAltivec() ?
10361                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10362                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10363                                DAG.getTargetConstant(1, dl, MVT::i64));
10364                                // second argument is 1 because this rounding
10365                                // is always exact.
10366
10367       // The output of the permutation is our loaded result, the TokenFactor is
10368       // our new chain.
10369       DCI.CombineTo(N, Perm, TF);
10370       return SDValue(N, 0);
10371     }
10372     }
10373     break;
10374     case ISD::INTRINSIC_WO_CHAIN: {
10375       bool isLittleEndian = Subtarget.isLittleEndian();
10376       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10377       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10378                                            : Intrinsic::ppc_altivec_lvsl);
10379       if ((IID == Intr ||
10380            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10381            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10382         N->getOperand(1)->getOpcode() == ISD::ADD) {
10383         SDValue Add = N->getOperand(1);
10384
10385         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10386                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10387
10388         if (DAG.MaskedValueIsZero(
10389                 Add->getOperand(1),
10390                 APInt::getAllOnesValue(Bits /* alignment */)
10391                     .zext(
10392                         Add.getValueType().getScalarType().getSizeInBits()))) {
10393           SDNode *BasePtr = Add->getOperand(0).getNode();
10394           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10395                                     UE = BasePtr->use_end();
10396                UI != UE; ++UI) {
10397             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10398                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10399               // We've found another LVSL/LVSR, and this address is an aligned
10400               // multiple of that one. The results will be the same, so use the
10401               // one we've just found instead.
10402
10403               return SDValue(*UI, 0);
10404             }
10405           }
10406         }
10407
10408         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10409           SDNode *BasePtr = Add->getOperand(0).getNode();
10410           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10411                UE = BasePtr->use_end(); UI != UE; ++UI) {
10412             if (UI->getOpcode() == ISD::ADD &&
10413                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10414                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10415                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10416                 (1ULL << Bits) == 0) {
10417               SDNode *OtherAdd = *UI;
10418               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10419                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10420                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10421                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10422                   return SDValue(*VI, 0);
10423                 }
10424               }
10425             }
10426           }
10427         }
10428       }
10429     }
10430
10431     break;
10432   case ISD::INTRINSIC_W_CHAIN: {
10433     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10434     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10435       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10436       default:
10437         break;
10438       case Intrinsic::ppc_vsx_lxvw4x:
10439       case Intrinsic::ppc_vsx_lxvd2x:
10440         return expandVSXLoadForLE(N, DCI);
10441       }
10442     }
10443     break;
10444   }
10445   case ISD::INTRINSIC_VOID: {
10446     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10447     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10448       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10449       default:
10450         break;
10451       case Intrinsic::ppc_vsx_stxvw4x:
10452       case Intrinsic::ppc_vsx_stxvd2x:
10453         return expandVSXStoreForLE(N, DCI);
10454       }
10455     }
10456     break;
10457   }
10458   case ISD::BSWAP:
10459     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10460     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10461         N->getOperand(0).hasOneUse() &&
10462         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10463          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10464           N->getValueType(0) == MVT::i64))) {
10465       SDValue Load = N->getOperand(0);
10466       LoadSDNode *LD = cast<LoadSDNode>(Load);
10467       // Create the byte-swapping load.
10468       SDValue Ops[] = {
10469         LD->getChain(),    // Chain
10470         LD->getBasePtr(),  // Ptr
10471         DAG.getValueType(N->getValueType(0)) // VT
10472       };
10473       SDValue BSLoad =
10474         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10475                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10476                                               MVT::i64 : MVT::i32, MVT::Other),
10477                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10478
10479       // If this is an i16 load, insert the truncate.
10480       SDValue ResVal = BSLoad;
10481       if (N->getValueType(0) == MVT::i16)
10482         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10483
10484       // First, combine the bswap away.  This makes the value produced by the
10485       // load dead.
10486       DCI.CombineTo(N, ResVal);
10487
10488       // Next, combine the load away, we give it a bogus result value but a real
10489       // chain result.  The result value is dead because the bswap is dead.
10490       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10491
10492       // Return N so it doesn't get rechecked!
10493       return SDValue(N, 0);
10494     }
10495
10496     break;
10497   case PPCISD::VCMP: {
10498     // If a VCMPo node already exists with exactly the same operands as this
10499     // node, use its result instead of this node (VCMPo computes both a CR6 and
10500     // a normal output).
10501     //
10502     if (!N->getOperand(0).hasOneUse() &&
10503         !N->getOperand(1).hasOneUse() &&
10504         !N->getOperand(2).hasOneUse()) {
10505
10506       // Scan all of the users of the LHS, looking for VCMPo's that match.
10507       SDNode *VCMPoNode = nullptr;
10508
10509       SDNode *LHSN = N->getOperand(0).getNode();
10510       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10511            UI != E; ++UI)
10512         if (UI->getOpcode() == PPCISD::VCMPo &&
10513             UI->getOperand(1) == N->getOperand(1) &&
10514             UI->getOperand(2) == N->getOperand(2) &&
10515             UI->getOperand(0) == N->getOperand(0)) {
10516           VCMPoNode = *UI;
10517           break;
10518         }
10519
10520       // If there is no VCMPo node, or if the flag value has a single use, don't
10521       // transform this.
10522       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10523         break;
10524
10525       // Look at the (necessarily single) use of the flag value.  If it has a
10526       // chain, this transformation is more complex.  Note that multiple things
10527       // could use the value result, which we should ignore.
10528       SDNode *FlagUser = nullptr;
10529       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10530            FlagUser == nullptr; ++UI) {
10531         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10532         SDNode *User = *UI;
10533         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10534           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10535             FlagUser = User;
10536             break;
10537           }
10538         }
10539       }
10540
10541       // If the user is a MFOCRF instruction, we know this is safe.
10542       // Otherwise we give up for right now.
10543       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10544         return SDValue(VCMPoNode, 0);
10545     }
10546     break;
10547   }
10548   case ISD::BRCOND: {
10549     SDValue Cond = N->getOperand(1);
10550     SDValue Target = N->getOperand(2);
10551  
10552     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10553         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10554           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10555
10556       // We now need to make the intrinsic dead (it cannot be instruction
10557       // selected).
10558       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10559       assert(Cond.getNode()->hasOneUse() &&
10560              "Counter decrement has more than one use");
10561
10562       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10563                          N->getOperand(0), Target);
10564     }
10565   }
10566   break;
10567   case ISD::BR_CC: {
10568     // If this is a branch on an altivec predicate comparison, lower this so
10569     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10570     // lowering is done pre-legalize, because the legalizer lowers the predicate
10571     // compare down to code that is difficult to reassemble.
10572     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10573     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10574
10575     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10576     // value. If so, pass-through the AND to get to the intrinsic.
10577     if (LHS.getOpcode() == ISD::AND &&
10578         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10579         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10580           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10581         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10582         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10583           isZero())
10584       LHS = LHS.getOperand(0);
10585
10586     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10587         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10588           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10589         isa<ConstantSDNode>(RHS)) {
10590       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10591              "Counter decrement comparison is not EQ or NE");
10592
10593       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10594       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10595                     (CC == ISD::SETNE && !Val);
10596
10597       // We now need to make the intrinsic dead (it cannot be instruction
10598       // selected).
10599       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10600       assert(LHS.getNode()->hasOneUse() &&
10601              "Counter decrement has more than one use");
10602
10603       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10604                          N->getOperand(0), N->getOperand(4));
10605     }
10606
10607     int CompareOpc;
10608     bool isDot;
10609
10610     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10611         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10612         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10613       assert(isDot && "Can't compare against a vector result!");
10614
10615       // If this is a comparison against something other than 0/1, then we know
10616       // that the condition is never/always true.
10617       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10618       if (Val != 0 && Val != 1) {
10619         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10620           return N->getOperand(0);
10621         // Always !=, turn it into an unconditional branch.
10622         return DAG.getNode(ISD::BR, dl, MVT::Other,
10623                            N->getOperand(0), N->getOperand(4));
10624       }
10625
10626       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10627
10628       // Create the PPCISD altivec 'dot' comparison node.
10629       SDValue Ops[] = {
10630         LHS.getOperand(2),  // LHS of compare
10631         LHS.getOperand(3),  // RHS of compare
10632         DAG.getConstant(CompareOpc, dl, MVT::i32)
10633       };
10634       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10635       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10636
10637       // Unpack the result based on how the target uses it.
10638       PPC::Predicate CompOpc;
10639       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10640       default:  // Can't happen, don't crash on invalid number though.
10641       case 0:   // Branch on the value of the EQ bit of CR6.
10642         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10643         break;
10644       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10645         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10646         break;
10647       case 2:   // Branch on the value of the LT bit of CR6.
10648         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10649         break;
10650       case 3:   // Branch on the inverted value of the LT bit of CR6.
10651         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10652         break;
10653       }
10654
10655       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10656                          DAG.getConstant(CompOpc, dl, MVT::i32),
10657                          DAG.getRegister(PPC::CR6, MVT::i32),
10658                          N->getOperand(4), CompNode.getValue(1));
10659     }
10660     break;
10661   }
10662   }
10663
10664   return SDValue();
10665 }
10666
10667 SDValue
10668 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10669                                   SelectionDAG &DAG,
10670                                   std::vector<SDNode *> *Created) const {
10671   // fold (sdiv X, pow2)
10672   EVT VT = N->getValueType(0);
10673   if (VT == MVT::i64 && !Subtarget.isPPC64())
10674     return SDValue();
10675   if ((VT != MVT::i32 && VT != MVT::i64) ||
10676       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10677     return SDValue();
10678
10679   SDLoc DL(N);
10680   SDValue N0 = N->getOperand(0);
10681
10682   bool IsNegPow2 = (-Divisor).isPowerOf2();
10683   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10684   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10685
10686   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10687   if (Created)
10688     Created->push_back(Op.getNode());
10689
10690   if (IsNegPow2) {
10691     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10692     if (Created)
10693       Created->push_back(Op.getNode());
10694   }
10695
10696   return Op;
10697 }
10698
10699 //===----------------------------------------------------------------------===//
10700 // Inline Assembly Support
10701 //===----------------------------------------------------------------------===//
10702
10703 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10704                                                       APInt &KnownZero,
10705                                                       APInt &KnownOne,
10706                                                       const SelectionDAG &DAG,
10707                                                       unsigned Depth) const {
10708   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10709   switch (Op.getOpcode()) {
10710   default: break;
10711   case PPCISD::LBRX: {
10712     // lhbrx is known to have the top bits cleared out.
10713     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10714       KnownZero = 0xFFFF0000;
10715     break;
10716   }
10717   case ISD::INTRINSIC_WO_CHAIN: {
10718     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10719     default: break;
10720     case Intrinsic::ppc_altivec_vcmpbfp_p:
10721     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10722     case Intrinsic::ppc_altivec_vcmpequb_p:
10723     case Intrinsic::ppc_altivec_vcmpequh_p:
10724     case Intrinsic::ppc_altivec_vcmpequw_p:
10725     case Intrinsic::ppc_altivec_vcmpequd_p:
10726     case Intrinsic::ppc_altivec_vcmpgefp_p:
10727     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10728     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10729     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10730     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10731     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10732     case Intrinsic::ppc_altivec_vcmpgtub_p:
10733     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10734     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10735     case Intrinsic::ppc_altivec_vcmpgtud_p:
10736       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10737       break;
10738     }
10739   }
10740   }
10741 }
10742
10743 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10744   switch (Subtarget.getDarwinDirective()) {
10745   default: break;
10746   case PPC::DIR_970:
10747   case PPC::DIR_PWR4:
10748   case PPC::DIR_PWR5:
10749   case PPC::DIR_PWR5X:
10750   case PPC::DIR_PWR6:
10751   case PPC::DIR_PWR6X:
10752   case PPC::DIR_PWR7:
10753   case PPC::DIR_PWR8: {
10754     if (!ML)
10755       break;
10756
10757     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10758
10759     // For small loops (between 5 and 8 instructions), align to a 32-byte
10760     // boundary so that the entire loop fits in one instruction-cache line.
10761     uint64_t LoopSize = 0;
10762     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10763       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10764         LoopSize += TII->GetInstSizeInBytes(J);
10765
10766     if (LoopSize > 16 && LoopSize <= 32)
10767       return 5;
10768
10769     break;
10770   }
10771   }
10772
10773   return TargetLowering::getPrefLoopAlignment(ML);
10774 }
10775
10776 /// getConstraintType - Given a constraint, return the type of
10777 /// constraint it is for this target.
10778 PPCTargetLowering::ConstraintType
10779 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
10780   if (Constraint.size() == 1) {
10781     switch (Constraint[0]) {
10782     default: break;
10783     case 'b':
10784     case 'r':
10785     case 'f':
10786     case 'v':
10787     case 'y':
10788       return C_RegisterClass;
10789     case 'Z':
10790       // FIXME: While Z does indicate a memory constraint, it specifically
10791       // indicates an r+r address (used in conjunction with the 'y' modifier
10792       // in the replacement string). Currently, we're forcing the base
10793       // register to be r0 in the asm printer (which is interpreted as zero)
10794       // and forming the complete address in the second register. This is
10795       // suboptimal.
10796       return C_Memory;
10797     }
10798   } else if (Constraint == "wc") { // individual CR bits.
10799     return C_RegisterClass;
10800   } else if (Constraint == "wa" || Constraint == "wd" ||
10801              Constraint == "wf" || Constraint == "ws") {
10802     return C_RegisterClass; // VSX registers.
10803   }
10804   return TargetLowering::getConstraintType(Constraint);
10805 }
10806
10807 /// Examine constraint type and operand type and determine a weight value.
10808 /// This object must already have been set up with the operand type
10809 /// and the current alternative constraint selected.
10810 TargetLowering::ConstraintWeight
10811 PPCTargetLowering::getSingleConstraintMatchWeight(
10812     AsmOperandInfo &info, const char *constraint) const {
10813   ConstraintWeight weight = CW_Invalid;
10814   Value *CallOperandVal = info.CallOperandVal;
10815     // If we don't have a value, we can't do a match,
10816     // but allow it at the lowest weight.
10817   if (!CallOperandVal)
10818     return CW_Default;
10819   Type *type = CallOperandVal->getType();
10820
10821   // Look at the constraint type.
10822   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10823     return CW_Register; // an individual CR bit.
10824   else if ((StringRef(constraint) == "wa" ||
10825             StringRef(constraint) == "wd" ||
10826             StringRef(constraint) == "wf") &&
10827            type->isVectorTy())
10828     return CW_Register;
10829   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10830     return CW_Register;
10831
10832   switch (*constraint) {
10833   default:
10834     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10835     break;
10836   case 'b':
10837     if (type->isIntegerTy())
10838       weight = CW_Register;
10839     break;
10840   case 'f':
10841     if (type->isFloatTy())
10842       weight = CW_Register;
10843     break;
10844   case 'd':
10845     if (type->isDoubleTy())
10846       weight = CW_Register;
10847     break;
10848   case 'v':
10849     if (type->isVectorTy())
10850       weight = CW_Register;
10851     break;
10852   case 'y':
10853     weight = CW_Register;
10854     break;
10855   case 'Z':
10856     weight = CW_Memory;
10857     break;
10858   }
10859   return weight;
10860 }
10861
10862 std::pair<unsigned, const TargetRegisterClass *>
10863 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10864                                                 StringRef Constraint,
10865                                                 MVT VT) const {
10866   if (Constraint.size() == 1) {
10867     // GCC RS6000 Constraint Letters
10868     switch (Constraint[0]) {
10869     case 'b':   // R1-R31
10870       if (VT == MVT::i64 && Subtarget.isPPC64())
10871         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10872       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10873     case 'r':   // R0-R31
10874       if (VT == MVT::i64 && Subtarget.isPPC64())
10875         return std::make_pair(0U, &PPC::G8RCRegClass);
10876       return std::make_pair(0U, &PPC::GPRCRegClass);
10877     case 'f':
10878       if (VT == MVT::f32 || VT == MVT::i32)
10879         return std::make_pair(0U, &PPC::F4RCRegClass);
10880       if (VT == MVT::f64 || VT == MVT::i64)
10881         return std::make_pair(0U, &PPC::F8RCRegClass);
10882       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10883         return std::make_pair(0U, &PPC::QFRCRegClass);
10884       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10885         return std::make_pair(0U, &PPC::QSRCRegClass);
10886       break;
10887     case 'v':
10888       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10889         return std::make_pair(0U, &PPC::QFRCRegClass);
10890       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10891         return std::make_pair(0U, &PPC::QSRCRegClass);
10892       return std::make_pair(0U, &PPC::VRRCRegClass);
10893     case 'y':   // crrc
10894       return std::make_pair(0U, &PPC::CRRCRegClass);
10895     }
10896   } else if (Constraint == "wc") { // an individual CR bit.
10897     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10898   } else if (Constraint == "wa" || Constraint == "wd" ||
10899              Constraint == "wf") {
10900     return std::make_pair(0U, &PPC::VSRCRegClass);
10901   } else if (Constraint == "ws") {
10902     if (VT == MVT::f32)
10903       return std::make_pair(0U, &PPC::VSSRCRegClass);
10904     else
10905       return std::make_pair(0U, &PPC::VSFRCRegClass);
10906   }
10907
10908   std::pair<unsigned, const TargetRegisterClass *> R =
10909       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10910
10911   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10912   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10913   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10914   // register.
10915   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10916   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10917   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10918       PPC::GPRCRegClass.contains(R.first))
10919     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10920                             PPC::sub_32, &PPC::G8RCRegClass),
10921                           &PPC::G8RCRegClass);
10922
10923   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10924   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10925     R.first = PPC::CR0;
10926     R.second = &PPC::CRRCRegClass;
10927   }
10928
10929   return R;
10930 }
10931
10932
10933 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10934 /// vector.  If it is invalid, don't add anything to Ops.
10935 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10936                                                      std::string &Constraint,
10937                                                      std::vector<SDValue>&Ops,
10938                                                      SelectionDAG &DAG) const {
10939   SDValue Result;
10940
10941   // Only support length 1 constraints.
10942   if (Constraint.length() > 1) return;
10943
10944   char Letter = Constraint[0];
10945   switch (Letter) {
10946   default: break;
10947   case 'I':
10948   case 'J':
10949   case 'K':
10950   case 'L':
10951   case 'M':
10952   case 'N':
10953   case 'O':
10954   case 'P': {
10955     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10956     if (!CST) return; // Must be an immediate to match.
10957     SDLoc dl(Op);
10958     int64_t Value = CST->getSExtValue();
10959     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10960                          // numbers are printed as such.
10961     switch (Letter) {
10962     default: llvm_unreachable("Unknown constraint letter!");
10963     case 'I':  // "I" is a signed 16-bit constant.
10964       if (isInt<16>(Value))
10965         Result = DAG.getTargetConstant(Value, dl, TCVT);
10966       break;
10967     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10968       if (isShiftedUInt<16, 16>(Value))
10969         Result = DAG.getTargetConstant(Value, dl, TCVT);
10970       break;
10971     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10972       if (isShiftedInt<16, 16>(Value))
10973         Result = DAG.getTargetConstant(Value, dl, TCVT);
10974       break;
10975     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10976       if (isUInt<16>(Value))
10977         Result = DAG.getTargetConstant(Value, dl, TCVT);
10978       break;
10979     case 'M':  // "M" is a constant that is greater than 31.
10980       if (Value > 31)
10981         Result = DAG.getTargetConstant(Value, dl, TCVT);
10982       break;
10983     case 'N':  // "N" is a positive constant that is an exact power of two.
10984       if (Value > 0 && isPowerOf2_64(Value))
10985         Result = DAG.getTargetConstant(Value, dl, TCVT);
10986       break;
10987     case 'O':  // "O" is the constant zero.
10988       if (Value == 0)
10989         Result = DAG.getTargetConstant(Value, dl, TCVT);
10990       break;
10991     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10992       if (isInt<16>(-Value))
10993         Result = DAG.getTargetConstant(Value, dl, TCVT);
10994       break;
10995     }
10996     break;
10997   }
10998   }
10999
11000   if (Result.getNode()) {
11001     Ops.push_back(Result);
11002     return;
11003   }
11004
11005   // Handle standard constraint letters.
11006   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11007 }
11008
11009 // isLegalAddressingMode - Return true if the addressing mode represented
11010 // by AM is legal for this target, for a load/store of the specified type.
11011 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11012                                               const AddrMode &AM, Type *Ty,
11013                                               unsigned AS) const {
11014   // PPC does not allow r+i addressing modes for vectors!
11015   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11016     return false;
11017
11018   // PPC allows a sign-extended 16-bit immediate field.
11019   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11020     return false;
11021
11022   // No global is ever allowed as a base.
11023   if (AM.BaseGV)
11024     return false;
11025
11026   // PPC only support r+r,
11027   switch (AM.Scale) {
11028   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11029     break;
11030   case 1:
11031     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11032       return false;
11033     // Otherwise we have r+r or r+i.
11034     break;
11035   case 2:
11036     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11037       return false;
11038     // Allow 2*r as r+r.
11039     break;
11040   default:
11041     // No other scales are supported.
11042     return false;
11043   }
11044
11045   return true;
11046 }
11047
11048 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11049                                            SelectionDAG &DAG) const {
11050   MachineFunction &MF = DAG.getMachineFunction();
11051   MachineFrameInfo *MFI = MF.getFrameInfo();
11052   MFI->setReturnAddressIsTaken(true);
11053
11054   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11055     return SDValue();
11056
11057   SDLoc dl(Op);
11058   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11059
11060   // Make sure the function does not optimize away the store of the RA to
11061   // the stack.
11062   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11063   FuncInfo->setLRStoreRequired();
11064   bool isPPC64 = Subtarget.isPPC64();
11065   auto PtrVT = getPointerTy(MF.getDataLayout());
11066
11067   if (Depth > 0) {
11068     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11069     SDValue Offset =
11070         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11071                         isPPC64 ? MVT::i64 : MVT::i32);
11072     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11073                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11074                        MachinePointerInfo(), false, false, false, 0);
11075   }
11076
11077   // Just load the return address off the stack.
11078   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11079   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11080                      MachinePointerInfo(), false, false, false, 0);
11081 }
11082
11083 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11084                                           SelectionDAG &DAG) const {
11085   SDLoc dl(Op);
11086   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11087
11088   MachineFunction &MF = DAG.getMachineFunction();
11089   MachineFrameInfo *MFI = MF.getFrameInfo();
11090   MFI->setFrameAddressIsTaken(true);
11091
11092   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11093   bool isPPC64 = PtrVT == MVT::i64;
11094
11095   // Naked functions never have a frame pointer, and so we use r1. For all
11096   // other functions, this decision must be delayed until during PEI.
11097   unsigned FrameReg;
11098   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11099     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11100   else
11101     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11102
11103   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11104                                          PtrVT);
11105   while (Depth--)
11106     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11107                             FrameAddr, MachinePointerInfo(), false, false,
11108                             false, 0);
11109   return FrameAddr;
11110 }
11111
11112 // FIXME? Maybe this could be a TableGen attribute on some registers and
11113 // this table could be generated automatically from RegInfo.
11114 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11115                                               SelectionDAG &DAG) const {
11116   bool isPPC64 = Subtarget.isPPC64();
11117   bool isDarwinABI = Subtarget.isDarwinABI();
11118
11119   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11120       (!isPPC64 && VT != MVT::i32))
11121     report_fatal_error("Invalid register global variable type");
11122
11123   bool is64Bit = isPPC64 && VT == MVT::i64;
11124   unsigned Reg = StringSwitch<unsigned>(RegName)
11125                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11126                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11127                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11128                                   (is64Bit ? PPC::X13 : PPC::R13))
11129                    .Default(0);
11130
11131   if (Reg)
11132     return Reg;
11133   report_fatal_error("Invalid register name global variable");
11134 }
11135
11136 bool
11137 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11138   // The PowerPC target isn't yet aware of offsets.
11139   return false;
11140 }
11141
11142 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11143                                            const CallInst &I,
11144                                            unsigned Intrinsic) const {
11145
11146   switch (Intrinsic) {
11147   case Intrinsic::ppc_qpx_qvlfd:
11148   case Intrinsic::ppc_qpx_qvlfs:
11149   case Intrinsic::ppc_qpx_qvlfcd:
11150   case Intrinsic::ppc_qpx_qvlfcs:
11151   case Intrinsic::ppc_qpx_qvlfiwa:
11152   case Intrinsic::ppc_qpx_qvlfiwz:
11153   case Intrinsic::ppc_altivec_lvx:
11154   case Intrinsic::ppc_altivec_lvxl:
11155   case Intrinsic::ppc_altivec_lvebx:
11156   case Intrinsic::ppc_altivec_lvehx:
11157   case Intrinsic::ppc_altivec_lvewx:
11158   case Intrinsic::ppc_vsx_lxvd2x:
11159   case Intrinsic::ppc_vsx_lxvw4x: {
11160     EVT VT;
11161     switch (Intrinsic) {
11162     case Intrinsic::ppc_altivec_lvebx:
11163       VT = MVT::i8;
11164       break;
11165     case Intrinsic::ppc_altivec_lvehx:
11166       VT = MVT::i16;
11167       break;
11168     case Intrinsic::ppc_altivec_lvewx:
11169       VT = MVT::i32;
11170       break;
11171     case Intrinsic::ppc_vsx_lxvd2x:
11172       VT = MVT::v2f64;
11173       break;
11174     case Intrinsic::ppc_qpx_qvlfd:
11175       VT = MVT::v4f64;
11176       break;
11177     case Intrinsic::ppc_qpx_qvlfs:
11178       VT = MVT::v4f32;
11179       break;
11180     case Intrinsic::ppc_qpx_qvlfcd:
11181       VT = MVT::v2f64;
11182       break;
11183     case Intrinsic::ppc_qpx_qvlfcs:
11184       VT = MVT::v2f32;
11185       break;
11186     default:
11187       VT = MVT::v4i32;
11188       break;
11189     }
11190
11191     Info.opc = ISD::INTRINSIC_W_CHAIN;
11192     Info.memVT = VT;
11193     Info.ptrVal = I.getArgOperand(0);
11194     Info.offset = -VT.getStoreSize()+1;
11195     Info.size = 2*VT.getStoreSize()-1;
11196     Info.align = 1;
11197     Info.vol = false;
11198     Info.readMem = true;
11199     Info.writeMem = false;
11200     return true;
11201   }
11202   case Intrinsic::ppc_qpx_qvlfda:
11203   case Intrinsic::ppc_qpx_qvlfsa:
11204   case Intrinsic::ppc_qpx_qvlfcda:
11205   case Intrinsic::ppc_qpx_qvlfcsa:
11206   case Intrinsic::ppc_qpx_qvlfiwaa:
11207   case Intrinsic::ppc_qpx_qvlfiwza: {
11208     EVT VT;
11209     switch (Intrinsic) {
11210     case Intrinsic::ppc_qpx_qvlfda:
11211       VT = MVT::v4f64;
11212       break;
11213     case Intrinsic::ppc_qpx_qvlfsa:
11214       VT = MVT::v4f32;
11215       break;
11216     case Intrinsic::ppc_qpx_qvlfcda:
11217       VT = MVT::v2f64;
11218       break;
11219     case Intrinsic::ppc_qpx_qvlfcsa:
11220       VT = MVT::v2f32;
11221       break;
11222     default:
11223       VT = MVT::v4i32;
11224       break;
11225     }
11226
11227     Info.opc = ISD::INTRINSIC_W_CHAIN;
11228     Info.memVT = VT;
11229     Info.ptrVal = I.getArgOperand(0);
11230     Info.offset = 0;
11231     Info.size = VT.getStoreSize();
11232     Info.align = 1;
11233     Info.vol = false;
11234     Info.readMem = true;
11235     Info.writeMem = false;
11236     return true;
11237   }
11238   case Intrinsic::ppc_qpx_qvstfd:
11239   case Intrinsic::ppc_qpx_qvstfs:
11240   case Intrinsic::ppc_qpx_qvstfcd:
11241   case Intrinsic::ppc_qpx_qvstfcs:
11242   case Intrinsic::ppc_qpx_qvstfiw:
11243   case Intrinsic::ppc_altivec_stvx:
11244   case Intrinsic::ppc_altivec_stvxl:
11245   case Intrinsic::ppc_altivec_stvebx:
11246   case Intrinsic::ppc_altivec_stvehx:
11247   case Intrinsic::ppc_altivec_stvewx:
11248   case Intrinsic::ppc_vsx_stxvd2x:
11249   case Intrinsic::ppc_vsx_stxvw4x: {
11250     EVT VT;
11251     switch (Intrinsic) {
11252     case Intrinsic::ppc_altivec_stvebx:
11253       VT = MVT::i8;
11254       break;
11255     case Intrinsic::ppc_altivec_stvehx:
11256       VT = MVT::i16;
11257       break;
11258     case Intrinsic::ppc_altivec_stvewx:
11259       VT = MVT::i32;
11260       break;
11261     case Intrinsic::ppc_vsx_stxvd2x:
11262       VT = MVT::v2f64;
11263       break;
11264     case Intrinsic::ppc_qpx_qvstfd:
11265       VT = MVT::v4f64;
11266       break;
11267     case Intrinsic::ppc_qpx_qvstfs:
11268       VT = MVT::v4f32;
11269       break;
11270     case Intrinsic::ppc_qpx_qvstfcd:
11271       VT = MVT::v2f64;
11272       break;
11273     case Intrinsic::ppc_qpx_qvstfcs:
11274       VT = MVT::v2f32;
11275       break;
11276     default:
11277       VT = MVT::v4i32;
11278       break;
11279     }
11280
11281     Info.opc = ISD::INTRINSIC_VOID;
11282     Info.memVT = VT;
11283     Info.ptrVal = I.getArgOperand(1);
11284     Info.offset = -VT.getStoreSize()+1;
11285     Info.size = 2*VT.getStoreSize()-1;
11286     Info.align = 1;
11287     Info.vol = false;
11288     Info.readMem = false;
11289     Info.writeMem = true;
11290     return true;
11291   }
11292   case Intrinsic::ppc_qpx_qvstfda:
11293   case Intrinsic::ppc_qpx_qvstfsa:
11294   case Intrinsic::ppc_qpx_qvstfcda:
11295   case Intrinsic::ppc_qpx_qvstfcsa:
11296   case Intrinsic::ppc_qpx_qvstfiwa: {
11297     EVT VT;
11298     switch (Intrinsic) {
11299     case Intrinsic::ppc_qpx_qvstfda:
11300       VT = MVT::v4f64;
11301       break;
11302     case Intrinsic::ppc_qpx_qvstfsa:
11303       VT = MVT::v4f32;
11304       break;
11305     case Intrinsic::ppc_qpx_qvstfcda:
11306       VT = MVT::v2f64;
11307       break;
11308     case Intrinsic::ppc_qpx_qvstfcsa:
11309       VT = MVT::v2f32;
11310       break;
11311     default:
11312       VT = MVT::v4i32;
11313       break;
11314     }
11315
11316     Info.opc = ISD::INTRINSIC_VOID;
11317     Info.memVT = VT;
11318     Info.ptrVal = I.getArgOperand(1);
11319     Info.offset = 0;
11320     Info.size = VT.getStoreSize();
11321     Info.align = 1;
11322     Info.vol = false;
11323     Info.readMem = false;
11324     Info.writeMem = true;
11325     return true;
11326   }
11327   default:
11328     break;
11329   }
11330
11331   return false;
11332 }
11333
11334 /// getOptimalMemOpType - Returns the target specific optimal type for load
11335 /// and store operations as a result of memset, memcpy, and memmove
11336 /// lowering. If DstAlign is zero that means it's safe to destination
11337 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11338 /// means there isn't a need to check it against alignment requirement,
11339 /// probably because the source does not need to be loaded. If 'IsMemset' is
11340 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11341 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11342 /// source is constant so it does not need to be loaded.
11343 /// It returns EVT::Other if the type should be determined using generic
11344 /// target-independent logic.
11345 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11346                                            unsigned DstAlign, unsigned SrcAlign,
11347                                            bool IsMemset, bool ZeroMemset,
11348                                            bool MemcpyStrSrc,
11349                                            MachineFunction &MF) const {
11350   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11351     const Function *F = MF.getFunction();
11352     // When expanding a memset, require at least two QPX instructions to cover
11353     // the cost of loading the value to be stored from the constant pool.
11354     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11355        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11356         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11357       return MVT::v4f64;
11358     }
11359
11360     // We should use Altivec/VSX loads and stores when available. For unaligned
11361     // addresses, unaligned VSX loads are only fast starting with the P8.
11362     if (Subtarget.hasAltivec() && Size >= 16 &&
11363         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11364          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11365       return MVT::v4i32;
11366   }
11367
11368   if (Subtarget.isPPC64()) {
11369     return MVT::i64;
11370   }
11371
11372   return MVT::i32;
11373 }
11374
11375 /// \brief Returns true if it is beneficial to convert a load of a constant
11376 /// to just the constant itself.
11377 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11378                                                           Type *Ty) const {
11379   assert(Ty->isIntegerTy());
11380
11381   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11382   if (BitSize == 0 || BitSize > 64)
11383     return false;
11384   return true;
11385 }
11386
11387 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11388   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11389     return false;
11390   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11391   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11392   return NumBits1 == 64 && NumBits2 == 32;
11393 }
11394
11395 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11396   if (!VT1.isInteger() || !VT2.isInteger())
11397     return false;
11398   unsigned NumBits1 = VT1.getSizeInBits();
11399   unsigned NumBits2 = VT2.getSizeInBits();
11400   return NumBits1 == 64 && NumBits2 == 32;
11401 }
11402
11403 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11404   // Generally speaking, zexts are not free, but they are free when they can be
11405   // folded with other operations.
11406   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11407     EVT MemVT = LD->getMemoryVT();
11408     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11409          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11410         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11411          LD->getExtensionType() == ISD::ZEXTLOAD))
11412       return true;
11413   }
11414
11415   // FIXME: Add other cases...
11416   //  - 32-bit shifts with a zext to i64
11417   //  - zext after ctlz, bswap, etc.
11418   //  - zext after and by a constant mask
11419
11420   return TargetLowering::isZExtFree(Val, VT2);
11421 }
11422
11423 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11424   assert(VT.isFloatingPoint());
11425   return true;
11426 }
11427
11428 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11429   return isInt<16>(Imm) || isUInt<16>(Imm);
11430 }
11431
11432 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11433   return isInt<16>(Imm) || isUInt<16>(Imm);
11434 }
11435
11436 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11437                                                        unsigned,
11438                                                        unsigned,
11439                                                        bool *Fast) const {
11440   if (DisablePPCUnaligned)
11441     return false;
11442
11443   // PowerPC supports unaligned memory access for simple non-vector types.
11444   // Although accessing unaligned addresses is not as efficient as accessing
11445   // aligned addresses, it is generally more efficient than manual expansion,
11446   // and generally only traps for software emulation when crossing page
11447   // boundaries.
11448
11449   if (!VT.isSimple())
11450     return false;
11451
11452   if (VT.getSimpleVT().isVector()) {
11453     if (Subtarget.hasVSX()) {
11454       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11455           VT != MVT::v4f32 && VT != MVT::v4i32)
11456         return false;
11457     } else {
11458       return false;
11459     }
11460   }
11461
11462   if (VT == MVT::ppcf128)
11463     return false;
11464
11465   if (Fast)
11466     *Fast = true;
11467
11468   return true;
11469 }
11470
11471 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11472   VT = VT.getScalarType();
11473
11474   if (!VT.isSimple())
11475     return false;
11476
11477   switch (VT.getSimpleVT().SimpleTy) {
11478   case MVT::f32:
11479   case MVT::f64:
11480     return true;
11481   default:
11482     break;
11483   }
11484
11485   return false;
11486 }
11487
11488 const MCPhysReg *
11489 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11490   // LR is a callee-save register, but we must treat it as clobbered by any call
11491   // site. Hence we include LR in the scratch registers, which are in turn added
11492   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11493   // to CTR, which is used by any indirect call.
11494   static const MCPhysReg ScratchRegs[] = {
11495     PPC::X12, PPC::LR8, PPC::CTR8, 0
11496   };
11497
11498   return ScratchRegs;
11499 }
11500
11501 bool
11502 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11503                      EVT VT , unsigned DefinedValues) const {
11504   if (VT == MVT::v2i64)
11505     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
11506
11507   if (Subtarget.hasQPX()) {
11508     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11509       return true;
11510   }
11511
11512   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11513 }
11514
11515 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11516   if (DisableILPPref || Subtarget.enableMachineScheduler())
11517     return TargetLowering::getSchedulingPreference(N);
11518
11519   return Sched::ILP;
11520 }
11521
11522 // Create a fast isel object.
11523 FastISel *
11524 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11525                                   const TargetLibraryInfo *LibInfo) const {
11526   return PPC::createFastISel(FuncInfo, LibInfo);
11527 }