[PPC64] Handle vpkudum mask pattern correctly when vpkudum isn't available
[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       // This check is temporary until support for quadword add/sub is added
407       if (VT.SimpleTy != MVT::v1i128) {
408         setOperationAction(ISD::ADD , VT, Legal);
409         setOperationAction(ISD::SUB , VT, Legal);
410       }
411       else {
412         setOperationAction(ISD::ADD , VT, Expand);
413         setOperationAction(ISD::SUB , VT, Expand);
414       }
415       
416       // Vector instructions introduced in P8
417       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
418         setOperationAction(ISD::CTPOP, VT, Legal);
419         setOperationAction(ISD::CTLZ, VT, Legal);
420       }
421       else {
422         setOperationAction(ISD::CTPOP, VT, Expand);
423         setOperationAction(ISD::CTLZ, VT, Expand);
424       }
425
426       // We promote all shuffles to v16i8.
427       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
428       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
429
430       // We promote all non-typed operations to v4i32.
431       setOperationAction(ISD::AND   , VT, Promote);
432       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
433       setOperationAction(ISD::OR    , VT, Promote);
434       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
435       setOperationAction(ISD::XOR   , VT, Promote);
436       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
437       setOperationAction(ISD::LOAD  , VT, Promote);
438       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
439       setOperationAction(ISD::SELECT, VT, Promote);
440       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
441       setOperationAction(ISD::STORE, VT, Promote);
442       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
443
444       // No other operations are legal.
445       setOperationAction(ISD::MUL , VT, Expand);
446       setOperationAction(ISD::SDIV, VT, Expand);
447       setOperationAction(ISD::SREM, VT, Expand);
448       setOperationAction(ISD::UDIV, VT, Expand);
449       setOperationAction(ISD::UREM, VT, Expand);
450       setOperationAction(ISD::FDIV, VT, Expand);
451       setOperationAction(ISD::FREM, VT, Expand);
452       setOperationAction(ISD::FNEG, VT, Expand);
453       setOperationAction(ISD::FSQRT, VT, Expand);
454       setOperationAction(ISD::FLOG, VT, Expand);
455       setOperationAction(ISD::FLOG10, VT, Expand);
456       setOperationAction(ISD::FLOG2, VT, Expand);
457       setOperationAction(ISD::FEXP, VT, Expand);
458       setOperationAction(ISD::FEXP2, VT, Expand);
459       setOperationAction(ISD::FSIN, VT, Expand);
460       setOperationAction(ISD::FCOS, VT, Expand);
461       setOperationAction(ISD::FABS, VT, Expand);
462       setOperationAction(ISD::FPOWI, VT, Expand);
463       setOperationAction(ISD::FFLOOR, VT, Expand);
464       setOperationAction(ISD::FCEIL,  VT, Expand);
465       setOperationAction(ISD::FTRUNC, VT, Expand);
466       setOperationAction(ISD::FRINT,  VT, Expand);
467       setOperationAction(ISD::FNEARBYINT, VT, Expand);
468       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
469       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
470       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
471       setOperationAction(ISD::MULHU, VT, Expand);
472       setOperationAction(ISD::MULHS, VT, Expand);
473       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
474       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
475       setOperationAction(ISD::UDIVREM, VT, Expand);
476       setOperationAction(ISD::SDIVREM, VT, Expand);
477       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
478       setOperationAction(ISD::FPOW, VT, Expand);
479       setOperationAction(ISD::BSWAP, VT, Expand);
480       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
481       setOperationAction(ISD::CTTZ, VT, Expand);
482       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
483       setOperationAction(ISD::VSELECT, VT, Expand);
484       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
485
486       for (MVT InnerVT : MVT::vector_valuetypes()) {
487         setTruncStoreAction(VT, InnerVT, Expand);
488         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
489         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
490         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
491       }
492     }
493
494     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
495     // with merges, splats, etc.
496     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
497
498     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
499     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
500     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
501     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
502     setOperationAction(ISD::SELECT, MVT::v4i32,
503                        Subtarget.useCRBits() ? Legal : Expand);
504     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
505     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
506     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
507     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
508     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
509     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
510     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
511     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
512     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
513
514     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
515     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
516     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
517     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
518
519     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
520     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
521
522     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
523       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
524       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
525     }
526
527     
528     if (Subtarget.hasP8Altivec()) 
529       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
530     else
531       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
532       
533     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
534     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
535
536     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
537     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
538
539     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
540     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
541     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
542     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
543
544     // Altivec does not contain unordered floating-point compare instructions
545     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
546     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
547     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
548     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
549
550     if (Subtarget.hasVSX()) {
551       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
552       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
553
554       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
555       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
556       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
557       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
558       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
559
560       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
561
562       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
563       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
564
565       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
566       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
567
568       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
569       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
570       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
571       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
572       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
573
574       // Share the Altivec comparison restrictions.
575       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
576       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
577       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
578       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
579
580       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
581       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
582
583       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
584
585       if (Subtarget.hasP8Vector())
586         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
587
588       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
589
590       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
591       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
592
593       if (Subtarget.hasP8Altivec()) {
594         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
595         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
596         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
597
598         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
599       }
600       else {
601         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
602         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
603         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
604
605         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
606
607         // VSX v2i64 only supports non-arithmetic operations.
608         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
609         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
610       }
611
612       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
613       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
614       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
615       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
616
617       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
618
619       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
620       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
621       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
622       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
623
624       // Vector operation legalization checks the result type of
625       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
626       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
627       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
628       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
629       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
630
631       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
632     }
633
634     if (Subtarget.hasP8Altivec()) {
635       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
636       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
637     }
638   }
639
640   if (Subtarget.hasQPX()) {
641     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
642     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
643     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
644     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
645
646     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
647     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
648
649     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
650     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
651
652     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
653     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
654
655     if (!Subtarget.useCRBits())
656       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
657     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
658
659     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
660     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
661     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
662     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
663     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
664     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
665     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
666
667     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
668     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
669
670     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
671     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
672     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
673
674     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
675     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
676     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
677     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
678     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
679     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
680     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
681     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
682     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
683     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
684     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
685
686     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
687     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
688
689     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
690     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
691
692     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
693
694     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
695     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
696     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
697     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
698
699     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
700     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
701
702     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
703     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
704
705     if (!Subtarget.useCRBits())
706       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
707     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
708
709     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
710     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
711     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
712     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
713     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
714     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
715     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
716
717     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
718     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
719
720     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
721     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
722     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
723     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
724     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
725     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
726     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
727     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
728     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
729     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
730     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
731
732     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
733     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
734
735     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
736     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
737
738     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
739
740     setOperationAction(ISD::AND , MVT::v4i1, Legal);
741     setOperationAction(ISD::OR , MVT::v4i1, Legal);
742     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
743
744     if (!Subtarget.useCRBits())
745       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
746     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
747
748     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
749     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
750
751     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
753     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
754     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
755     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
756     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
757     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
758
759     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
760     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
761
762     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
763
764     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
765     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
766     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
767     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
768
769     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
770     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
771     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
772     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
773
774     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
775     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
776
777     // These need to set FE_INEXACT, and so cannot be vectorized here.
778     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
779     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
780
781     if (TM.Options.UnsafeFPMath) {
782       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
783       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
784
785       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
786       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
787     } else {
788       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
789       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
790
791       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
792       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
793     }
794   }
795
796   if (Subtarget.has64BitSupport())
797     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
798
799   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
800
801   if (!isPPC64) {
802     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
803     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
804   }
805
806   setBooleanContents(ZeroOrOneBooleanContent);
807
808   if (Subtarget.hasAltivec()) {
809     // Altivec instructions set fields to all zeros or all ones.
810     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
811   }
812
813   if (!isPPC64) {
814     // These libcalls are not available in 32-bit.
815     setLibcallName(RTLIB::SHL_I128, nullptr);
816     setLibcallName(RTLIB::SRL_I128, nullptr);
817     setLibcallName(RTLIB::SRA_I128, nullptr);
818   }
819
820   if (isPPC64) {
821     setStackPointerRegisterToSaveRestore(PPC::X1);
822     setExceptionPointerRegister(PPC::X3);
823     setExceptionSelectorRegister(PPC::X4);
824   } else {
825     setStackPointerRegisterToSaveRestore(PPC::R1);
826     setExceptionPointerRegister(PPC::R3);
827     setExceptionSelectorRegister(PPC::R4);
828   }
829
830   // We have target-specific dag combine patterns for the following nodes:
831   setTargetDAGCombine(ISD::SINT_TO_FP);
832   if (Subtarget.hasFPCVT())
833     setTargetDAGCombine(ISD::UINT_TO_FP);
834   setTargetDAGCombine(ISD::LOAD);
835   setTargetDAGCombine(ISD::STORE);
836   setTargetDAGCombine(ISD::BR_CC);
837   if (Subtarget.useCRBits())
838     setTargetDAGCombine(ISD::BRCOND);
839   setTargetDAGCombine(ISD::BSWAP);
840   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
841   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
842   setTargetDAGCombine(ISD::INTRINSIC_VOID);
843
844   setTargetDAGCombine(ISD::SIGN_EXTEND);
845   setTargetDAGCombine(ISD::ZERO_EXTEND);
846   setTargetDAGCombine(ISD::ANY_EXTEND);
847
848   if (Subtarget.useCRBits()) {
849     setTargetDAGCombine(ISD::TRUNCATE);
850     setTargetDAGCombine(ISD::SETCC);
851     setTargetDAGCombine(ISD::SELECT_CC);
852   }
853
854   // Use reciprocal estimates.
855   if (TM.Options.UnsafeFPMath) {
856     setTargetDAGCombine(ISD::FDIV);
857     setTargetDAGCombine(ISD::FSQRT);
858   }
859
860   // Darwin long double math library functions have $LDBL128 appended.
861   if (Subtarget.isDarwin()) {
862     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
863     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
864     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
865     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
866     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
867     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
868     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
869     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
870     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
871     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
872   }
873
874   // With 32 condition bits, we don't need to sink (and duplicate) compares
875   // aggressively in CodeGenPrep.
876   if (Subtarget.useCRBits()) {
877     setHasMultipleConditionRegisters();
878     setJumpIsExpensive();
879   }
880
881   setMinFunctionAlignment(2);
882   if (Subtarget.isDarwin())
883     setPrefFunctionAlignment(4);
884
885   switch (Subtarget.getDarwinDirective()) {
886   default: break;
887   case PPC::DIR_970:
888   case PPC::DIR_A2:
889   case PPC::DIR_E500mc:
890   case PPC::DIR_E5500:
891   case PPC::DIR_PWR4:
892   case PPC::DIR_PWR5:
893   case PPC::DIR_PWR5X:
894   case PPC::DIR_PWR6:
895   case PPC::DIR_PWR6X:
896   case PPC::DIR_PWR7:
897   case PPC::DIR_PWR8:
898     setPrefFunctionAlignment(4);
899     setPrefLoopAlignment(4);
900     break;
901   }
902
903   setInsertFencesForAtomic(true);
904
905   if (Subtarget.enableMachineScheduler())
906     setSchedulingPreference(Sched::Source);
907   else
908     setSchedulingPreference(Sched::Hybrid);
909
910   computeRegisterProperties(STI.getRegisterInfo());
911
912   // The Freescale cores do better with aggressive inlining of memcpy and
913   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
914   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
915       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
916     MaxStoresPerMemset = 32;
917     MaxStoresPerMemsetOptSize = 16;
918     MaxStoresPerMemcpy = 32;
919     MaxStoresPerMemcpyOptSize = 8;
920     MaxStoresPerMemmove = 32;
921     MaxStoresPerMemmoveOptSize = 8;
922   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
923     // The A2 also benefits from (very) aggressive inlining of memcpy and
924     // friends. The overhead of a the function call, even when warm, can be
925     // over one hundred cycles.
926     MaxStoresPerMemset = 128;
927     MaxStoresPerMemcpy = 128;
928     MaxStoresPerMemmove = 128;
929   }
930 }
931
932 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
933 /// the desired ByVal argument alignment.
934 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
935                              unsigned MaxMaxAlign) {
936   if (MaxAlign == MaxMaxAlign)
937     return;
938   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
939     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
940       MaxAlign = 32;
941     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
942       MaxAlign = 16;
943   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
944     unsigned EltAlign = 0;
945     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
946     if (EltAlign > MaxAlign)
947       MaxAlign = EltAlign;
948   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
949     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
950       unsigned EltAlign = 0;
951       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
952       if (EltAlign > MaxAlign)
953         MaxAlign = EltAlign;
954       if (MaxAlign == MaxMaxAlign)
955         break;
956     }
957   }
958 }
959
960 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
961 /// function arguments in the caller parameter area.
962 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
963   // Darwin passes everything on 4 byte boundary.
964   if (Subtarget.isDarwin())
965     return 4;
966
967   // 16byte and wider vectors are passed on 16byte boundary.
968   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
969   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
970   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
971     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
972   return Align;
973 }
974
975 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
976   switch ((PPCISD::NodeType)Opcode) {
977   case PPCISD::FIRST_NUMBER:    break;
978   case PPCISD::FSEL:            return "PPCISD::FSEL";
979   case PPCISD::FCFID:           return "PPCISD::FCFID";
980   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
981   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
982   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
983   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
984   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
985   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
986   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
987   case PPCISD::FRE:             return "PPCISD::FRE";
988   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
989   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
990   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
991   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
992   case PPCISD::VPERM:           return "PPCISD::VPERM";
993   case PPCISD::CMPB:            return "PPCISD::CMPB";
994   case PPCISD::Hi:              return "PPCISD::Hi";
995   case PPCISD::Lo:              return "PPCISD::Lo";
996   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
997   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
998   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
999   case PPCISD::SRL:             return "PPCISD::SRL";
1000   case PPCISD::SRA:             return "PPCISD::SRA";
1001   case PPCISD::SHL:             return "PPCISD::SHL";
1002   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1003   case PPCISD::CALL:            return "PPCISD::CALL";
1004   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1005   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1006   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1007   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1008   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1009   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1010   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1011   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1012   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1013   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1014   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1015   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1016   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1017   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1018   case PPCISD::VCMP:            return "PPCISD::VCMP";
1019   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1020   case PPCISD::LBRX:            return "PPCISD::LBRX";
1021   case PPCISD::STBRX:           return "PPCISD::STBRX";
1022   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1023   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1024   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1025   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1026   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1027   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1028   case PPCISD::BDZ:             return "PPCISD::BDZ";
1029   case PPCISD::MFFS:            return "PPCISD::MFFS";
1030   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1031   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1032   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1033   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1034   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1035   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1036   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1037   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1038   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1039   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1040   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1041   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1042   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1043   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1044   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1045   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1046   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1047   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1048   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1049   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1050   case PPCISD::SC:              return "PPCISD::SC";
1051   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1052   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1053   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1054   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1055   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1056   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1057   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1058   }
1059   return nullptr;
1060 }
1061
1062 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1063   if (!VT.isVector())
1064     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1065
1066   if (Subtarget.hasQPX())
1067     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1068
1069   return VT.changeVectorElementTypeToInteger();
1070 }
1071
1072 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1073   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1074   return true;
1075 }
1076
1077 //===----------------------------------------------------------------------===//
1078 // Node matching predicates, for use by the tblgen matching code.
1079 //===----------------------------------------------------------------------===//
1080
1081 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1082 static bool isFloatingPointZero(SDValue Op) {
1083   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1084     return CFP->getValueAPF().isZero();
1085   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1086     // Maybe this has already been legalized into the constant pool?
1087     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1088       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1089         return CFP->getValueAPF().isZero();
1090   }
1091   return false;
1092 }
1093
1094 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1095 /// true if Op is undef or if it matches the specified value.
1096 static bool isConstantOrUndef(int Op, int Val) {
1097   return Op < 0 || Op == Val;
1098 }
1099
1100 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1101 /// VPKUHUM instruction.
1102 /// The ShuffleKind distinguishes between big-endian operations with
1103 /// two different inputs (0), either-endian operations with two identical
1104 /// inputs (1), and little-endian operations with two different inputs (2).
1105 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1106 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1107                                SelectionDAG &DAG) {
1108   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1109   if (ShuffleKind == 0) {
1110     if (IsLE)
1111       return false;
1112     for (unsigned i = 0; i != 16; ++i)
1113       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1114         return false;
1115   } else if (ShuffleKind == 2) {
1116     if (!IsLE)
1117       return false;
1118     for (unsigned i = 0; i != 16; ++i)
1119       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1120         return false;
1121   } else if (ShuffleKind == 1) {
1122     unsigned j = IsLE ? 0 : 1;
1123     for (unsigned i = 0; i != 8; ++i)
1124       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1125           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1126         return false;
1127   }
1128   return true;
1129 }
1130
1131 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1132 /// VPKUWUM instruction.
1133 /// The ShuffleKind distinguishes between big-endian operations with
1134 /// two different inputs (0), either-endian operations with two identical
1135 /// inputs (1), and little-endian operations with two different inputs (2).
1136 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1137 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1138                                SelectionDAG &DAG) {
1139   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1140   if (ShuffleKind == 0) {
1141     if (IsLE)
1142       return false;
1143     for (unsigned i = 0; i != 16; i += 2)
1144       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1145           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1146         return false;
1147   } else if (ShuffleKind == 2) {
1148     if (!IsLE)
1149       return false;
1150     for (unsigned i = 0; i != 16; i += 2)
1151       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1152           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1153         return false;
1154   } else if (ShuffleKind == 1) {
1155     unsigned j = IsLE ? 0 : 2;
1156     for (unsigned i = 0; i != 8; i += 2)
1157       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1158           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1159           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1160           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1161         return false;
1162   }
1163   return true;
1164 }
1165
1166 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1167 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1168 /// current subtarget.
1169 ///
1170 /// The ShuffleKind distinguishes between big-endian operations with
1171 /// two different inputs (0), either-endian operations with two identical
1172 /// inputs (1), and little-endian operations with two different inputs (2).
1173 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1174 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1175                                SelectionDAG &DAG) {
1176   const PPCSubtarget& Subtarget =
1177     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1178   if (!Subtarget.hasP8Vector())
1179     return false;
1180
1181   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1182   if (ShuffleKind == 0) {
1183     if (IsLE)
1184       return false;
1185     for (unsigned i = 0; i != 16; i += 4)
1186       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1187           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1188           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1189           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1190         return false;
1191   } else if (ShuffleKind == 2) {
1192     if (!IsLE)
1193       return false;
1194     for (unsigned i = 0; i != 16; i += 4)
1195       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1196           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1197           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1198           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1199         return false;
1200   } else if (ShuffleKind == 1) {
1201     unsigned j = IsLE ? 0 : 4;
1202     for (unsigned i = 0; i != 8; i += 4)
1203       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1204           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1205           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1206           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1207           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1208           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1209           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1210           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1211         return false;
1212   }
1213   return true;
1214 }
1215
1216 /// isVMerge - Common function, used to match vmrg* shuffles.
1217 ///
1218 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1219                      unsigned LHSStart, unsigned RHSStart) {
1220   if (N->getValueType(0) != MVT::v16i8)
1221     return false;
1222   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1223          "Unsupported merge size!");
1224
1225   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1226     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1227       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1228                              LHSStart+j+i*UnitSize) ||
1229           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1230                              RHSStart+j+i*UnitSize))
1231         return false;
1232     }
1233   return true;
1234 }
1235
1236 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1237 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1238 /// The ShuffleKind distinguishes between big-endian merges with two 
1239 /// different inputs (0), either-endian merges with two identical inputs (1),
1240 /// and little-endian merges with two different inputs (2).  For the latter,
1241 /// the input operands are swapped (see PPCInstrAltivec.td).
1242 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1243                              unsigned ShuffleKind, SelectionDAG &DAG) {
1244   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1245     if (ShuffleKind == 1) // unary
1246       return isVMerge(N, UnitSize, 0, 0);
1247     else if (ShuffleKind == 2) // swapped
1248       return isVMerge(N, UnitSize, 0, 16);
1249     else
1250       return false;
1251   } else {
1252     if (ShuffleKind == 1) // unary
1253       return isVMerge(N, UnitSize, 8, 8);
1254     else if (ShuffleKind == 0) // normal
1255       return isVMerge(N, UnitSize, 8, 24);
1256     else
1257       return false;
1258   }
1259 }
1260
1261 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1262 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1263 /// The ShuffleKind distinguishes between big-endian merges with two 
1264 /// different inputs (0), either-endian merges with two identical inputs (1),
1265 /// and little-endian merges with two different inputs (2).  For the latter,
1266 /// the input operands are swapped (see PPCInstrAltivec.td).
1267 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1268                              unsigned ShuffleKind, SelectionDAG &DAG) {
1269   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1270     if (ShuffleKind == 1) // unary
1271       return isVMerge(N, UnitSize, 8, 8);
1272     else if (ShuffleKind == 2) // swapped
1273       return isVMerge(N, UnitSize, 8, 24);
1274     else
1275       return false;
1276   } else {
1277     if (ShuffleKind == 1) // unary
1278       return isVMerge(N, UnitSize, 0, 0);
1279     else if (ShuffleKind == 0) // normal
1280       return isVMerge(N, UnitSize, 0, 16);
1281     else
1282       return false;
1283   }
1284 }
1285
1286
1287 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1288 /// amount, otherwise return -1.
1289 /// The ShuffleKind distinguishes between big-endian operations with two 
1290 /// different inputs (0), either-endian operations with two identical inputs
1291 /// (1), and little-endian operations with two different inputs (2).  For the
1292 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1293 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1294                              SelectionDAG &DAG) {
1295   if (N->getValueType(0) != MVT::v16i8)
1296     return -1;
1297
1298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1299
1300   // Find the first non-undef value in the shuffle mask.
1301   unsigned i;
1302   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1303     /*search*/;
1304
1305   if (i == 16) return -1;  // all undef.
1306
1307   // Otherwise, check to see if the rest of the elements are consecutively
1308   // numbered from this value.
1309   unsigned ShiftAmt = SVOp->getMaskElt(i);
1310   if (ShiftAmt < i) return -1;
1311
1312   ShiftAmt -= i;
1313   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1314
1315   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1316     // Check the rest of the elements to see if they are consecutive.
1317     for (++i; i != 16; ++i)
1318       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1319         return -1;
1320   } else if (ShuffleKind == 1) {
1321     // Check the rest of the elements to see if they are consecutive.
1322     for (++i; i != 16; ++i)
1323       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1324         return -1;
1325   } else
1326     return -1;
1327
1328   if (ShuffleKind == 2 && isLE)
1329     ShiftAmt = 16 - ShiftAmt;
1330
1331   return ShiftAmt;
1332 }
1333
1334 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1335 /// specifies a splat of a single element that is suitable for input to
1336 /// VSPLTB/VSPLTH/VSPLTW.
1337 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1338   assert(N->getValueType(0) == MVT::v16i8 &&
1339          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1340
1341   // This is a splat operation if each element of the permute is the same, and
1342   // if the value doesn't reference the second vector.
1343   unsigned ElementBase = N->getMaskElt(0);
1344
1345   // FIXME: Handle UNDEF elements too!
1346   if (ElementBase >= 16)
1347     return false;
1348
1349   // Check that the indices are consecutive, in the case of a multi-byte element
1350   // splatted with a v16i8 mask.
1351   for (unsigned i = 1; i != EltSize; ++i)
1352     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1353       return false;
1354
1355   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1356     if (N->getMaskElt(i) < 0) continue;
1357     for (unsigned j = 0; j != EltSize; ++j)
1358       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1359         return false;
1360   }
1361   return true;
1362 }
1363
1364 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1365 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1366 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1367                                 SelectionDAG &DAG) {
1368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1369   assert(isSplatShuffleMask(SVOp, EltSize));
1370   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1371     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1372   else
1373     return SVOp->getMaskElt(0) / EltSize;
1374 }
1375
1376 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1377 /// by using a vspltis[bhw] instruction of the specified element size, return
1378 /// the constant being splatted.  The ByteSize field indicates the number of
1379 /// bytes of each element [124] -> [bhw].
1380 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1381   SDValue OpVal(nullptr, 0);
1382
1383   // If ByteSize of the splat is bigger than the element size of the
1384   // build_vector, then we have a case where we are checking for a splat where
1385   // multiple elements of the buildvector are folded together into a single
1386   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1387   unsigned EltSize = 16/N->getNumOperands();
1388   if (EltSize < ByteSize) {
1389     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1390     SDValue UniquedVals[4];
1391     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1392
1393     // See if all of the elements in the buildvector agree across.
1394     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1395       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1396       // If the element isn't a constant, bail fully out.
1397       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1398
1399
1400       if (!UniquedVals[i&(Multiple-1)].getNode())
1401         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1402       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1403         return SDValue();  // no match.
1404     }
1405
1406     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1407     // either constant or undef values that are identical for each chunk.  See
1408     // if these chunks can form into a larger vspltis*.
1409
1410     // Check to see if all of the leading entries are either 0 or -1.  If
1411     // neither, then this won't fit into the immediate field.
1412     bool LeadingZero = true;
1413     bool LeadingOnes = true;
1414     for (unsigned i = 0; i != Multiple-1; ++i) {
1415       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1416
1417       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1418       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1419     }
1420     // Finally, check the least significant entry.
1421     if (LeadingZero) {
1422       if (!UniquedVals[Multiple-1].getNode())
1423         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1424       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1425       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1426         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1427     }
1428     if (LeadingOnes) {
1429       if (!UniquedVals[Multiple-1].getNode())
1430         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1431       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1432       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1433         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1434     }
1435
1436     return SDValue();
1437   }
1438
1439   // Check to see if this buildvec has a single non-undef value in its elements.
1440   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1441     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1442     if (!OpVal.getNode())
1443       OpVal = N->getOperand(i);
1444     else if (OpVal != N->getOperand(i))
1445       return SDValue();
1446   }
1447
1448   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1449
1450   unsigned ValSizeInBytes = EltSize;
1451   uint64_t Value = 0;
1452   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1453     Value = CN->getZExtValue();
1454   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1455     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1456     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1457   }
1458
1459   // If the splat value is larger than the element value, then we can never do
1460   // this splat.  The only case that we could fit the replicated bits into our
1461   // immediate field for would be zero, and we prefer to use vxor for it.
1462   if (ValSizeInBytes < ByteSize) return SDValue();
1463
1464   // If the element value is larger than the splat value, check if it consists
1465   // of a repeated bit pattern of size ByteSize.
1466   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1467     return SDValue();
1468
1469   // Properly sign extend the value.
1470   int MaskVal = SignExtend32(Value, ByteSize * 8);
1471
1472   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1473   if (MaskVal == 0) return SDValue();
1474
1475   // Finally, if this value fits in a 5 bit sext field, return it
1476   if (SignExtend32<5>(MaskVal) == MaskVal)
1477     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1478   return SDValue();
1479 }
1480
1481 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1482 /// amount, otherwise return -1.
1483 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1484   EVT VT = N->getValueType(0);
1485   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1486     return -1;
1487
1488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1489
1490   // Find the first non-undef value in the shuffle mask.
1491   unsigned i;
1492   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1493     /*search*/;
1494
1495   if (i == 4) return -1;  // all undef.
1496
1497   // Otherwise, check to see if the rest of the elements are consecutively
1498   // numbered from this value.
1499   unsigned ShiftAmt = SVOp->getMaskElt(i);
1500   if (ShiftAmt < i) return -1;
1501   ShiftAmt -= i;
1502
1503   // Check the rest of the elements to see if they are consecutive.
1504   for (++i; i != 4; ++i)
1505     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1506       return -1;
1507
1508   return ShiftAmt;
1509 }
1510
1511 //===----------------------------------------------------------------------===//
1512 //  Addressing Mode Selection
1513 //===----------------------------------------------------------------------===//
1514
1515 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1516 /// or 64-bit immediate, and if the value can be accurately represented as a
1517 /// sign extension from a 16-bit value.  If so, this returns true and the
1518 /// immediate.
1519 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1520   if (!isa<ConstantSDNode>(N))
1521     return false;
1522
1523   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1524   if (N->getValueType(0) == MVT::i32)
1525     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1526   else
1527     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1528 }
1529 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1530   return isIntS16Immediate(Op.getNode(), Imm);
1531 }
1532
1533
1534 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1535 /// can be represented as an indexed [r+r] operation.  Returns false if it
1536 /// can be more efficiently represented with [r+imm].
1537 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1538                                             SDValue &Index,
1539                                             SelectionDAG &DAG) const {
1540   short imm = 0;
1541   if (N.getOpcode() == ISD::ADD) {
1542     if (isIntS16Immediate(N.getOperand(1), imm))
1543       return false;    // r+i
1544     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1545       return false;    // r+i
1546
1547     Base = N.getOperand(0);
1548     Index = N.getOperand(1);
1549     return true;
1550   } else if (N.getOpcode() == ISD::OR) {
1551     if (isIntS16Immediate(N.getOperand(1), imm))
1552       return false;    // r+i can fold it if we can.
1553
1554     // If this is an or of disjoint bitfields, we can codegen this as an add
1555     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1556     // disjoint.
1557     APInt LHSKnownZero, LHSKnownOne;
1558     APInt RHSKnownZero, RHSKnownOne;
1559     DAG.computeKnownBits(N.getOperand(0),
1560                          LHSKnownZero, LHSKnownOne);
1561
1562     if (LHSKnownZero.getBoolValue()) {
1563       DAG.computeKnownBits(N.getOperand(1),
1564                            RHSKnownZero, RHSKnownOne);
1565       // If all of the bits are known zero on the LHS or RHS, the add won't
1566       // carry.
1567       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1568         Base = N.getOperand(0);
1569         Index = N.getOperand(1);
1570         return true;
1571       }
1572     }
1573   }
1574
1575   return false;
1576 }
1577
1578 // If we happen to be doing an i64 load or store into a stack slot that has
1579 // less than a 4-byte alignment, then the frame-index elimination may need to
1580 // use an indexed load or store instruction (because the offset may not be a
1581 // multiple of 4). The extra register needed to hold the offset comes from the
1582 // register scavenger, and it is possible that the scavenger will need to use
1583 // an emergency spill slot. As a result, we need to make sure that a spill slot
1584 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1585 // stack slot.
1586 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1587   // FIXME: This does not handle the LWA case.
1588   if (VT != MVT::i64)
1589     return;
1590
1591   // NOTE: We'll exclude negative FIs here, which come from argument
1592   // lowering, because there are no known test cases triggering this problem
1593   // using packed structures (or similar). We can remove this exclusion if
1594   // we find such a test case. The reason why this is so test-case driven is
1595   // because this entire 'fixup' is only to prevent crashes (from the
1596   // register scavenger) on not-really-valid inputs. For example, if we have:
1597   //   %a = alloca i1
1598   //   %b = bitcast i1* %a to i64*
1599   //   store i64* a, i64 b
1600   // then the store should really be marked as 'align 1', but is not. If it
1601   // were marked as 'align 1' then the indexed form would have been
1602   // instruction-selected initially, and the problem this 'fixup' is preventing
1603   // won't happen regardless.
1604   if (FrameIdx < 0)
1605     return;
1606
1607   MachineFunction &MF = DAG.getMachineFunction();
1608   MachineFrameInfo *MFI = MF.getFrameInfo();
1609
1610   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1611   if (Align >= 4)
1612     return;
1613
1614   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1615   FuncInfo->setHasNonRISpills();
1616 }
1617
1618 /// Returns true if the address N can be represented by a base register plus
1619 /// a signed 16-bit displacement [r+imm], and if it is not better
1620 /// represented as reg+reg.  If Aligned is true, only accept displacements
1621 /// suitable for STD and friends, i.e. multiples of 4.
1622 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1623                                             SDValue &Base,
1624                                             SelectionDAG &DAG,
1625                                             bool Aligned) const {
1626   // FIXME dl should come from parent load or store, not from address
1627   SDLoc dl(N);
1628   // If this can be more profitably realized as r+r, fail.
1629   if (SelectAddressRegReg(N, Disp, Base, DAG))
1630     return false;
1631
1632   if (N.getOpcode() == ISD::ADD) {
1633     short imm = 0;
1634     if (isIntS16Immediate(N.getOperand(1), imm) &&
1635         (!Aligned || (imm & 3) == 0)) {
1636       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1637       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1638         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1639         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1640       } else {
1641         Base = N.getOperand(0);
1642       }
1643       return true; // [r+i]
1644     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1645       // Match LOAD (ADD (X, Lo(G))).
1646       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1647              && "Cannot handle constant offsets yet!");
1648       Disp = N.getOperand(1).getOperand(0);  // The global address.
1649       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1650              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1651              Disp.getOpcode() == ISD::TargetConstantPool ||
1652              Disp.getOpcode() == ISD::TargetJumpTable);
1653       Base = N.getOperand(0);
1654       return true;  // [&g+r]
1655     }
1656   } else if (N.getOpcode() == ISD::OR) {
1657     short imm = 0;
1658     if (isIntS16Immediate(N.getOperand(1), imm) &&
1659         (!Aligned || (imm & 3) == 0)) {
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
1662       // provably disjoint.
1663       APInt LHSKnownZero, LHSKnownOne;
1664       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1665
1666       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1667         // If all of the bits are known zero on the LHS or RHS, the add won't
1668         // carry.
1669         if (FrameIndexSDNode *FI =
1670               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1671           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1672           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1673         } else {
1674           Base = N.getOperand(0);
1675         }
1676         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1677         return true;
1678       }
1679     }
1680   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1681     // Loading from a constant address.
1682
1683     // If this address fits entirely in a 16-bit sext immediate field, codegen
1684     // this as "d, 0"
1685     short Imm;
1686     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1687       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1688       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1689                              CN->getValueType(0));
1690       return true;
1691     }
1692
1693     // Handle 32-bit sext immediates with LIS + addr mode.
1694     if ((CN->getValueType(0) == MVT::i32 ||
1695          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1696         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1697       int Addr = (int)CN->getZExtValue();
1698
1699       // Otherwise, break this down into an LIS + disp.
1700       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1701
1702       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1703                                    MVT::i32);
1704       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1705       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1706       return true;
1707     }
1708   }
1709
1710   Disp = DAG.getTargetConstant(0, dl, getPointerTy());
1711   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1712     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1713     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1714   } else
1715     Base = N;
1716   return true;      // [r+0]
1717 }
1718
1719 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1720 /// represented as an indexed [r+r] operation.
1721 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1722                                                 SDValue &Index,
1723                                                 SelectionDAG &DAG) const {
1724   // Check to see if we can easily represent this as an [r+r] address.  This
1725   // will fail if it thinks that the address is more profitably represented as
1726   // reg+imm, e.g. where imm = 0.
1727   if (SelectAddressRegReg(N, Base, Index, DAG))
1728     return true;
1729
1730   // If the operand is an addition, always emit this as [r+r], since this is
1731   // better (for code size, and execution, as the memop does the add for free)
1732   // than emitting an explicit add.
1733   if (N.getOpcode() == ISD::ADD) {
1734     Base = N.getOperand(0);
1735     Index = N.getOperand(1);
1736     return true;
1737   }
1738
1739   // Otherwise, do it the hard way, using R0 as the base register.
1740   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1741                          N.getValueType());
1742   Index = N;
1743   return true;
1744 }
1745
1746 /// getPreIndexedAddressParts - returns true by value, base pointer and
1747 /// offset pointer and addressing mode by reference if the node's address
1748 /// can be legally represented as pre-indexed load / store address.
1749 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1750                                                   SDValue &Offset,
1751                                                   ISD::MemIndexedMode &AM,
1752                                                   SelectionDAG &DAG) const {
1753   if (DisablePPCPreinc) return false;
1754
1755   bool isLoad = true;
1756   SDValue Ptr;
1757   EVT VT;
1758   unsigned Alignment;
1759   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1760     Ptr = LD->getBasePtr();
1761     VT = LD->getMemoryVT();
1762     Alignment = LD->getAlignment();
1763   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1764     Ptr = ST->getBasePtr();
1765     VT  = ST->getMemoryVT();
1766     Alignment = ST->getAlignment();
1767     isLoad = false;
1768   } else
1769     return false;
1770
1771   // PowerPC doesn't have preinc load/store instructions for vectors (except
1772   // for QPX, which does have preinc r+r forms).
1773   if (VT.isVector()) {
1774     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1775       return false;
1776     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1777       AM = ISD::PRE_INC;
1778       return true;
1779     }
1780   }
1781
1782   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1783
1784     // Common code will reject creating a pre-inc form if the base pointer
1785     // is a frame index, or if N is a store and the base pointer is either
1786     // the same as or a predecessor of the value being stored.  Check for
1787     // those situations here, and try with swapped Base/Offset instead.
1788     bool Swap = false;
1789
1790     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1791       Swap = true;
1792     else if (!isLoad) {
1793       SDValue Val = cast<StoreSDNode>(N)->getValue();
1794       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1795         Swap = true;
1796     }
1797
1798     if (Swap)
1799       std::swap(Base, Offset);
1800
1801     AM = ISD::PRE_INC;
1802     return true;
1803   }
1804
1805   // LDU/STU can only handle immediates that are a multiple of 4.
1806   if (VT != MVT::i64) {
1807     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1808       return false;
1809   } else {
1810     // LDU/STU need an address with at least 4-byte alignment.
1811     if (Alignment < 4)
1812       return false;
1813
1814     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1815       return false;
1816   }
1817
1818   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1819     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1820     // sext i32 to i64 when addr mode is r+i.
1821     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1822         LD->getExtensionType() == ISD::SEXTLOAD &&
1823         isa<ConstantSDNode>(Offset))
1824       return false;
1825   }
1826
1827   AM = ISD::PRE_INC;
1828   return true;
1829 }
1830
1831 //===----------------------------------------------------------------------===//
1832 //  LowerOperation implementation
1833 //===----------------------------------------------------------------------===//
1834
1835 /// GetLabelAccessInfo - Return true if we should reference labels using a
1836 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1837 static bool GetLabelAccessInfo(const TargetMachine &TM,
1838                                const PPCSubtarget &Subtarget,
1839                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1840                                const GlobalValue *GV = nullptr) {
1841   HiOpFlags = PPCII::MO_HA;
1842   LoOpFlags = PPCII::MO_LO;
1843
1844   // Don't use the pic base if not in PIC relocation model.
1845   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1846
1847   if (isPIC) {
1848     HiOpFlags |= PPCII::MO_PIC_FLAG;
1849     LoOpFlags |= PPCII::MO_PIC_FLAG;
1850   }
1851
1852   // If this is a reference to a global value that requires a non-lazy-ptr, make
1853   // sure that instruction lowering adds it.
1854   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1855     HiOpFlags |= PPCII::MO_NLP_FLAG;
1856     LoOpFlags |= PPCII::MO_NLP_FLAG;
1857
1858     if (GV->hasHiddenVisibility()) {
1859       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1860       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1861     }
1862   }
1863
1864   return isPIC;
1865 }
1866
1867 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1868                              SelectionDAG &DAG) {
1869   SDLoc DL(HiPart);
1870   EVT PtrVT = HiPart.getValueType();
1871   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1872
1873   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1874   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1875
1876   // With PIC, the first instruction is actually "GR+hi(&G)".
1877   if (isPIC)
1878     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1879                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1880
1881   // Generate non-pic code that has direct accesses to the constant pool.
1882   // The address of the global is just (hi(&g)+lo(&g)).
1883   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1884 }
1885
1886 static void setUsesTOCBasePtr(MachineFunction &MF) {
1887   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1888   FuncInfo->setUsesTOCBasePtr();
1889 }
1890
1891 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1892   setUsesTOCBasePtr(DAG.getMachineFunction());
1893 }
1894
1895 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1896                            SDValue GA) {
1897   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1898   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1899                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1900
1901   SDValue Ops[] = { GA, Reg };
1902   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1903                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1904                                  MachinePointerInfo::getGOT(), 0, false, true,
1905                                  false, 0);
1906 }
1907
1908 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1909                                              SelectionDAG &DAG) const {
1910   EVT PtrVT = Op.getValueType();
1911   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1912   const Constant *C = CP->getConstVal();
1913
1914   // 64-bit SVR4 ABI code is always position-independent.
1915   // The actual address of the GlobalValue is stored in the TOC.
1916   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1917     setUsesTOCBasePtr(DAG);
1918     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1919     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1920   }
1921
1922   unsigned MOHiFlag, MOLoFlag;
1923   bool isPIC =
1924       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1925
1926   if (isPIC && Subtarget.isSVR4ABI()) {
1927     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1928                                            PPCII::MO_PIC_FLAG);
1929     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1930   }
1931
1932   SDValue CPIHi =
1933     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1934   SDValue CPILo =
1935     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1936   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1937 }
1938
1939 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1940   EVT PtrVT = Op.getValueType();
1941   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1942
1943   // 64-bit SVR4 ABI code is always position-independent.
1944   // The actual address of the GlobalValue is stored in the TOC.
1945   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1946     setUsesTOCBasePtr(DAG);
1947     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1948     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1949   }
1950
1951   unsigned MOHiFlag, MOLoFlag;
1952   bool isPIC =
1953       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1954
1955   if (isPIC && Subtarget.isSVR4ABI()) {
1956     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1957                                         PPCII::MO_PIC_FLAG);
1958     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1959   }
1960
1961   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1962   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1963   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1964 }
1965
1966 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1967                                              SelectionDAG &DAG) const {
1968   EVT PtrVT = Op.getValueType();
1969   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1970   const BlockAddress *BA = BASDN->getBlockAddress();
1971
1972   // 64-bit SVR4 ABI code is always position-independent.
1973   // The actual BlockAddress is stored in the TOC.
1974   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1975     setUsesTOCBasePtr(DAG);
1976     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1977     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1978   }
1979
1980   unsigned MOHiFlag, MOLoFlag;
1981   bool isPIC =
1982       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1983   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1984   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1985   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1986 }
1987
1988 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1989                                               SelectionDAG &DAG) const {
1990
1991   // FIXME: TLS addresses currently use medium model code sequences,
1992   // which is the most useful form.  Eventually support for small and
1993   // large models could be added if users need it, at the cost of
1994   // additional complexity.
1995   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1996   SDLoc dl(GA);
1997   const GlobalValue *GV = GA->getGlobal();
1998   EVT PtrVT = getPointerTy();
1999   bool is64bit = Subtarget.isPPC64();
2000   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2001   PICLevel::Level picLevel = M->getPICLevel();
2002
2003   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2004
2005   if (Model == TLSModel::LocalExec) {
2006     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2007                                                PPCII::MO_TPREL_HA);
2008     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2009                                                PPCII::MO_TPREL_LO);
2010     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2011                                      is64bit ? MVT::i64 : MVT::i32);
2012     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2013     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2014   }
2015
2016   if (Model == TLSModel::InitialExec) {
2017     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2018     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2019                                                 PPCII::MO_TLS);
2020     SDValue GOTPtr;
2021     if (is64bit) {
2022       setUsesTOCBasePtr(DAG);
2023       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2024       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2025                            PtrVT, GOTReg, TGA);
2026     } else
2027       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2028     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2029                                    PtrVT, TGA, GOTPtr);
2030     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2031   }
2032
2033   if (Model == TLSModel::GeneralDynamic) {
2034     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2035     SDValue GOTPtr;
2036     if (is64bit) {
2037       setUsesTOCBasePtr(DAG);
2038       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2039       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2040                                    GOTReg, TGA);
2041     } else {
2042       if (picLevel == PICLevel::Small)
2043         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2044       else
2045         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2046     }
2047     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2048                        GOTPtr, TGA, TGA);
2049   }
2050
2051   if (Model == TLSModel::LocalDynamic) {
2052     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2053     SDValue GOTPtr;
2054     if (is64bit) {
2055       setUsesTOCBasePtr(DAG);
2056       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2057       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2058                            GOTReg, TGA);
2059     } else {
2060       if (picLevel == PICLevel::Small)
2061         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2062       else
2063         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2064     }
2065     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2066                                   PtrVT, GOTPtr, TGA, TGA);
2067     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2068                                       PtrVT, TLSAddr, TGA);
2069     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2070   }
2071
2072   llvm_unreachable("Unknown TLS model!");
2073 }
2074
2075 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2076                                               SelectionDAG &DAG) const {
2077   EVT PtrVT = Op.getValueType();
2078   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2079   SDLoc DL(GSDN);
2080   const GlobalValue *GV = GSDN->getGlobal();
2081
2082   // 64-bit SVR4 ABI code is always position-independent.
2083   // The actual address of the GlobalValue is stored in the TOC.
2084   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2085     setUsesTOCBasePtr(DAG);
2086     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2087     return getTOCEntry(DAG, DL, true, GA);
2088   }
2089
2090   unsigned MOHiFlag, MOLoFlag;
2091   bool isPIC =
2092       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2093
2094   if (isPIC && Subtarget.isSVR4ABI()) {
2095     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2096                                             GSDN->getOffset(),
2097                                             PPCII::MO_PIC_FLAG);
2098     return getTOCEntry(DAG, DL, false, GA);
2099   }
2100
2101   SDValue GAHi =
2102     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2103   SDValue GALo =
2104     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2105
2106   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2107
2108   // If the global reference is actually to a non-lazy-pointer, we have to do an
2109   // extra load to get the address of the global.
2110   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2111     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2112                       false, false, false, 0);
2113   return Ptr;
2114 }
2115
2116 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2117   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2118   SDLoc dl(Op);
2119
2120   if (Op.getValueType() == MVT::v2i64) {
2121     // When the operands themselves are v2i64 values, we need to do something
2122     // special because VSX has no underlying comparison operations for these.
2123     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2124       // Equality can be handled by casting to the legal type for Altivec
2125       // comparisons, everything else needs to be expanded.
2126       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2127         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2128                  DAG.getSetCC(dl, MVT::v4i32,
2129                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2130                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2131                    CC));
2132       }
2133
2134       return SDValue();
2135     }
2136
2137     // We handle most of these in the usual way.
2138     return Op;
2139   }
2140
2141   // If we're comparing for equality to zero, expose the fact that this is
2142   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2143   // fold the new nodes.
2144   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2145     if (C->isNullValue() && CC == ISD::SETEQ) {
2146       EVT VT = Op.getOperand(0).getValueType();
2147       SDValue Zext = Op.getOperand(0);
2148       if (VT.bitsLT(MVT::i32)) {
2149         VT = MVT::i32;
2150         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2151       }
2152       unsigned Log2b = Log2_32(VT.getSizeInBits());
2153       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2154       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2155                                 DAG.getConstant(Log2b, dl, MVT::i32));
2156       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2157     }
2158     // Leave comparisons against 0 and -1 alone for now, since they're usually
2159     // optimized.  FIXME: revisit this when we can custom lower all setcc
2160     // optimizations.
2161     if (C->isAllOnesValue() || C->isNullValue())
2162       return SDValue();
2163   }
2164
2165   // If we have an integer seteq/setne, turn it into a compare against zero
2166   // by xor'ing the rhs with the lhs, which is faster than setting a
2167   // condition register, reading it back out, and masking the correct bit.  The
2168   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2169   // the result to other bit-twiddling opportunities.
2170   EVT LHSVT = Op.getOperand(0).getValueType();
2171   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2172     EVT VT = Op.getValueType();
2173     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2174                                 Op.getOperand(1));
2175     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2176   }
2177   return SDValue();
2178 }
2179
2180 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2181                                       const PPCSubtarget &Subtarget) const {
2182   SDNode *Node = Op.getNode();
2183   EVT VT = Node->getValueType(0);
2184   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2185   SDValue InChain = Node->getOperand(0);
2186   SDValue VAListPtr = Node->getOperand(1);
2187   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2188   SDLoc dl(Node);
2189
2190   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2191
2192   // gpr_index
2193   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2194                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2195                                     false, false, false, 0);
2196   InChain = GprIndex.getValue(1);
2197
2198   if (VT == MVT::i64) {
2199     // Check if GprIndex is even
2200     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2201                                  DAG.getConstant(1, dl, MVT::i32));
2202     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2203                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2204     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2205                                           DAG.getConstant(1, dl, MVT::i32));
2206     // Align GprIndex to be even if it isn't
2207     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2208                            GprIndex);
2209   }
2210
2211   // fpr index is 1 byte after gpr
2212   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2213                                DAG.getConstant(1, dl, MVT::i32));
2214
2215   // fpr
2216   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2217                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2218                                     false, false, false, 0);
2219   InChain = FprIndex.getValue(1);
2220
2221   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2222                                        DAG.getConstant(8, dl, MVT::i32));
2223
2224   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2225                                         DAG.getConstant(4, dl, MVT::i32));
2226
2227   // areas
2228   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2229                                      MachinePointerInfo(), false, false,
2230                                      false, 0);
2231   InChain = OverflowArea.getValue(1);
2232
2233   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2234                                     MachinePointerInfo(), false, false,
2235                                     false, 0);
2236   InChain = RegSaveArea.getValue(1);
2237
2238   // select overflow_area if index > 8
2239   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2240                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2241
2242   // adjustment constant gpr_index * 4/8
2243   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2244                                     VT.isInteger() ? GprIndex : FprIndex,
2245                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2246                                                     MVT::i32));
2247
2248   // OurReg = RegSaveArea + RegConstant
2249   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2250                                RegConstant);
2251
2252   // Floating types are 32 bytes into RegSaveArea
2253   if (VT.isFloatingPoint())
2254     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2255                          DAG.getConstant(32, dl, MVT::i32));
2256
2257   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2258   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2259                                    VT.isInteger() ? GprIndex : FprIndex,
2260                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2261                                                    MVT::i32));
2262
2263   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2264                               VT.isInteger() ? VAListPtr : FprPtr,
2265                               MachinePointerInfo(SV),
2266                               MVT::i8, false, false, 0);
2267
2268   // determine if we should load from reg_save_area or overflow_area
2269   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2270
2271   // increase overflow_area by 4/8 if gpr/fpr > 8
2272   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2273                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2274                                           dl, MVT::i32));
2275
2276   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2277                              OverflowAreaPlusN);
2278
2279   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2280                               OverflowAreaPtr,
2281                               MachinePointerInfo(),
2282                               MVT::i32, false, false, 0);
2283
2284   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2285                      false, false, false, 0);
2286 }
2287
2288 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2289                                        const PPCSubtarget &Subtarget) const {
2290   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2291
2292   // We have to copy the entire va_list struct:
2293   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2294   return DAG.getMemcpy(Op.getOperand(0), Op,
2295                        Op.getOperand(1), Op.getOperand(2),
2296                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2297                        false, MachinePointerInfo(), MachinePointerInfo());
2298 }
2299
2300 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2301                                                   SelectionDAG &DAG) const {
2302   return Op.getOperand(0);
2303 }
2304
2305 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2306                                                 SelectionDAG &DAG) const {
2307   SDValue Chain = Op.getOperand(0);
2308   SDValue Trmp = Op.getOperand(1); // trampoline
2309   SDValue FPtr = Op.getOperand(2); // nested function
2310   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2311   SDLoc dl(Op);
2312
2313   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2314   bool isPPC64 = (PtrVT == MVT::i64);
2315   Type *IntPtrTy =
2316     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2317                                                              *DAG.getContext());
2318
2319   TargetLowering::ArgListTy Args;
2320   TargetLowering::ArgListEntry Entry;
2321
2322   Entry.Ty = IntPtrTy;
2323   Entry.Node = Trmp; Args.push_back(Entry);
2324
2325   // TrampSize == (isPPC64 ? 48 : 40);
2326   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2327                                isPPC64 ? MVT::i64 : MVT::i32);
2328   Args.push_back(Entry);
2329
2330   Entry.Node = FPtr; Args.push_back(Entry);
2331   Entry.Node = Nest; Args.push_back(Entry);
2332
2333   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2334   TargetLowering::CallLoweringInfo CLI(DAG);
2335   CLI.setDebugLoc(dl).setChain(Chain)
2336     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2337                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2338                std::move(Args), 0);
2339
2340   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2341   return CallResult.second;
2342 }
2343
2344 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2345                                         const PPCSubtarget &Subtarget) const {
2346   MachineFunction &MF = DAG.getMachineFunction();
2347   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2348
2349   SDLoc dl(Op);
2350
2351   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2352     // vastart just stores the address of the VarArgsFrameIndex slot into the
2353     // memory location argument.
2354     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2355     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2356     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2357     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2358                         MachinePointerInfo(SV),
2359                         false, false, 0);
2360   }
2361
2362   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2363   // We suppose the given va_list is already allocated.
2364   //
2365   // typedef struct {
2366   //  char gpr;     /* index into the array of 8 GPRs
2367   //                 * stored in the register save area
2368   //                 * gpr=0 corresponds to r3,
2369   //                 * gpr=1 to r4, etc.
2370   //                 */
2371   //  char fpr;     /* index into the array of 8 FPRs
2372   //                 * stored in the register save area
2373   //                 * fpr=0 corresponds to f1,
2374   //                 * fpr=1 to f2, etc.
2375   //                 */
2376   //  char *overflow_arg_area;
2377   //                /* location on stack that holds
2378   //                 * the next overflow argument
2379   //                 */
2380   //  char *reg_save_area;
2381   //               /* where r3:r10 and f1:f8 (if saved)
2382   //                * are stored
2383   //                */
2384   // } va_list[1];
2385
2386
2387   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2388   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2389
2390
2391   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2392
2393   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2394                                             PtrVT);
2395   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2396                                  PtrVT);
2397
2398   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2399   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2400
2401   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2402   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2403
2404   uint64_t FPROffset = 1;
2405   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2406
2407   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2408
2409   // Store first byte : number of int regs
2410   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2411                                          Op.getOperand(1),
2412                                          MachinePointerInfo(SV),
2413                                          MVT::i8, false, false, 0);
2414   uint64_t nextOffset = FPROffset;
2415   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2416                                   ConstFPROffset);
2417
2418   // Store second byte : number of float regs
2419   SDValue secondStore =
2420     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2421                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2422                       false, false, 0);
2423   nextOffset += StackOffset;
2424   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2425
2426   // Store second word : arguments given on stack
2427   SDValue thirdStore =
2428     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2429                  MachinePointerInfo(SV, nextOffset),
2430                  false, false, 0);
2431   nextOffset += FrameOffset;
2432   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2433
2434   // Store third word : arguments given in registers
2435   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2436                       MachinePointerInfo(SV, nextOffset),
2437                       false, false, 0);
2438
2439 }
2440
2441 #include "PPCGenCallingConv.inc"
2442
2443 // Function whose sole purpose is to kill compiler warnings 
2444 // stemming from unused functions included from PPCGenCallingConv.inc.
2445 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2446   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2447 }
2448
2449 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2450                                       CCValAssign::LocInfo &LocInfo,
2451                                       ISD::ArgFlagsTy &ArgFlags,
2452                                       CCState &State) {
2453   return true;
2454 }
2455
2456 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2457                                              MVT &LocVT,
2458                                              CCValAssign::LocInfo &LocInfo,
2459                                              ISD::ArgFlagsTy &ArgFlags,
2460                                              CCState &State) {
2461   static const MCPhysReg ArgRegs[] = {
2462     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2463     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2464   };
2465   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2466
2467   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2468
2469   // Skip one register if the first unallocated register has an even register
2470   // number and there are still argument registers available which have not been
2471   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2472   // need to skip a register if RegNum is odd.
2473   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2474     State.AllocateReg(ArgRegs[RegNum]);
2475   }
2476
2477   // Always return false here, as this function only makes sure that the first
2478   // unallocated register has an odd register number and does not actually
2479   // allocate a register for the current argument.
2480   return false;
2481 }
2482
2483 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2484                                                MVT &LocVT,
2485                                                CCValAssign::LocInfo &LocInfo,
2486                                                ISD::ArgFlagsTy &ArgFlags,
2487                                                CCState &State) {
2488   static const MCPhysReg ArgRegs[] = {
2489     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2490     PPC::F8
2491   };
2492
2493   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2494
2495   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2496
2497   // If there is only one Floating-point register left we need to put both f64
2498   // values of a split ppc_fp128 value on the stack.
2499   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2500     State.AllocateReg(ArgRegs[RegNum]);
2501   }
2502
2503   // Always return false here, as this function only makes sure that the two f64
2504   // values a ppc_fp128 value is split into are both passed in registers or both
2505   // passed on the stack and does not actually allocate a register for the
2506   // current argument.
2507   return false;
2508 }
2509
2510 /// FPR - The set of FP registers that should be allocated for arguments,
2511 /// on Darwin.
2512 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2513                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2514                                 PPC::F11, PPC::F12, PPC::F13};
2515
2516 /// QFPR - The set of QPX registers that should be allocated for arguments.
2517 static const MCPhysReg QFPR[] = {
2518     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2519     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2520
2521 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2522 /// the stack.
2523 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2524                                        unsigned PtrByteSize) {
2525   unsigned ArgSize = ArgVT.getStoreSize();
2526   if (Flags.isByVal())
2527     ArgSize = Flags.getByValSize();
2528
2529   // Round up to multiples of the pointer size, except for array members,
2530   // which are always packed.
2531   if (!Flags.isInConsecutiveRegs())
2532     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2533
2534   return ArgSize;
2535 }
2536
2537 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2538 /// on the stack.
2539 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2540                                             ISD::ArgFlagsTy Flags,
2541                                             unsigned PtrByteSize) {
2542   unsigned Align = PtrByteSize;
2543
2544   // Altivec parameters are padded to a 16 byte boundary.
2545   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2546       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2547       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2548       ArgVT == MVT::v1i128)
2549     Align = 16;
2550   // QPX vector types stored in double-precision are padded to a 32 byte
2551   // boundary.
2552   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2553     Align = 32;
2554
2555   // ByVal parameters are aligned as requested.
2556   if (Flags.isByVal()) {
2557     unsigned BVAlign = Flags.getByValAlign();
2558     if (BVAlign > PtrByteSize) {
2559       if (BVAlign % PtrByteSize != 0)
2560           llvm_unreachable(
2561             "ByVal alignment is not a multiple of the pointer size");
2562
2563       Align = BVAlign;
2564     }
2565   }
2566
2567   // Array members are always packed to their original alignment.
2568   if (Flags.isInConsecutiveRegs()) {
2569     // If the array member was split into multiple registers, the first
2570     // needs to be aligned to the size of the full type.  (Except for
2571     // ppcf128, which is only aligned as its f64 components.)
2572     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2573       Align = OrigVT.getStoreSize();
2574     else
2575       Align = ArgVT.getStoreSize();
2576   }
2577
2578   return Align;
2579 }
2580
2581 /// CalculateStackSlotUsed - Return whether this argument will use its
2582 /// stack slot (instead of being passed in registers).  ArgOffset,
2583 /// AvailableFPRs, and AvailableVRs must hold the current argument
2584 /// position, and will be updated to account for this argument.
2585 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2586                                    ISD::ArgFlagsTy Flags,
2587                                    unsigned PtrByteSize,
2588                                    unsigned LinkageSize,
2589                                    unsigned ParamAreaSize,
2590                                    unsigned &ArgOffset,
2591                                    unsigned &AvailableFPRs,
2592                                    unsigned &AvailableVRs, bool HasQPX) {
2593   bool UseMemory = false;
2594
2595   // Respect alignment of argument on the stack.
2596   unsigned Align =
2597     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2598   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2599   // If there's no space left in the argument save area, we must
2600   // use memory (this check also catches zero-sized arguments).
2601   if (ArgOffset >= LinkageSize + ParamAreaSize)
2602     UseMemory = true;
2603
2604   // Allocate argument on the stack.
2605   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2606   if (Flags.isInConsecutiveRegsLast())
2607     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2608   // If we overran the argument save area, we must use memory
2609   // (this check catches arguments passed partially in memory)
2610   if (ArgOffset > LinkageSize + ParamAreaSize)
2611     UseMemory = true;
2612
2613   // However, if the argument is actually passed in an FPR or a VR,
2614   // we don't use memory after all.
2615   if (!Flags.isByVal()) {
2616     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2617         // QPX registers overlap with the scalar FP registers.
2618         (HasQPX && (ArgVT == MVT::v4f32 ||
2619                     ArgVT == MVT::v4f64 ||
2620                     ArgVT == MVT::v4i1)))
2621       if (AvailableFPRs > 0) {
2622         --AvailableFPRs;
2623         return false;
2624       }
2625     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2626         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2627         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2628         ArgVT == MVT::v1i128)
2629       if (AvailableVRs > 0) {
2630         --AvailableVRs;
2631         return false;
2632       }
2633   }
2634
2635   return UseMemory;
2636 }
2637
2638 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2639 /// ensure minimum alignment required for target.
2640 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2641                                      unsigned NumBytes) {
2642   unsigned TargetAlign = Lowering->getStackAlignment();
2643   unsigned AlignMask = TargetAlign - 1;
2644   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2645   return NumBytes;
2646 }
2647
2648 SDValue
2649 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2650                                         CallingConv::ID CallConv, bool isVarArg,
2651                                         const SmallVectorImpl<ISD::InputArg>
2652                                           &Ins,
2653                                         SDLoc dl, SelectionDAG &DAG,
2654                                         SmallVectorImpl<SDValue> &InVals)
2655                                           const {
2656   if (Subtarget.isSVR4ABI()) {
2657     if (Subtarget.isPPC64())
2658       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2659                                          dl, DAG, InVals);
2660     else
2661       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2662                                          dl, DAG, InVals);
2663   } else {
2664     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2665                                        dl, DAG, InVals);
2666   }
2667 }
2668
2669 SDValue
2670 PPCTargetLowering::LowerFormalArguments_32SVR4(
2671                                       SDValue Chain,
2672                                       CallingConv::ID CallConv, bool isVarArg,
2673                                       const SmallVectorImpl<ISD::InputArg>
2674                                         &Ins,
2675                                       SDLoc dl, SelectionDAG &DAG,
2676                                       SmallVectorImpl<SDValue> &InVals) const {
2677
2678   // 32-bit SVR4 ABI Stack Frame Layout:
2679   //              +-----------------------------------+
2680   //        +-->  |            Back chain             |
2681   //        |     +-----------------------------------+
2682   //        |     | Floating-point register save area |
2683   //        |     +-----------------------------------+
2684   //        |     |    General register save area     |
2685   //        |     +-----------------------------------+
2686   //        |     |          CR save word             |
2687   //        |     +-----------------------------------+
2688   //        |     |         VRSAVE save word          |
2689   //        |     +-----------------------------------+
2690   //        |     |         Alignment padding         |
2691   //        |     +-----------------------------------+
2692   //        |     |     Vector register save area     |
2693   //        |     +-----------------------------------+
2694   //        |     |       Local variable space        |
2695   //        |     +-----------------------------------+
2696   //        |     |        Parameter list area        |
2697   //        |     +-----------------------------------+
2698   //        |     |           LR save word            |
2699   //        |     +-----------------------------------+
2700   // SP-->  +---  |            Back chain             |
2701   //              +-----------------------------------+
2702   //
2703   // Specifications:
2704   //   System V Application Binary Interface PowerPC Processor Supplement
2705   //   AltiVec Technology Programming Interface Manual
2706
2707   MachineFunction &MF = DAG.getMachineFunction();
2708   MachineFrameInfo *MFI = MF.getFrameInfo();
2709   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2710
2711   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2712   // Potential tail calls could cause overwriting of argument stack slots.
2713   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2714                        (CallConv == CallingConv::Fast));
2715   unsigned PtrByteSize = 4;
2716
2717   // Assign locations to all of the incoming arguments.
2718   SmallVector<CCValAssign, 16> ArgLocs;
2719   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2720                  *DAG.getContext());
2721
2722   // Reserve space for the linkage area on the stack.
2723   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2724   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2725
2726   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2727
2728   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2729     CCValAssign &VA = ArgLocs[i];
2730
2731     // Arguments stored in registers.
2732     if (VA.isRegLoc()) {
2733       const TargetRegisterClass *RC;
2734       EVT ValVT = VA.getValVT();
2735
2736       switch (ValVT.getSimpleVT().SimpleTy) {
2737         default:
2738           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2739         case MVT::i1:
2740         case MVT::i32:
2741           RC = &PPC::GPRCRegClass;
2742           break;
2743         case MVT::f32:
2744           if (Subtarget.hasP8Vector())
2745             RC = &PPC::VSSRCRegClass;
2746           else
2747             RC = &PPC::F4RCRegClass;
2748           break;
2749         case MVT::f64:
2750           if (Subtarget.hasVSX())
2751             RC = &PPC::VSFRCRegClass;
2752           else
2753             RC = &PPC::F8RCRegClass;
2754           break;
2755         case MVT::v16i8:
2756         case MVT::v8i16:
2757         case MVT::v4i32:
2758           RC = &PPC::VRRCRegClass;
2759           break;
2760         case MVT::v4f32:
2761           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2762           break;
2763         case MVT::v2f64:
2764         case MVT::v2i64:
2765           RC = &PPC::VSHRCRegClass;
2766           break;
2767         case MVT::v4f64:
2768           RC = &PPC::QFRCRegClass;
2769           break;
2770         case MVT::v4i1:
2771           RC = &PPC::QBRCRegClass;
2772           break;
2773       }
2774
2775       // Transform the arguments stored in physical registers into virtual ones.
2776       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2777       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2778                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2779
2780       if (ValVT == MVT::i1)
2781         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2782
2783       InVals.push_back(ArgValue);
2784     } else {
2785       // Argument stored in memory.
2786       assert(VA.isMemLoc());
2787
2788       unsigned ArgSize = VA.getLocVT().getStoreSize();
2789       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2790                                       isImmutable);
2791
2792       // Create load nodes to retrieve arguments from the stack.
2793       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2794       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2795                                    MachinePointerInfo(),
2796                                    false, false, false, 0));
2797     }
2798   }
2799
2800   // Assign locations to all of the incoming aggregate by value arguments.
2801   // Aggregates passed by value are stored in the local variable space of the
2802   // caller's stack frame, right above the parameter list area.
2803   SmallVector<CCValAssign, 16> ByValArgLocs;
2804   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2805                       ByValArgLocs, *DAG.getContext());
2806
2807   // Reserve stack space for the allocations in CCInfo.
2808   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2809
2810   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2811
2812   // Area that is at least reserved in the caller of this function.
2813   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2814   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2815
2816   // Set the size that is at least reserved in caller of this function.  Tail
2817   // call optimized function's reserved stack space needs to be aligned so that
2818   // taking the difference between two stack areas will result in an aligned
2819   // stack.
2820   MinReservedArea =
2821       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2822   FuncInfo->setMinReservedArea(MinReservedArea);
2823
2824   SmallVector<SDValue, 8> MemOps;
2825
2826   // If the function takes variable number of arguments, make a frame index for
2827   // the start of the first vararg value... for expansion of llvm.va_start.
2828   if (isVarArg) {
2829     static const MCPhysReg GPArgRegs[] = {
2830       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2831       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2832     };
2833     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2834
2835     static const MCPhysReg FPArgRegs[] = {
2836       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2837       PPC::F8
2838     };
2839     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2840     if (DisablePPCFloatInVariadic)
2841       NumFPArgRegs = 0;
2842
2843     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2844     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2845
2846     // Make room for NumGPArgRegs and NumFPArgRegs.
2847     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2848                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2849
2850     FuncInfo->setVarArgsStackOffset(
2851       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2852                              CCInfo.getNextStackOffset(), true));
2853
2854     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2855     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2856
2857     // The fixed integer arguments of a variadic function are stored to the
2858     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2859     // the result of va_next.
2860     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2861       // Get an existing live-in vreg, or add a new one.
2862       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2863       if (!VReg)
2864         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2865
2866       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2867       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2868                                    MachinePointerInfo(), false, false, 0);
2869       MemOps.push_back(Store);
2870       // Increment the address by four for the next argument to store
2871       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2872       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2873     }
2874
2875     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2876     // is set.
2877     // The double arguments are stored to the VarArgsFrameIndex
2878     // on the stack.
2879     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2880       // Get an existing live-in vreg, or add a new one.
2881       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2882       if (!VReg)
2883         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2884
2885       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2886       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2887                                    MachinePointerInfo(), false, false, 0);
2888       MemOps.push_back(Store);
2889       // Increment the address by eight for the next argument to store
2890       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2891                                          PtrVT);
2892       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2893     }
2894   }
2895
2896   if (!MemOps.empty())
2897     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2898
2899   return Chain;
2900 }
2901
2902 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2903 // value to MVT::i64 and then truncate to the correct register size.
2904 SDValue
2905 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2906                                      SelectionDAG &DAG, SDValue ArgVal,
2907                                      SDLoc dl) const {
2908   if (Flags.isSExt())
2909     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2910                          DAG.getValueType(ObjectVT));
2911   else if (Flags.isZExt())
2912     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2913                          DAG.getValueType(ObjectVT));
2914
2915   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2916 }
2917
2918 SDValue
2919 PPCTargetLowering::LowerFormalArguments_64SVR4(
2920                                       SDValue Chain,
2921                                       CallingConv::ID CallConv, bool isVarArg,
2922                                       const SmallVectorImpl<ISD::InputArg>
2923                                         &Ins,
2924                                       SDLoc dl, SelectionDAG &DAG,
2925                                       SmallVectorImpl<SDValue> &InVals) const {
2926   // TODO: add description of PPC stack frame format, or at least some docs.
2927   //
2928   bool isELFv2ABI = Subtarget.isELFv2ABI();
2929   bool isLittleEndian = Subtarget.isLittleEndian();
2930   MachineFunction &MF = DAG.getMachineFunction();
2931   MachineFrameInfo *MFI = MF.getFrameInfo();
2932   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2933
2934   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2935          "fastcc not supported on varargs functions");
2936
2937   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2938   // Potential tail calls could cause overwriting of argument stack slots.
2939   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2940                        (CallConv == CallingConv::Fast));
2941   unsigned PtrByteSize = 8;
2942   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2943
2944   static const MCPhysReg GPR[] = {
2945     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2946     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2947   };
2948   static const MCPhysReg VR[] = {
2949     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2950     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2951   };
2952   static const MCPhysReg VSRH[] = {
2953     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2954     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2955   };
2956
2957   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2958   const unsigned Num_FPR_Regs = 13;
2959   const unsigned Num_VR_Regs  = array_lengthof(VR);
2960   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2961
2962   // Do a first pass over the arguments to determine whether the ABI
2963   // guarantees that our caller has allocated the parameter save area
2964   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2965   // in the ELFv2 ABI, it is true if this is a vararg function or if
2966   // any parameter is located in a stack slot.
2967
2968   bool HasParameterArea = !isELFv2ABI || isVarArg;
2969   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2970   unsigned NumBytes = LinkageSize;
2971   unsigned AvailableFPRs = Num_FPR_Regs;
2972   unsigned AvailableVRs = Num_VR_Regs;
2973   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2974     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2975                                PtrByteSize, LinkageSize, ParamAreaSize,
2976                                NumBytes, AvailableFPRs, AvailableVRs,
2977                                Subtarget.hasQPX()))
2978       HasParameterArea = true;
2979
2980   // Add DAG nodes to load the arguments or copy them out of registers.  On
2981   // entry to a function on PPC, the arguments start after the linkage area,
2982   // although the first ones are often in registers.
2983
2984   unsigned ArgOffset = LinkageSize;
2985   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2986   unsigned &QFPR_idx = FPR_idx;
2987   SmallVector<SDValue, 8> MemOps;
2988   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2989   unsigned CurArgIdx = 0;
2990   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2991     SDValue ArgVal;
2992     bool needsLoad = false;
2993     EVT ObjectVT = Ins[ArgNo].VT;
2994     EVT OrigVT = Ins[ArgNo].ArgVT;
2995     unsigned ObjSize = ObjectVT.getStoreSize();
2996     unsigned ArgSize = ObjSize;
2997     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2998     if (Ins[ArgNo].isOrigArg()) {
2999       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3000       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3001     }
3002     // We re-align the argument offset for each argument, except when using the
3003     // fast calling convention, when we need to make sure we do that only when
3004     // we'll actually use a stack slot.
3005     unsigned CurArgOffset, Align;
3006     auto ComputeArgOffset = [&]() {
3007       /* Respect alignment of argument on the stack.  */
3008       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3009       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3010       CurArgOffset = ArgOffset;
3011     };
3012
3013     if (CallConv != CallingConv::Fast) {
3014       ComputeArgOffset();
3015
3016       /* Compute GPR index associated with argument offset.  */
3017       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3018       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3019     }
3020
3021     // FIXME the codegen can be much improved in some cases.
3022     // We do not have to keep everything in memory.
3023     if (Flags.isByVal()) {
3024       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3025
3026       if (CallConv == CallingConv::Fast)
3027         ComputeArgOffset();
3028
3029       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3030       ObjSize = Flags.getByValSize();
3031       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3032       // Empty aggregate parameters do not take up registers.  Examples:
3033       //   struct { } a;
3034       //   union  { } b;
3035       //   int c[0];
3036       // etc.  However, we have to provide a place-holder in InVals, so
3037       // pretend we have an 8-byte item at the current address for that
3038       // purpose.
3039       if (!ObjSize) {
3040         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3041         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3042         InVals.push_back(FIN);
3043         continue;
3044       }
3045
3046       // Create a stack object covering all stack doublewords occupied
3047       // by the argument.  If the argument is (fully or partially) on
3048       // the stack, or if the argument is fully in registers but the
3049       // caller has allocated the parameter save anyway, we can refer
3050       // directly to the caller's stack frame.  Otherwise, create a
3051       // local copy in our own frame.
3052       int FI;
3053       if (HasParameterArea ||
3054           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3055         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3056       else
3057         FI = MFI->CreateStackObject(ArgSize, Align, false);
3058       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3059
3060       // Handle aggregates smaller than 8 bytes.
3061       if (ObjSize < PtrByteSize) {
3062         // The value of the object is its address, which differs from the
3063         // address of the enclosing doubleword on big-endian systems.
3064         SDValue Arg = FIN;
3065         if (!isLittleEndian) {
3066           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3067           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3068         }
3069         InVals.push_back(Arg);
3070
3071         if (GPR_idx != Num_GPR_Regs) {
3072           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3073           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3074           SDValue Store;
3075
3076           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3077             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3078                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3079             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3080                                       MachinePointerInfo(FuncArg),
3081                                       ObjType, false, false, 0);
3082           } else {
3083             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3084             // store the whole register as-is to the parameter save area
3085             // slot.
3086             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3087                                  MachinePointerInfo(FuncArg),
3088                                  false, false, 0);
3089           }
3090
3091           MemOps.push_back(Store);
3092         }
3093         // Whether we copied from a register or not, advance the offset
3094         // into the parameter save area by a full doubleword.
3095         ArgOffset += PtrByteSize;
3096         continue;
3097       }
3098
3099       // The value of the object is its address, which is the address of
3100       // its first stack doubleword.
3101       InVals.push_back(FIN);
3102
3103       // Store whatever pieces of the object are in registers to memory.
3104       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3105         if (GPR_idx == Num_GPR_Regs)
3106           break;
3107
3108         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3109         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3110         SDValue Addr = FIN;
3111         if (j) {
3112           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3113           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3114         }
3115         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3116                                      MachinePointerInfo(FuncArg, j),
3117                                      false, false, 0);
3118         MemOps.push_back(Store);
3119         ++GPR_idx;
3120       }
3121       ArgOffset += ArgSize;
3122       continue;
3123     }
3124
3125     switch (ObjectVT.getSimpleVT().SimpleTy) {
3126     default: llvm_unreachable("Unhandled argument type!");
3127     case MVT::i1:
3128     case MVT::i32:
3129     case MVT::i64:
3130       // These can be scalar arguments or elements of an integer array type
3131       // passed directly.  Clang may use those instead of "byval" aggregate
3132       // types to avoid forcing arguments to memory unnecessarily.
3133       if (GPR_idx != Num_GPR_Regs) {
3134         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3135         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3136
3137         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3138           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3139           // value to MVT::i64 and then truncate to the correct register size.
3140           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3141       } else {
3142         if (CallConv == CallingConv::Fast)
3143           ComputeArgOffset();
3144
3145         needsLoad = true;
3146         ArgSize = PtrByteSize;
3147       }
3148       if (CallConv != CallingConv::Fast || needsLoad)
3149         ArgOffset += 8;
3150       break;
3151
3152     case MVT::f32:
3153     case MVT::f64:
3154       // These can be scalar arguments or elements of a float array type
3155       // passed directly.  The latter are used to implement ELFv2 homogenous
3156       // float aggregates.
3157       if (FPR_idx != Num_FPR_Regs) {
3158         unsigned VReg;
3159
3160         if (ObjectVT == MVT::f32)
3161           VReg = MF.addLiveIn(FPR[FPR_idx],
3162                               Subtarget.hasP8Vector()
3163                                   ? &PPC::VSSRCRegClass
3164                                   : &PPC::F4RCRegClass);
3165         else
3166           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3167                                                 ? &PPC::VSFRCRegClass
3168                                                 : &PPC::F8RCRegClass);
3169
3170         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3171         ++FPR_idx;
3172       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3173         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3174         // once we support fp <-> gpr moves.
3175
3176         // This can only ever happen in the presence of f32 array types,
3177         // since otherwise we never run out of FPRs before running out
3178         // of GPRs.
3179         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3180         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3181
3182         if (ObjectVT == MVT::f32) {
3183           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3184             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3185                                  DAG.getConstant(32, dl, MVT::i32));
3186           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3187         }
3188
3189         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3190       } else {
3191         if (CallConv == CallingConv::Fast)
3192           ComputeArgOffset();
3193
3194         needsLoad = true;
3195       }
3196
3197       // When passing an array of floats, the array occupies consecutive
3198       // space in the argument area; only round up to the next doubleword
3199       // at the end of the array.  Otherwise, each float takes 8 bytes.
3200       if (CallConv != CallingConv::Fast || needsLoad) {
3201         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3202         ArgOffset += ArgSize;
3203         if (Flags.isInConsecutiveRegsLast())
3204           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3205       }
3206       break;
3207     case MVT::v4f32:
3208     case MVT::v4i32:
3209     case MVT::v8i16:
3210     case MVT::v16i8:
3211     case MVT::v2f64:
3212     case MVT::v2i64:
3213     case MVT::v1i128:
3214       if (!Subtarget.hasQPX()) {
3215       // These can be scalar arguments or elements of a vector array type
3216       // passed directly.  The latter are used to implement ELFv2 homogenous
3217       // vector aggregates.
3218       if (VR_idx != Num_VR_Regs) {
3219         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3220                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3221                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3222         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3223         ++VR_idx;
3224       } else {
3225         if (CallConv == CallingConv::Fast)
3226           ComputeArgOffset();
3227
3228         needsLoad = true;
3229       }
3230       if (CallConv != CallingConv::Fast || needsLoad)
3231         ArgOffset += 16;
3232       break;
3233       } // not QPX
3234
3235       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3236              "Invalid QPX parameter type");
3237       /* fall through */
3238
3239     case MVT::v4f64:
3240     case MVT::v4i1:
3241       // QPX vectors are treated like their scalar floating-point subregisters
3242       // (except that they're larger).
3243       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3244       if (QFPR_idx != Num_QFPR_Regs) {
3245         const TargetRegisterClass *RC;
3246         switch (ObjectVT.getSimpleVT().SimpleTy) {
3247         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3248         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3249         default:         RC = &PPC::QBRCRegClass; break;
3250         }
3251
3252         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3253         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3254         ++QFPR_idx;
3255       } else {
3256         if (CallConv == CallingConv::Fast)
3257           ComputeArgOffset();
3258         needsLoad = true;
3259       }
3260       if (CallConv != CallingConv::Fast || needsLoad)
3261         ArgOffset += Sz;
3262       break;
3263     }
3264
3265     // We need to load the argument to a virtual register if we determined
3266     // above that we ran out of physical registers of the appropriate type.
3267     if (needsLoad) {
3268       if (ObjSize < ArgSize && !isLittleEndian)
3269         CurArgOffset += ArgSize - ObjSize;
3270       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3271       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3272       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3273                            false, false, false, 0);
3274     }
3275
3276     InVals.push_back(ArgVal);
3277   }
3278
3279   // Area that is at least reserved in the caller of this function.
3280   unsigned MinReservedArea;
3281   if (HasParameterArea)
3282     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3283   else
3284     MinReservedArea = LinkageSize;
3285
3286   // Set the size that is at least reserved in caller of this function.  Tail
3287   // call optimized functions' reserved stack space needs to be aligned so that
3288   // taking the difference between two stack areas will result in an aligned
3289   // stack.
3290   MinReservedArea =
3291       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3292   FuncInfo->setMinReservedArea(MinReservedArea);
3293
3294   // If the function takes variable number of arguments, make a frame index for
3295   // the start of the first vararg value... for expansion of llvm.va_start.
3296   if (isVarArg) {
3297     int Depth = ArgOffset;
3298
3299     FuncInfo->setVarArgsFrameIndex(
3300       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3301     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3302
3303     // If this function is vararg, store any remaining integer argument regs
3304     // to their spots on the stack so that they may be loaded by deferencing the
3305     // result of va_next.
3306     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3307          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3308       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3309       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3310       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3311                                    MachinePointerInfo(), false, false, 0);
3312       MemOps.push_back(Store);
3313       // Increment the address by four for the next argument to store
3314       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3315       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3316     }
3317   }
3318
3319   if (!MemOps.empty())
3320     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3321
3322   return Chain;
3323 }
3324
3325 SDValue
3326 PPCTargetLowering::LowerFormalArguments_Darwin(
3327                                       SDValue Chain,
3328                                       CallingConv::ID CallConv, bool isVarArg,
3329                                       const SmallVectorImpl<ISD::InputArg>
3330                                         &Ins,
3331                                       SDLoc dl, SelectionDAG &DAG,
3332                                       SmallVectorImpl<SDValue> &InVals) const {
3333   // TODO: add description of PPC stack frame format, or at least some docs.
3334   //
3335   MachineFunction &MF = DAG.getMachineFunction();
3336   MachineFrameInfo *MFI = MF.getFrameInfo();
3337   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3338
3339   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3340   bool isPPC64 = PtrVT == MVT::i64;
3341   // Potential tail calls could cause overwriting of argument stack slots.
3342   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3343                        (CallConv == CallingConv::Fast));
3344   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3345   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3346   unsigned ArgOffset = LinkageSize;
3347   // Area that is at least reserved in caller of this function.
3348   unsigned MinReservedArea = ArgOffset;
3349
3350   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3351     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3352     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3353   };
3354   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3355     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3356     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3357   };
3358   static const MCPhysReg VR[] = {
3359     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3360     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3361   };
3362
3363   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3364   const unsigned Num_FPR_Regs = 13;
3365   const unsigned Num_VR_Regs  = array_lengthof( VR);
3366
3367   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3368
3369   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3370
3371   // In 32-bit non-varargs functions, the stack space for vectors is after the
3372   // stack space for non-vectors.  We do not use this space unless we have
3373   // too many vectors to fit in registers, something that only occurs in
3374   // constructed examples:), but we have to walk the arglist to figure
3375   // that out...for the pathological case, compute VecArgOffset as the
3376   // start of the vector parameter area.  Computing VecArgOffset is the
3377   // entire point of the following loop.
3378   unsigned VecArgOffset = ArgOffset;
3379   if (!isVarArg && !isPPC64) {
3380     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3381          ++ArgNo) {
3382       EVT ObjectVT = Ins[ArgNo].VT;
3383       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3384
3385       if (Flags.isByVal()) {
3386         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3387         unsigned ObjSize = Flags.getByValSize();
3388         unsigned ArgSize =
3389                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3390         VecArgOffset += ArgSize;
3391         continue;
3392       }
3393
3394       switch(ObjectVT.getSimpleVT().SimpleTy) {
3395       default: llvm_unreachable("Unhandled argument type!");
3396       case MVT::i1:
3397       case MVT::i32:
3398       case MVT::f32:
3399         VecArgOffset += 4;
3400         break;
3401       case MVT::i64:  // PPC64
3402       case MVT::f64:
3403         // FIXME: We are guaranteed to be !isPPC64 at this point.
3404         // Does MVT::i64 apply?
3405         VecArgOffset += 8;
3406         break;
3407       case MVT::v4f32:
3408       case MVT::v4i32:
3409       case MVT::v8i16:
3410       case MVT::v16i8:
3411         // Nothing to do, we're only looking at Nonvector args here.
3412         break;
3413       }
3414     }
3415   }
3416   // We've found where the vector parameter area in memory is.  Skip the
3417   // first 12 parameters; these don't use that memory.
3418   VecArgOffset = ((VecArgOffset+15)/16)*16;
3419   VecArgOffset += 12*16;
3420
3421   // Add DAG nodes to load the arguments or copy them out of registers.  On
3422   // entry to a function on PPC, the arguments start after the linkage area,
3423   // although the first ones are often in registers.
3424
3425   SmallVector<SDValue, 8> MemOps;
3426   unsigned nAltivecParamsAtEnd = 0;
3427   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3428   unsigned CurArgIdx = 0;
3429   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3430     SDValue ArgVal;
3431     bool needsLoad = false;
3432     EVT ObjectVT = Ins[ArgNo].VT;
3433     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3434     unsigned ArgSize = ObjSize;
3435     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3436     if (Ins[ArgNo].isOrigArg()) {
3437       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3438       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3439     }
3440     unsigned CurArgOffset = ArgOffset;
3441
3442     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3443     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3444         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3445       if (isVarArg || isPPC64) {
3446         MinReservedArea = ((MinReservedArea+15)/16)*16;
3447         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3448                                                   Flags,
3449                                                   PtrByteSize);
3450       } else  nAltivecParamsAtEnd++;
3451     } else
3452       // Calculate min reserved area.
3453       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3454                                                 Flags,
3455                                                 PtrByteSize);
3456
3457     // FIXME the codegen can be much improved in some cases.
3458     // We do not have to keep everything in memory.
3459     if (Flags.isByVal()) {
3460       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3461
3462       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3463       ObjSize = Flags.getByValSize();
3464       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3465       // Objects of size 1 and 2 are right justified, everything else is
3466       // left justified.  This means the memory address is adjusted forwards.
3467       if (ObjSize==1 || ObjSize==2) {
3468         CurArgOffset = CurArgOffset + (4 - ObjSize);
3469       }
3470       // The value of the object is its address.
3471       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3472       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3473       InVals.push_back(FIN);
3474       if (ObjSize==1 || ObjSize==2) {
3475         if (GPR_idx != Num_GPR_Regs) {
3476           unsigned VReg;
3477           if (isPPC64)
3478             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3479           else
3480             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3481           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3482           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3483           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3484                                             MachinePointerInfo(FuncArg),
3485                                             ObjType, false, false, 0);
3486           MemOps.push_back(Store);
3487           ++GPR_idx;
3488         }
3489
3490         ArgOffset += PtrByteSize;
3491
3492         continue;
3493       }
3494       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3495         // Store whatever pieces of the object are in registers
3496         // to memory.  ArgOffset will be the address of the beginning
3497         // of the object.
3498         if (GPR_idx != Num_GPR_Regs) {
3499           unsigned VReg;
3500           if (isPPC64)
3501             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3502           else
3503             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3504           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3505           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3506           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3507           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3508                                        MachinePointerInfo(FuncArg, j),
3509                                        false, false, 0);
3510           MemOps.push_back(Store);
3511           ++GPR_idx;
3512           ArgOffset += PtrByteSize;
3513         } else {
3514           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3515           break;
3516         }
3517       }
3518       continue;
3519     }
3520
3521     switch (ObjectVT.getSimpleVT().SimpleTy) {
3522     default: llvm_unreachable("Unhandled argument type!");
3523     case MVT::i1:
3524     case MVT::i32:
3525       if (!isPPC64) {
3526         if (GPR_idx != Num_GPR_Regs) {
3527           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3528           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3529
3530           if (ObjectVT == MVT::i1)
3531             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3532
3533           ++GPR_idx;
3534         } else {
3535           needsLoad = true;
3536           ArgSize = PtrByteSize;
3537         }
3538         // All int arguments reserve stack space in the Darwin ABI.
3539         ArgOffset += PtrByteSize;
3540         break;
3541       }
3542       // FALLTHROUGH
3543     case MVT::i64:  // PPC64
3544       if (GPR_idx != Num_GPR_Regs) {
3545         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3546         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3547
3548         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3549           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3550           // value to MVT::i64 and then truncate to the correct register size.
3551           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3552
3553         ++GPR_idx;
3554       } else {
3555         needsLoad = true;
3556         ArgSize = PtrByteSize;
3557       }
3558       // All int arguments reserve stack space in the Darwin ABI.
3559       ArgOffset += 8;
3560       break;
3561
3562     case MVT::f32:
3563     case MVT::f64:
3564       // Every 4 bytes of argument space consumes one of the GPRs available for
3565       // argument passing.
3566       if (GPR_idx != Num_GPR_Regs) {
3567         ++GPR_idx;
3568         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3569           ++GPR_idx;
3570       }
3571       if (FPR_idx != Num_FPR_Regs) {
3572         unsigned VReg;
3573
3574         if (ObjectVT == MVT::f32)
3575           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3576         else
3577           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3578
3579         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3580         ++FPR_idx;
3581       } else {
3582         needsLoad = true;
3583       }
3584
3585       // All FP arguments reserve stack space in the Darwin ABI.
3586       ArgOffset += isPPC64 ? 8 : ObjSize;
3587       break;
3588     case MVT::v4f32:
3589     case MVT::v4i32:
3590     case MVT::v8i16:
3591     case MVT::v16i8:
3592       // Note that vector arguments in registers don't reserve stack space,
3593       // except in varargs functions.
3594       if (VR_idx != Num_VR_Regs) {
3595         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3596         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3597         if (isVarArg) {
3598           while ((ArgOffset % 16) != 0) {
3599             ArgOffset += PtrByteSize;
3600             if (GPR_idx != Num_GPR_Regs)
3601               GPR_idx++;
3602           }
3603           ArgOffset += 16;
3604           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3605         }
3606         ++VR_idx;
3607       } else {
3608         if (!isVarArg && !isPPC64) {
3609           // Vectors go after all the nonvectors.
3610           CurArgOffset = VecArgOffset;
3611           VecArgOffset += 16;
3612         } else {
3613           // Vectors are aligned.
3614           ArgOffset = ((ArgOffset+15)/16)*16;
3615           CurArgOffset = ArgOffset;
3616           ArgOffset += 16;
3617         }
3618         needsLoad = true;
3619       }
3620       break;
3621     }
3622
3623     // We need to load the argument to a virtual register if we determined above
3624     // that we ran out of physical registers of the appropriate type.
3625     if (needsLoad) {
3626       int FI = MFI->CreateFixedObject(ObjSize,
3627                                       CurArgOffset + (ArgSize - ObjSize),
3628                                       isImmutable);
3629       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3630       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3631                            false, false, false, 0);
3632     }
3633
3634     InVals.push_back(ArgVal);
3635   }
3636
3637   // Allow for Altivec parameters at the end, if needed.
3638   if (nAltivecParamsAtEnd) {
3639     MinReservedArea = ((MinReservedArea+15)/16)*16;
3640     MinReservedArea += 16*nAltivecParamsAtEnd;
3641   }
3642
3643   // Area that is at least reserved in the caller of this function.
3644   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3645
3646   // Set the size that is at least reserved in caller of this function.  Tail
3647   // call optimized functions' reserved stack space needs to be aligned so that
3648   // taking the difference between two stack areas will result in an aligned
3649   // stack.
3650   MinReservedArea =
3651       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3652   FuncInfo->setMinReservedArea(MinReservedArea);
3653
3654   // If the function takes variable number of arguments, make a frame index for
3655   // the start of the first vararg value... for expansion of llvm.va_start.
3656   if (isVarArg) {
3657     int Depth = ArgOffset;
3658
3659     FuncInfo->setVarArgsFrameIndex(
3660       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3661                              Depth, true));
3662     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3663
3664     // If this function is vararg, store any remaining integer argument regs
3665     // to their spots on the stack so that they may be loaded by deferencing the
3666     // result of va_next.
3667     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3668       unsigned VReg;
3669
3670       if (isPPC64)
3671         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3672       else
3673         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3674
3675       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3676       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3677                                    MachinePointerInfo(), false, false, 0);
3678       MemOps.push_back(Store);
3679       // Increment the address by four for the next argument to store
3680       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3681       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3682     }
3683   }
3684
3685   if (!MemOps.empty())
3686     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3687
3688   return Chain;
3689 }
3690
3691 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3692 /// adjusted to accommodate the arguments for the tailcall.
3693 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3694                                    unsigned ParamSize) {
3695
3696   if (!isTailCall) return 0;
3697
3698   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3699   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3700   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3701   // Remember only if the new adjustement is bigger.
3702   if (SPDiff < FI->getTailCallSPDelta())
3703     FI->setTailCallSPDelta(SPDiff);
3704
3705   return SPDiff;
3706 }
3707
3708 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3709 /// for tail call optimization. Targets which want to do tail call
3710 /// optimization should implement this function.
3711 bool
3712 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3713                                                      CallingConv::ID CalleeCC,
3714                                                      bool isVarArg,
3715                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3716                                                      SelectionDAG& DAG) const {
3717   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3718     return false;
3719
3720   // Variable argument functions are not supported.
3721   if (isVarArg)
3722     return false;
3723
3724   MachineFunction &MF = DAG.getMachineFunction();
3725   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3726   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3727     // Functions containing by val parameters are not supported.
3728     for (unsigned i = 0; i != Ins.size(); i++) {
3729        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3730        if (Flags.isByVal()) return false;
3731     }
3732
3733     // Non-PIC/GOT tail calls are supported.
3734     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3735       return true;
3736
3737     // At the moment we can only do local tail calls (in same module, hidden
3738     // or protected) if we are generating PIC.
3739     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3740       return G->getGlobal()->hasHiddenVisibility()
3741           || G->getGlobal()->hasProtectedVisibility();
3742   }
3743
3744   return false;
3745 }
3746
3747 /// isCallCompatibleAddress - Return the immediate to use if the specified
3748 /// 32-bit value is representable in the immediate field of a BxA instruction.
3749 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3750   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3751   if (!C) return nullptr;
3752
3753   int Addr = C->getZExtValue();
3754   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3755       SignExtend32<26>(Addr) != Addr)
3756     return nullptr;  // Top 6 bits have to be sext of immediate.
3757
3758   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3759                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3760 }
3761
3762 namespace {
3763
3764 struct TailCallArgumentInfo {
3765   SDValue Arg;
3766   SDValue FrameIdxOp;
3767   int       FrameIdx;
3768
3769   TailCallArgumentInfo() : FrameIdx(0) {}
3770 };
3771
3772 }
3773
3774 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3775 static void
3776 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3777                                            SDValue Chain,
3778                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3779                    SmallVectorImpl<SDValue> &MemOpChains,
3780                    SDLoc dl) {
3781   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3782     SDValue Arg = TailCallArgs[i].Arg;
3783     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3784     int FI = TailCallArgs[i].FrameIdx;
3785     // Store relative to framepointer.
3786     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3787                                        MachinePointerInfo::getFixedStack(FI),
3788                                        false, false, 0));
3789   }
3790 }
3791
3792 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3793 /// the appropriate stack slot for the tail call optimized function call.
3794 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3795                                                MachineFunction &MF,
3796                                                SDValue Chain,
3797                                                SDValue OldRetAddr,
3798                                                SDValue OldFP,
3799                                                int SPDiff,
3800                                                bool isPPC64,
3801                                                bool isDarwinABI,
3802                                                SDLoc dl) {
3803   if (SPDiff) {
3804     // Calculate the new stack slot for the return address.
3805     int SlotSize = isPPC64 ? 8 : 4;
3806     const PPCFrameLowering *FL =
3807         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3808     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3809     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3810                                                           NewRetAddrLoc, true);
3811     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3812     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3813     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3814                          MachinePointerInfo::getFixedStack(NewRetAddr),
3815                          false, false, 0);
3816
3817     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3818     // slot as the FP is never overwritten.
3819     if (isDarwinABI) {
3820       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3821       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3822                                                           true);
3823       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3824       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3825                            MachinePointerInfo::getFixedStack(NewFPIdx),
3826                            false, false, 0);
3827     }
3828   }
3829   return Chain;
3830 }
3831
3832 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3833 /// the position of the argument.
3834 static void
3835 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3836                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3837                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3838   int Offset = ArgOffset + SPDiff;
3839   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3840   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3841   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3842   SDValue FIN = DAG.getFrameIndex(FI, VT);
3843   TailCallArgumentInfo Info;
3844   Info.Arg = Arg;
3845   Info.FrameIdxOp = FIN;
3846   Info.FrameIdx = FI;
3847   TailCallArguments.push_back(Info);
3848 }
3849
3850 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3851 /// stack slot. Returns the chain as result and the loaded frame pointers in
3852 /// LROpOut/FPOpout. Used when tail calling.
3853 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3854                                                         int SPDiff,
3855                                                         SDValue Chain,
3856                                                         SDValue &LROpOut,
3857                                                         SDValue &FPOpOut,
3858                                                         bool isDarwinABI,
3859                                                         SDLoc dl) const {
3860   if (SPDiff) {
3861     // Load the LR and FP stack slot for later adjusting.
3862     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3863     LROpOut = getReturnAddrFrameIndex(DAG);
3864     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3865                           false, false, false, 0);
3866     Chain = SDValue(LROpOut.getNode(), 1);
3867
3868     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3869     // slot as the FP is never overwritten.
3870     if (isDarwinABI) {
3871       FPOpOut = getFramePointerFrameIndex(DAG);
3872       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3873                             false, false, false, 0);
3874       Chain = SDValue(FPOpOut.getNode(), 1);
3875     }
3876   }
3877   return Chain;
3878 }
3879
3880 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3881 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3882 /// specified by the specific parameter attribute. The copy will be passed as
3883 /// a byval function parameter.
3884 /// Sometimes what we are copying is the end of a larger object, the part that
3885 /// does not fit in registers.
3886 static SDValue
3887 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3888                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3889                           SDLoc dl) {
3890   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3891   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3892                        false, false, false, MachinePointerInfo(),
3893                        MachinePointerInfo());
3894 }
3895
3896 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3897 /// tail calls.
3898 static void
3899 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3900                  SDValue Arg, SDValue PtrOff, int SPDiff,
3901                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3902                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3903                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3904                  SDLoc dl) {
3905   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3906   if (!isTailCall) {
3907     if (isVector) {
3908       SDValue StackPtr;
3909       if (isPPC64)
3910         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3911       else
3912         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3913       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3914                            DAG.getConstant(ArgOffset, dl, PtrVT));
3915     }
3916     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3917                                        MachinePointerInfo(), false, false, 0));
3918   // Calculate and remember argument location.
3919   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3920                                   TailCallArguments);
3921 }
3922
3923 static
3924 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3925                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3926                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3927                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3928   MachineFunction &MF = DAG.getMachineFunction();
3929
3930   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3931   // might overwrite each other in case of tail call optimization.
3932   SmallVector<SDValue, 8> MemOpChains2;
3933   // Do not flag preceding copytoreg stuff together with the following stuff.
3934   InFlag = SDValue();
3935   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3936                                     MemOpChains2, dl);
3937   if (!MemOpChains2.empty())
3938     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3939
3940   // Store the return address to the appropriate stack slot.
3941   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3942                                         isPPC64, isDarwinABI, dl);
3943
3944   // Emit callseq_end just before tailcall node.
3945   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
3946                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3947   InFlag = Chain.getValue(1);
3948 }
3949
3950 // Is this global address that of a function that can be called by name? (as
3951 // opposed to something that must hold a descriptor for an indirect call).
3952 static bool isFunctionGlobalAddress(SDValue Callee) {
3953   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3954     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3955         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3956       return false;
3957
3958     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3959   }
3960
3961   return false;
3962 }
3963
3964 static
3965 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3966                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3967                      bool isTailCall, bool IsPatchPoint,
3968                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3969                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3970                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3971
3972   bool isPPC64 = Subtarget.isPPC64();
3973   bool isSVR4ABI = Subtarget.isSVR4ABI();
3974   bool isELFv2ABI = Subtarget.isELFv2ABI();
3975
3976   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3977   NodeTys.push_back(MVT::Other);   // Returns a chain
3978   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3979
3980   unsigned CallOpc = PPCISD::CALL;
3981
3982   bool needIndirectCall = true;
3983   if (!isSVR4ABI || !isPPC64)
3984     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3985       // If this is an absolute destination address, use the munged value.
3986       Callee = SDValue(Dest, 0);
3987       needIndirectCall = false;
3988     }
3989
3990   if (isFunctionGlobalAddress(Callee)) {
3991     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3992     // A call to a TLS address is actually an indirect call to a
3993     // thread-specific pointer.
3994     unsigned OpFlags = 0;
3995     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3996          (Subtarget.getTargetTriple().isMacOSX() &&
3997           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3998          (G->getGlobal()->isDeclaration() ||
3999           G->getGlobal()->isWeakForLinker())) ||
4000         (Subtarget.isTargetELF() && !isPPC64 &&
4001          !G->getGlobal()->hasLocalLinkage() &&
4002          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4003       // PC-relative references to external symbols should go through $stub,
4004       // unless we're building with the leopard linker or later, which
4005       // automatically synthesizes these stubs.
4006       OpFlags = PPCII::MO_PLT_OR_STUB;
4007     }
4008
4009     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4010     // every direct call is) turn it into a TargetGlobalAddress /
4011     // TargetExternalSymbol node so that legalize doesn't hack it.
4012     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4013                                         Callee.getValueType(), 0, OpFlags);
4014     needIndirectCall = false;
4015   }
4016
4017   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4018     unsigned char OpFlags = 0;
4019
4020     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4021          (Subtarget.getTargetTriple().isMacOSX() &&
4022           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4023         (Subtarget.isTargetELF() && !isPPC64 &&
4024          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4025       // PC-relative references to external symbols should go through $stub,
4026       // unless we're building with the leopard linker or later, which
4027       // automatically synthesizes these stubs.
4028       OpFlags = PPCII::MO_PLT_OR_STUB;
4029     }
4030
4031     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4032                                          OpFlags);
4033     needIndirectCall = false;
4034   }
4035
4036   if (IsPatchPoint) {
4037     // We'll form an invalid direct call when lowering a patchpoint; the full
4038     // sequence for an indirect call is complicated, and many of the
4039     // instructions introduced might have side effects (and, thus, can't be
4040     // removed later). The call itself will be removed as soon as the
4041     // argument/return lowering is complete, so the fact that it has the wrong
4042     // kind of operands should not really matter.
4043     needIndirectCall = false;
4044   }
4045
4046   if (needIndirectCall) {
4047     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4048     // to do the call, we can't use PPCISD::CALL.
4049     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4050
4051     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4052       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4053       // entry point, but to the function descriptor (the function entry point
4054       // address is part of the function descriptor though).
4055       // The function descriptor is a three doubleword structure with the
4056       // following fields: function entry point, TOC base address and
4057       // environment pointer.
4058       // Thus for a call through a function pointer, the following actions need
4059       // to be performed:
4060       //   1. Save the TOC of the caller in the TOC save area of its stack
4061       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4062       //   2. Load the address of the function entry point from the function
4063       //      descriptor.
4064       //   3. Load the TOC of the callee from the function descriptor into r2.
4065       //   4. Load the environment pointer from the function descriptor into
4066       //      r11.
4067       //   5. Branch to the function entry point address.
4068       //   6. On return of the callee, the TOC of the caller needs to be
4069       //      restored (this is done in FinishCall()).
4070       //
4071       // The loads are scheduled at the beginning of the call sequence, and the
4072       // register copies are flagged together to ensure that no other
4073       // operations can be scheduled in between. E.g. without flagging the
4074       // copies together, a TOC access in the caller could be scheduled between
4075       // the assignment of the callee TOC and the branch to the callee, which
4076       // results in the TOC access going through the TOC of the callee instead
4077       // of going through the TOC of the caller, which leads to incorrect code.
4078
4079       // Load the address of the function entry point from the function
4080       // descriptor.
4081       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4082       if (LDChain.getValueType() == MVT::Glue)
4083         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4084
4085       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4086
4087       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4088       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4089                                         false, false, LoadsInv, 8);
4090
4091       // Load environment pointer into r11.
4092       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4093       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4094       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4095                                        MPI.getWithOffset(16), false, false,
4096                                        LoadsInv, 8);
4097
4098       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4099       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4100       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4101                                    MPI.getWithOffset(8), false, false,
4102                                    LoadsInv, 8);
4103
4104       setUsesTOCBasePtr(DAG);
4105       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4106                                         InFlag);
4107       Chain = TOCVal.getValue(0);
4108       InFlag = TOCVal.getValue(1);
4109
4110       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4111                                         InFlag);
4112
4113       Chain = EnvVal.getValue(0);
4114       InFlag = EnvVal.getValue(1);
4115
4116       MTCTROps[0] = Chain;
4117       MTCTROps[1] = LoadFuncPtr;
4118       MTCTROps[2] = InFlag;
4119     }
4120
4121     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4122                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4123     InFlag = Chain.getValue(1);
4124
4125     NodeTys.clear();
4126     NodeTys.push_back(MVT::Other);
4127     NodeTys.push_back(MVT::Glue);
4128     Ops.push_back(Chain);
4129     CallOpc = PPCISD::BCTRL;
4130     Callee.setNode(nullptr);
4131     // Add use of X11 (holding environment pointer)
4132     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4133       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4134     // Add CTR register as callee so a bctr can be emitted later.
4135     if (isTailCall)
4136       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4137   }
4138
4139   // If this is a direct call, pass the chain and the callee.
4140   if (Callee.getNode()) {
4141     Ops.push_back(Chain);
4142     Ops.push_back(Callee);
4143   }
4144   // If this is a tail call add stack pointer delta.
4145   if (isTailCall)
4146     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4147
4148   // Add argument registers to the end of the list so that they are known live
4149   // into the call.
4150   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4151     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4152                                   RegsToPass[i].second.getValueType()));
4153
4154   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4155   // into the call.
4156   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4157     setUsesTOCBasePtr(DAG);
4158     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4159   }
4160
4161   return CallOpc;
4162 }
4163
4164 static
4165 bool isLocalCall(const SDValue &Callee)
4166 {
4167   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4168     return !G->getGlobal()->isDeclaration() &&
4169            !G->getGlobal()->isWeakForLinker();
4170   return false;
4171 }
4172
4173 SDValue
4174 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4175                                    CallingConv::ID CallConv, bool isVarArg,
4176                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4177                                    SDLoc dl, SelectionDAG &DAG,
4178                                    SmallVectorImpl<SDValue> &InVals) const {
4179
4180   SmallVector<CCValAssign, 16> RVLocs;
4181   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4182                     *DAG.getContext());
4183   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4184
4185   // Copy all of the result registers out of their specified physreg.
4186   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4187     CCValAssign &VA = RVLocs[i];
4188     assert(VA.isRegLoc() && "Can only return in registers!");
4189
4190     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4191                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4192     Chain = Val.getValue(1);
4193     InFlag = Val.getValue(2);
4194
4195     switch (VA.getLocInfo()) {
4196     default: llvm_unreachable("Unknown loc info!");
4197     case CCValAssign::Full: break;
4198     case CCValAssign::AExt:
4199       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4200       break;
4201     case CCValAssign::ZExt:
4202       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4203                         DAG.getValueType(VA.getValVT()));
4204       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4205       break;
4206     case CCValAssign::SExt:
4207       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4208                         DAG.getValueType(VA.getValVT()));
4209       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4210       break;
4211     }
4212
4213     InVals.push_back(Val);
4214   }
4215
4216   return Chain;
4217 }
4218
4219 SDValue
4220 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4221                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4222                               SelectionDAG &DAG,
4223                               SmallVector<std::pair<unsigned, SDValue>, 8>
4224                                 &RegsToPass,
4225                               SDValue InFlag, SDValue Chain,
4226                               SDValue CallSeqStart, SDValue &Callee,
4227                               int SPDiff, unsigned NumBytes,
4228                               const SmallVectorImpl<ISD::InputArg> &Ins,
4229                               SmallVectorImpl<SDValue> &InVals,
4230                               ImmutableCallSite *CS) const {
4231
4232   std::vector<EVT> NodeTys;
4233   SmallVector<SDValue, 8> Ops;
4234   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4235                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4236                                  Ops, NodeTys, CS, Subtarget);
4237
4238   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4239   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4240     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4241
4242   // When performing tail call optimization the callee pops its arguments off
4243   // the stack. Account for this here so these bytes can be pushed back on in
4244   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4245   int BytesCalleePops =
4246     (CallConv == CallingConv::Fast &&
4247      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4248
4249   // Add a register mask operand representing the call-preserved registers.
4250   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4251   const uint32_t *Mask =
4252       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4253   assert(Mask && "Missing call preserved mask for calling convention");
4254   Ops.push_back(DAG.getRegisterMask(Mask));
4255
4256   if (InFlag.getNode())
4257     Ops.push_back(InFlag);
4258
4259   // Emit tail call.
4260   if (isTailCall) {
4261     assert(((Callee.getOpcode() == ISD::Register &&
4262              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4263             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4264             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4265             isa<ConstantSDNode>(Callee)) &&
4266     "Expecting an global address, external symbol, absolute value or register");
4267
4268     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4269     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4270   }
4271
4272   // Add a NOP immediately after the branch instruction when using the 64-bit
4273   // SVR4 ABI. At link time, if caller and callee are in a different module and
4274   // thus have a different TOC, the call will be replaced with a call to a stub
4275   // function which saves the current TOC, loads the TOC of the callee and
4276   // branches to the callee. The NOP will be replaced with a load instruction
4277   // which restores the TOC of the caller from the TOC save slot of the current
4278   // stack frame. If caller and callee belong to the same module (and have the
4279   // same TOC), the NOP will remain unchanged.
4280
4281   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4282       !IsPatchPoint) {
4283     if (CallOpc == PPCISD::BCTRL) {
4284       // This is a call through a function pointer.
4285       // Restore the caller TOC from the save area into R2.
4286       // See PrepareCall() for more information about calls through function
4287       // pointers in the 64-bit SVR4 ABI.
4288       // We are using a target-specific load with r2 hard coded, because the
4289       // result of a target-independent load would never go directly into r2,
4290       // since r2 is a reserved register (which prevents the register allocator
4291       // from allocating it), resulting in an additional register being
4292       // allocated and an unnecessary move instruction being generated.
4293       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4294
4295       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4296       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4297       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4298       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4299       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4300
4301       // The address needs to go after the chain input but before the flag (or
4302       // any other variadic arguments).
4303       Ops.insert(std::next(Ops.begin()), AddTOC);
4304     } else if ((CallOpc == PPCISD::CALL) &&
4305                (!isLocalCall(Callee) ||
4306                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4307       // Otherwise insert NOP for non-local calls.
4308       CallOpc = PPCISD::CALL_NOP;
4309   }
4310
4311   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4312   InFlag = Chain.getValue(1);
4313
4314   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4315                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4316                              InFlag, dl);
4317   if (!Ins.empty())
4318     InFlag = Chain.getValue(1);
4319
4320   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4321                          Ins, dl, DAG, InVals);
4322 }
4323
4324 SDValue
4325 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4326                              SmallVectorImpl<SDValue> &InVals) const {
4327   SelectionDAG &DAG                     = CLI.DAG;
4328   SDLoc &dl                             = CLI.DL;
4329   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4330   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4331   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4332   SDValue Chain                         = CLI.Chain;
4333   SDValue Callee                        = CLI.Callee;
4334   bool &isTailCall                      = CLI.IsTailCall;
4335   CallingConv::ID CallConv              = CLI.CallConv;
4336   bool isVarArg                         = CLI.IsVarArg;
4337   bool IsPatchPoint                     = CLI.IsPatchPoint;
4338   ImmutableCallSite *CS                 = CLI.CS;
4339
4340   if (isTailCall)
4341     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4342                                                    Ins, DAG);
4343
4344   if (!isTailCall && CS && CS->isMustTailCall())
4345     report_fatal_error("failed to perform tail call elimination on a call "
4346                        "site marked musttail");
4347
4348   if (Subtarget.isSVR4ABI()) {
4349     if (Subtarget.isPPC64())
4350       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4351                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4352                               dl, DAG, InVals, CS);
4353     else
4354       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4355                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4356                               dl, DAG, InVals, CS);
4357   }
4358
4359   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4360                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4361                           dl, DAG, InVals, CS);
4362 }
4363
4364 SDValue
4365 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4366                                     CallingConv::ID CallConv, bool isVarArg,
4367                                     bool isTailCall, bool IsPatchPoint,
4368                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4369                                     const SmallVectorImpl<SDValue> &OutVals,
4370                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4371                                     SDLoc dl, SelectionDAG &DAG,
4372                                     SmallVectorImpl<SDValue> &InVals,
4373                                     ImmutableCallSite *CS) const {
4374   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4375   // of the 32-bit SVR4 ABI stack frame layout.
4376
4377   assert((CallConv == CallingConv::C ||
4378           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4379
4380   unsigned PtrByteSize = 4;
4381
4382   MachineFunction &MF = DAG.getMachineFunction();
4383
4384   // Mark this function as potentially containing a function that contains a
4385   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4386   // and restoring the callers stack pointer in this functions epilog. This is
4387   // done because by tail calling the called function might overwrite the value
4388   // in this function's (MF) stack pointer stack slot 0(SP).
4389   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4390       CallConv == CallingConv::Fast)
4391     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4392
4393   // Count how many bytes are to be pushed on the stack, including the linkage
4394   // area, parameter list area and the part of the local variable space which
4395   // contains copies of aggregates which are passed by value.
4396
4397   // Assign locations to all of the outgoing arguments.
4398   SmallVector<CCValAssign, 16> ArgLocs;
4399   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4400                  *DAG.getContext());
4401
4402   // Reserve space for the linkage area on the stack.
4403   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4404                        PtrByteSize);
4405
4406   if (isVarArg) {
4407     // Handle fixed and variable vector arguments differently.
4408     // Fixed vector arguments go into registers as long as registers are
4409     // available. Variable vector arguments always go into memory.
4410     unsigned NumArgs = Outs.size();
4411
4412     for (unsigned i = 0; i != NumArgs; ++i) {
4413       MVT ArgVT = Outs[i].VT;
4414       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4415       bool Result;
4416
4417       if (Outs[i].IsFixed) {
4418         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4419                                CCInfo);
4420       } else {
4421         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4422                                       ArgFlags, CCInfo);
4423       }
4424
4425       if (Result) {
4426 #ifndef NDEBUG
4427         errs() << "Call operand #" << i << " has unhandled type "
4428              << EVT(ArgVT).getEVTString() << "\n";
4429 #endif
4430         llvm_unreachable(nullptr);
4431       }
4432     }
4433   } else {
4434     // All arguments are treated the same.
4435     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4436   }
4437
4438   // Assign locations to all of the outgoing aggregate by value arguments.
4439   SmallVector<CCValAssign, 16> ByValArgLocs;
4440   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4441                       ByValArgLocs, *DAG.getContext());
4442
4443   // Reserve stack space for the allocations in CCInfo.
4444   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4445
4446   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4447
4448   // Size of the linkage area, parameter list area and the part of the local
4449   // space variable where copies of aggregates which are passed by value are
4450   // stored.
4451   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4452
4453   // Calculate by how many bytes the stack has to be adjusted in case of tail
4454   // call optimization.
4455   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4456
4457   // Adjust the stack pointer for the new arguments...
4458   // These operations are automatically eliminated by the prolog/epilog pass
4459   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4460                                dl);
4461   SDValue CallSeqStart = Chain;
4462
4463   // Load the return address and frame pointer so it can be moved somewhere else
4464   // later.
4465   SDValue LROp, FPOp;
4466   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4467                                        dl);
4468
4469   // Set up a copy of the stack pointer for use loading and storing any
4470   // arguments that may not fit in the registers available for argument
4471   // passing.
4472   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4473
4474   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4475   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4476   SmallVector<SDValue, 8> MemOpChains;
4477
4478   bool seenFloatArg = false;
4479   // Walk the register/memloc assignments, inserting copies/loads.
4480   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4481        i != e;
4482        ++i) {
4483     CCValAssign &VA = ArgLocs[i];
4484     SDValue Arg = OutVals[i];
4485     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4486
4487     if (Flags.isByVal()) {
4488       // Argument is an aggregate which is passed by value, thus we need to
4489       // create a copy of it in the local variable space of the current stack
4490       // frame (which is the stack frame of the caller) and pass the address of
4491       // this copy to the callee.
4492       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4493       CCValAssign &ByValVA = ByValArgLocs[j++];
4494       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4495
4496       // Memory reserved in the local variable space of the callers stack frame.
4497       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4498
4499       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4500       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4501
4502       // Create a copy of the argument in the local area of the current
4503       // stack frame.
4504       SDValue MemcpyCall =
4505         CreateCopyOfByValArgument(Arg, PtrOff,
4506                                   CallSeqStart.getNode()->getOperand(0),
4507                                   Flags, DAG, dl);
4508
4509       // This must go outside the CALLSEQ_START..END.
4510       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4511                            CallSeqStart.getNode()->getOperand(1),
4512                            SDLoc(MemcpyCall));
4513       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4514                              NewCallSeqStart.getNode());
4515       Chain = CallSeqStart = NewCallSeqStart;
4516
4517       // Pass the address of the aggregate copy on the stack either in a
4518       // physical register or in the parameter list area of the current stack
4519       // frame to the callee.
4520       Arg = PtrOff;
4521     }
4522
4523     if (VA.isRegLoc()) {
4524       if (Arg.getValueType() == MVT::i1)
4525         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4526
4527       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4528       // Put argument in a physical register.
4529       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4530     } else {
4531       // Put argument in the parameter list area of the current stack frame.
4532       assert(VA.isMemLoc());
4533       unsigned LocMemOffset = VA.getLocMemOffset();
4534
4535       if (!isTailCall) {
4536         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4537         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4538
4539         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4540                                            MachinePointerInfo(),
4541                                            false, false, 0));
4542       } else {
4543         // Calculate and remember argument location.
4544         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4545                                  TailCallArguments);
4546       }
4547     }
4548   }
4549
4550   if (!MemOpChains.empty())
4551     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4552
4553   // Build a sequence of copy-to-reg nodes chained together with token chain
4554   // and flag operands which copy the outgoing args into the appropriate regs.
4555   SDValue InFlag;
4556   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4557     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4558                              RegsToPass[i].second, InFlag);
4559     InFlag = Chain.getValue(1);
4560   }
4561
4562   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4563   // registers.
4564   if (isVarArg) {
4565     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4566     SDValue Ops[] = { Chain, InFlag };
4567
4568     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4569                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4570
4571     InFlag = Chain.getValue(1);
4572   }
4573
4574   if (isTailCall)
4575     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4576                     false, TailCallArguments);
4577
4578   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4579                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4580                     NumBytes, Ins, InVals, CS);
4581 }
4582
4583 // Copy an argument into memory, being careful to do this outside the
4584 // call sequence for the call to which the argument belongs.
4585 SDValue
4586 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4587                                               SDValue CallSeqStart,
4588                                               ISD::ArgFlagsTy Flags,
4589                                               SelectionDAG &DAG,
4590                                               SDLoc dl) const {
4591   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4592                         CallSeqStart.getNode()->getOperand(0),
4593                         Flags, DAG, dl);
4594   // The MEMCPY must go outside the CALLSEQ_START..END.
4595   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4596                              CallSeqStart.getNode()->getOperand(1),
4597                              SDLoc(MemcpyCall));
4598   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4599                          NewCallSeqStart.getNode());
4600   return NewCallSeqStart;
4601 }
4602
4603 SDValue
4604 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4605                                     CallingConv::ID CallConv, bool isVarArg,
4606                                     bool isTailCall, bool IsPatchPoint,
4607                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4608                                     const SmallVectorImpl<SDValue> &OutVals,
4609                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4610                                     SDLoc dl, SelectionDAG &DAG,
4611                                     SmallVectorImpl<SDValue> &InVals,
4612                                     ImmutableCallSite *CS) const {
4613
4614   bool isELFv2ABI = Subtarget.isELFv2ABI();
4615   bool isLittleEndian = Subtarget.isLittleEndian();
4616   unsigned NumOps = Outs.size();
4617
4618   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4619   unsigned PtrByteSize = 8;
4620
4621   MachineFunction &MF = DAG.getMachineFunction();
4622
4623   // Mark this function as potentially containing a function that contains a
4624   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4625   // and restoring the callers stack pointer in this functions epilog. This is
4626   // done because by tail calling the called function might overwrite the value
4627   // in this function's (MF) stack pointer stack slot 0(SP).
4628   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4629       CallConv == CallingConv::Fast)
4630     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4631
4632   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4633          "fastcc not supported on varargs functions");
4634
4635   // Count how many bytes are to be pushed on the stack, including the linkage
4636   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4637   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4638   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4639   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4640   unsigned NumBytes = LinkageSize;
4641   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4642   unsigned &QFPR_idx = FPR_idx;
4643
4644   static const MCPhysReg GPR[] = {
4645     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4646     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4647   };
4648   static const MCPhysReg VR[] = {
4649     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4650     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4651   };
4652   static const MCPhysReg VSRH[] = {
4653     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4654     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4655   };
4656
4657   const unsigned NumGPRs = array_lengthof(GPR);
4658   const unsigned NumFPRs = 13;
4659   const unsigned NumVRs  = array_lengthof(VR);
4660   const unsigned NumQFPRs = NumFPRs;
4661
4662   // When using the fast calling convention, we don't provide backing for
4663   // arguments that will be in registers.
4664   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4665
4666   // Add up all the space actually used.
4667   for (unsigned i = 0; i != NumOps; ++i) {
4668     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4669     EVT ArgVT = Outs[i].VT;
4670     EVT OrigVT = Outs[i].ArgVT;
4671
4672     if (CallConv == CallingConv::Fast) {
4673       if (Flags.isByVal())
4674         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4675       else
4676         switch (ArgVT.getSimpleVT().SimpleTy) {
4677         default: llvm_unreachable("Unexpected ValueType for argument!");
4678         case MVT::i1:
4679         case MVT::i32:
4680         case MVT::i64:
4681           if (++NumGPRsUsed <= NumGPRs)
4682             continue;
4683           break;
4684         case MVT::v4i32:
4685         case MVT::v8i16:
4686         case MVT::v16i8:
4687         case MVT::v2f64:
4688         case MVT::v2i64:
4689         case MVT::v1i128:
4690           if (++NumVRsUsed <= NumVRs)
4691             continue;
4692           break;
4693         case MVT::v4f32:
4694           // When using QPX, this is handled like a FP register, otherwise, it
4695           // is an Altivec register.
4696           if (Subtarget.hasQPX()) {
4697             if (++NumFPRsUsed <= NumFPRs)
4698               continue;
4699           } else {
4700             if (++NumVRsUsed <= NumVRs)
4701               continue;
4702           }
4703           break;
4704         case MVT::f32:
4705         case MVT::f64:
4706         case MVT::v4f64: // QPX
4707         case MVT::v4i1:  // QPX
4708           if (++NumFPRsUsed <= NumFPRs)
4709             continue;
4710           break;
4711         }
4712     }
4713
4714     /* Respect alignment of argument on the stack.  */
4715     unsigned Align =
4716       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4717     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4718
4719     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4720     if (Flags.isInConsecutiveRegsLast())
4721       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4722   }
4723
4724   unsigned NumBytesActuallyUsed = NumBytes;
4725
4726   // The prolog code of the callee may store up to 8 GPR argument registers to
4727   // the stack, allowing va_start to index over them in memory if its varargs.
4728   // Because we cannot tell if this is needed on the caller side, we have to
4729   // conservatively assume that it is needed.  As such, make sure we have at
4730   // least enough stack space for the caller to store the 8 GPRs.
4731   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4732   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4733
4734   // Tail call needs the stack to be aligned.
4735   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4736       CallConv == CallingConv::Fast)
4737     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4738
4739   // Calculate by how many bytes the stack has to be adjusted in case of tail
4740   // call optimization.
4741   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4742
4743   // To protect arguments on the stack from being clobbered in a tail call,
4744   // force all the loads to happen before doing any other lowering.
4745   if (isTailCall)
4746     Chain = DAG.getStackArgumentTokenFactor(Chain);
4747
4748   // Adjust the stack pointer for the new arguments...
4749   // These operations are automatically eliminated by the prolog/epilog pass
4750   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4751                                dl);
4752   SDValue CallSeqStart = Chain;
4753
4754   // Load the return address and frame pointer so it can be move somewhere else
4755   // later.
4756   SDValue LROp, FPOp;
4757   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4758                                        dl);
4759
4760   // Set up a copy of the stack pointer for use loading and storing any
4761   // arguments that may not fit in the registers available for argument
4762   // passing.
4763   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4764
4765   // Figure out which arguments are going to go in registers, and which in
4766   // memory.  Also, if this is a vararg function, floating point operations
4767   // must be stored to our stack, and loaded into integer regs as well, if
4768   // any integer regs are available for argument passing.
4769   unsigned ArgOffset = LinkageSize;
4770
4771   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4772   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4773
4774   SmallVector<SDValue, 8> MemOpChains;
4775   for (unsigned i = 0; i != NumOps; ++i) {
4776     SDValue Arg = OutVals[i];
4777     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4778     EVT ArgVT = Outs[i].VT;
4779     EVT OrigVT = Outs[i].ArgVT;
4780
4781     // PtrOff will be used to store the current argument to the stack if a
4782     // register cannot be found for it.
4783     SDValue PtrOff;
4784
4785     // We re-align the argument offset for each argument, except when using the
4786     // fast calling convention, when we need to make sure we do that only when
4787     // we'll actually use a stack slot.
4788     auto ComputePtrOff = [&]() {
4789       /* Respect alignment of argument on the stack.  */
4790       unsigned Align =
4791         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4792       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4793
4794       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4795
4796       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4797     };
4798
4799     if (CallConv != CallingConv::Fast) {
4800       ComputePtrOff();
4801
4802       /* Compute GPR index associated with argument offset.  */
4803       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4804       GPR_idx = std::min(GPR_idx, NumGPRs);
4805     }
4806
4807     // Promote integers to 64-bit values.
4808     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4809       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4810       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4811       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4812     }
4813
4814     // FIXME memcpy is used way more than necessary.  Correctness first.
4815     // Note: "by value" is code for passing a structure by value, not
4816     // basic types.
4817     if (Flags.isByVal()) {
4818       // Note: Size includes alignment padding, so
4819       //   struct x { short a; char b; }
4820       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4821       // These are the proper values we need for right-justifying the
4822       // aggregate in a parameter register.
4823       unsigned Size = Flags.getByValSize();
4824
4825       // An empty aggregate parameter takes up no storage and no
4826       // registers.
4827       if (Size == 0)
4828         continue;
4829
4830       if (CallConv == CallingConv::Fast)
4831         ComputePtrOff();
4832
4833       // All aggregates smaller than 8 bytes must be passed right-justified.
4834       if (Size==1 || Size==2 || Size==4) {
4835         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4836         if (GPR_idx != NumGPRs) {
4837           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4838                                         MachinePointerInfo(), VT,
4839                                         false, false, false, 0);
4840           MemOpChains.push_back(Load.getValue(1));
4841           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4842
4843           ArgOffset += PtrByteSize;
4844           continue;
4845         }
4846       }
4847
4848       if (GPR_idx == NumGPRs && Size < 8) {
4849         SDValue AddPtr = PtrOff;
4850         if (!isLittleEndian) {
4851           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4852                                           PtrOff.getValueType());
4853           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4854         }
4855         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4856                                                           CallSeqStart,
4857                                                           Flags, DAG, dl);
4858         ArgOffset += PtrByteSize;
4859         continue;
4860       }
4861       // Copy entire object into memory.  There are cases where gcc-generated
4862       // code assumes it is there, even if it could be put entirely into
4863       // registers.  (This is not what the doc says.)
4864
4865       // FIXME: The above statement is likely due to a misunderstanding of the
4866       // documents.  All arguments must be copied into the parameter area BY
4867       // THE CALLEE in the event that the callee takes the address of any
4868       // formal argument.  That has not yet been implemented.  However, it is
4869       // reasonable to use the stack area as a staging area for the register
4870       // load.
4871
4872       // Skip this for small aggregates, as we will use the same slot for a
4873       // right-justified copy, below.
4874       if (Size >= 8)
4875         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4876                                                           CallSeqStart,
4877                                                           Flags, DAG, dl);
4878
4879       // When a register is available, pass a small aggregate right-justified.
4880       if (Size < 8 && GPR_idx != NumGPRs) {
4881         // The easiest way to get this right-justified in a register
4882         // is to copy the structure into the rightmost portion of a
4883         // local variable slot, then load the whole slot into the
4884         // register.
4885         // FIXME: The memcpy seems to produce pretty awful code for
4886         // small aggregates, particularly for packed ones.
4887         // FIXME: It would be preferable to use the slot in the
4888         // parameter save area instead of a new local variable.
4889         SDValue AddPtr = PtrOff;
4890         if (!isLittleEndian) {
4891           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
4892           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4893         }
4894         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4895                                                           CallSeqStart,
4896                                                           Flags, DAG, dl);
4897
4898         // Load the slot into the register.
4899         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4900                                    MachinePointerInfo(),
4901                                    false, false, false, 0);
4902         MemOpChains.push_back(Load.getValue(1));
4903         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4904
4905         // Done with this argument.
4906         ArgOffset += PtrByteSize;
4907         continue;
4908       }
4909
4910       // For aggregates larger than PtrByteSize, copy the pieces of the
4911       // object that fit into registers from the parameter save area.
4912       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4913         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
4914         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4915         if (GPR_idx != NumGPRs) {
4916           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4917                                      MachinePointerInfo(),
4918                                      false, false, false, 0);
4919           MemOpChains.push_back(Load.getValue(1));
4920           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4921           ArgOffset += PtrByteSize;
4922         } else {
4923           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4924           break;
4925         }
4926       }
4927       continue;
4928     }
4929
4930     switch (Arg.getSimpleValueType().SimpleTy) {
4931     default: llvm_unreachable("Unexpected ValueType for argument!");
4932     case MVT::i1:
4933     case MVT::i32:
4934     case MVT::i64:
4935       // These can be scalar arguments or elements of an integer array type
4936       // passed directly.  Clang may use those instead of "byval" aggregate
4937       // types to avoid forcing arguments to memory unnecessarily.
4938       if (GPR_idx != NumGPRs) {
4939         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4940       } else {
4941         if (CallConv == CallingConv::Fast)
4942           ComputePtrOff();
4943
4944         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4945                          true, isTailCall, false, MemOpChains,
4946                          TailCallArguments, dl);
4947         if (CallConv == CallingConv::Fast)
4948           ArgOffset += PtrByteSize;
4949       }
4950       if (CallConv != CallingConv::Fast)
4951         ArgOffset += PtrByteSize;
4952       break;
4953     case MVT::f32:
4954     case MVT::f64: {
4955       // These can be scalar arguments or elements of a float array type
4956       // passed directly.  The latter are used to implement ELFv2 homogenous
4957       // float aggregates.
4958
4959       // Named arguments go into FPRs first, and once they overflow, the
4960       // remaining arguments go into GPRs and then the parameter save area.
4961       // Unnamed arguments for vararg functions always go to GPRs and
4962       // then the parameter save area.  For now, put all arguments to vararg
4963       // routines always in both locations (FPR *and* GPR or stack slot).
4964       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4965       bool NeededLoad = false;
4966
4967       // First load the argument into the next available FPR.
4968       if (FPR_idx != NumFPRs)
4969         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4970
4971       // Next, load the argument into GPR or stack slot if needed.
4972       if (!NeedGPROrStack)
4973         ;
4974       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4975         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4976         // once we support fp <-> gpr moves.
4977
4978         // In the non-vararg case, this can only ever happen in the
4979         // presence of f32 array types, since otherwise we never run
4980         // out of FPRs before running out of GPRs.
4981         SDValue ArgVal;
4982
4983         // Double values are always passed in a single GPR.
4984         if (Arg.getValueType() != MVT::f32) {
4985           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4986
4987         // Non-array float values are extended and passed in a GPR.
4988         } else if (!Flags.isInConsecutiveRegs()) {
4989           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4990           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4991
4992         // If we have an array of floats, we collect every odd element
4993         // together with its predecessor into one GPR.
4994         } else if (ArgOffset % PtrByteSize != 0) {
4995           SDValue Lo, Hi;
4996           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4997           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4998           if (!isLittleEndian)
4999             std::swap(Lo, Hi);
5000           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5001
5002         // The final element, if even, goes into the first half of a GPR.
5003         } else if (Flags.isInConsecutiveRegsLast()) {
5004           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5005           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5006           if (!isLittleEndian)
5007             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5008                                  DAG.getConstant(32, dl, MVT::i32));
5009
5010         // Non-final even elements are skipped; they will be handled
5011         // together the with subsequent argument on the next go-around.
5012         } else
5013           ArgVal = SDValue();
5014
5015         if (ArgVal.getNode())
5016           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5017       } else {
5018         if (CallConv == CallingConv::Fast)
5019           ComputePtrOff();
5020
5021         // Single-precision floating-point values are mapped to the
5022         // second (rightmost) word of the stack doubleword.
5023         if (Arg.getValueType() == MVT::f32 &&
5024             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5025           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5026           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5027         }
5028
5029         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5030                          true, isTailCall, false, MemOpChains,
5031                          TailCallArguments, dl);
5032
5033         NeededLoad = true;
5034       }
5035       // When passing an array of floats, the array occupies consecutive
5036       // space in the argument area; only round up to the next doubleword
5037       // at the end of the array.  Otherwise, each float takes 8 bytes.
5038       if (CallConv != CallingConv::Fast || NeededLoad) {
5039         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5040                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5041         if (Flags.isInConsecutiveRegsLast())
5042           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5043       }
5044       break;
5045     }
5046     case MVT::v4f32:
5047     case MVT::v4i32:
5048     case MVT::v8i16:
5049     case MVT::v16i8:
5050     case MVT::v2f64:
5051     case MVT::v2i64:
5052     case MVT::v1i128:
5053       if (!Subtarget.hasQPX()) {
5054       // These can be scalar arguments or elements of a vector array type
5055       // passed directly.  The latter are used to implement ELFv2 homogenous
5056       // vector aggregates.
5057
5058       // For a varargs call, named arguments go into VRs or on the stack as
5059       // usual; unnamed arguments always go to the stack or the corresponding
5060       // GPRs when within range.  For now, we always put the value in both
5061       // locations (or even all three).
5062       if (isVarArg) {
5063         // We could elide this store in the case where the object fits
5064         // entirely in R registers.  Maybe later.
5065         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5066                                      MachinePointerInfo(), false, false, 0);
5067         MemOpChains.push_back(Store);
5068         if (VR_idx != NumVRs) {
5069           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5070                                      MachinePointerInfo(),
5071                                      false, false, false, 0);
5072           MemOpChains.push_back(Load.getValue(1));
5073
5074           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5075                            Arg.getSimpleValueType() == MVT::v2i64) ?
5076                           VSRH[VR_idx] : VR[VR_idx];
5077           ++VR_idx;
5078
5079           RegsToPass.push_back(std::make_pair(VReg, Load));
5080         }
5081         ArgOffset += 16;
5082         for (unsigned i=0; i<16; i+=PtrByteSize) {
5083           if (GPR_idx == NumGPRs)
5084             break;
5085           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5086                                    DAG.getConstant(i, dl, PtrVT));
5087           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5088                                      false, false, false, 0);
5089           MemOpChains.push_back(Load.getValue(1));
5090           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5091         }
5092         break;
5093       }
5094
5095       // Non-varargs Altivec params go into VRs or on the stack.
5096       if (VR_idx != NumVRs) {
5097         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5098                          Arg.getSimpleValueType() == MVT::v2i64) ?
5099                         VSRH[VR_idx] : VR[VR_idx];
5100         ++VR_idx;
5101
5102         RegsToPass.push_back(std::make_pair(VReg, Arg));
5103       } else {
5104         if (CallConv == CallingConv::Fast)
5105           ComputePtrOff();
5106
5107         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5108                          true, isTailCall, true, MemOpChains,
5109                          TailCallArguments, dl);
5110         if (CallConv == CallingConv::Fast)
5111           ArgOffset += 16;
5112       }
5113
5114       if (CallConv != CallingConv::Fast)
5115         ArgOffset += 16;
5116       break;
5117       } // not QPX
5118
5119       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5120              "Invalid QPX parameter type");
5121
5122       /* fall through */
5123     case MVT::v4f64:
5124     case MVT::v4i1: {
5125       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5126       if (isVarArg) {
5127         // We could elide this store in the case where the object fits
5128         // entirely in R registers.  Maybe later.
5129         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5130                                      MachinePointerInfo(), false, false, 0);
5131         MemOpChains.push_back(Store);
5132         if (QFPR_idx != NumQFPRs) {
5133           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5134                                      Store, PtrOff, MachinePointerInfo(),
5135                                      false, false, false, 0);
5136           MemOpChains.push_back(Load.getValue(1));
5137           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5138         }
5139         ArgOffset += (IsF32 ? 16 : 32);
5140         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5141           if (GPR_idx == NumGPRs)
5142             break;
5143           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5144                                    DAG.getConstant(i, dl, PtrVT));
5145           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5146                                      false, false, false, 0);
5147           MemOpChains.push_back(Load.getValue(1));
5148           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5149         }
5150         break;
5151       }
5152
5153       // Non-varargs QPX params go into registers or on the stack.
5154       if (QFPR_idx != NumQFPRs) {
5155         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5156       } else {
5157         if (CallConv == CallingConv::Fast)
5158           ComputePtrOff();
5159
5160         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5161                          true, isTailCall, true, MemOpChains,
5162                          TailCallArguments, dl);
5163         if (CallConv == CallingConv::Fast)
5164           ArgOffset += (IsF32 ? 16 : 32);
5165       }
5166
5167       if (CallConv != CallingConv::Fast)
5168         ArgOffset += (IsF32 ? 16 : 32);
5169       break;
5170       }
5171     }
5172   }
5173
5174   assert(NumBytesActuallyUsed == ArgOffset);
5175   (void)NumBytesActuallyUsed;
5176
5177   if (!MemOpChains.empty())
5178     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5179
5180   // Check if this is an indirect call (MTCTR/BCTRL).
5181   // See PrepareCall() for more information about calls through function
5182   // pointers in the 64-bit SVR4 ABI.
5183   if (!isTailCall && !IsPatchPoint &&
5184       !isFunctionGlobalAddress(Callee) &&
5185       !isa<ExternalSymbolSDNode>(Callee)) {
5186     // Load r2 into a virtual register and store it to the TOC save area.
5187     setUsesTOCBasePtr(DAG);
5188     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5189     // TOC save area offset.
5190     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5191     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5192     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5193     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5194                          MachinePointerInfo::getStack(TOCSaveOffset),
5195                          false, false, 0);
5196     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5197     // This does not mean the MTCTR instruction must use R12; it's easier
5198     // to model this as an extra parameter, so do that.
5199     if (isELFv2ABI && !IsPatchPoint)
5200       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5201   }
5202
5203   // Build a sequence of copy-to-reg nodes chained together with token chain
5204   // and flag operands which copy the outgoing args into the appropriate regs.
5205   SDValue InFlag;
5206   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5207     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5208                              RegsToPass[i].second, InFlag);
5209     InFlag = Chain.getValue(1);
5210   }
5211
5212   if (isTailCall)
5213     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5214                     FPOp, true, TailCallArguments);
5215
5216   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5217                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5218                     NumBytes, Ins, InVals, CS);
5219 }
5220
5221 SDValue
5222 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5223                                     CallingConv::ID CallConv, bool isVarArg,
5224                                     bool isTailCall, bool IsPatchPoint,
5225                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5226                                     const SmallVectorImpl<SDValue> &OutVals,
5227                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5228                                     SDLoc dl, SelectionDAG &DAG,
5229                                     SmallVectorImpl<SDValue> &InVals,
5230                                     ImmutableCallSite *CS) const {
5231
5232   unsigned NumOps = Outs.size();
5233
5234   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5235   bool isPPC64 = PtrVT == MVT::i64;
5236   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5237
5238   MachineFunction &MF = DAG.getMachineFunction();
5239
5240   // Mark this function as potentially containing a function that contains a
5241   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5242   // and restoring the callers stack pointer in this functions epilog. This is
5243   // done because by tail calling the called function might overwrite the value
5244   // in this function's (MF) stack pointer stack slot 0(SP).
5245   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5246       CallConv == CallingConv::Fast)
5247     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5248
5249   // Count how many bytes are to be pushed on the stack, including the linkage
5250   // area, and parameter passing area.  We start with 24/48 bytes, which is
5251   // prereserved space for [SP][CR][LR][3 x unused].
5252   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5253   unsigned NumBytes = LinkageSize;
5254
5255   // Add up all the space actually used.
5256   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5257   // they all go in registers, but we must reserve stack space for them for
5258   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5259   // assigned stack space in order, with padding so Altivec parameters are
5260   // 16-byte aligned.
5261   unsigned nAltivecParamsAtEnd = 0;
5262   for (unsigned i = 0; i != NumOps; ++i) {
5263     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5264     EVT ArgVT = Outs[i].VT;
5265     // Varargs Altivec parameters are padded to a 16 byte boundary.
5266     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5267         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5268         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5269       if (!isVarArg && !isPPC64) {
5270         // Non-varargs Altivec parameters go after all the non-Altivec
5271         // parameters; handle those later so we know how much padding we need.
5272         nAltivecParamsAtEnd++;
5273         continue;
5274       }
5275       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5276       NumBytes = ((NumBytes+15)/16)*16;
5277     }
5278     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5279   }
5280
5281   // Allow for Altivec parameters at the end, if needed.
5282   if (nAltivecParamsAtEnd) {
5283     NumBytes = ((NumBytes+15)/16)*16;
5284     NumBytes += 16*nAltivecParamsAtEnd;
5285   }
5286
5287   // The prolog code of the callee may store up to 8 GPR argument registers to
5288   // the stack, allowing va_start to index over them in memory if its varargs.
5289   // Because we cannot tell if this is needed on the caller side, we have to
5290   // conservatively assume that it is needed.  As such, make sure we have at
5291   // least enough stack space for the caller to store the 8 GPRs.
5292   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5293
5294   // Tail call needs the stack to be aligned.
5295   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5296       CallConv == CallingConv::Fast)
5297     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5298
5299   // Calculate by how many bytes the stack has to be adjusted in case of tail
5300   // call optimization.
5301   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5302
5303   // To protect arguments on the stack from being clobbered in a tail call,
5304   // force all the loads to happen before doing any other lowering.
5305   if (isTailCall)
5306     Chain = DAG.getStackArgumentTokenFactor(Chain);
5307
5308   // Adjust the stack pointer for the new arguments...
5309   // These operations are automatically eliminated by the prolog/epilog pass
5310   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5311                                dl);
5312   SDValue CallSeqStart = Chain;
5313
5314   // Load the return address and frame pointer so it can be move somewhere else
5315   // later.
5316   SDValue LROp, FPOp;
5317   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5318                                        dl);
5319
5320   // Set up a copy of the stack pointer for use loading and storing any
5321   // arguments that may not fit in the registers available for argument
5322   // passing.
5323   SDValue StackPtr;
5324   if (isPPC64)
5325     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5326   else
5327     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5328
5329   // Figure out which arguments are going to go in registers, and which in
5330   // memory.  Also, if this is a vararg function, floating point operations
5331   // must be stored to our stack, and loaded into integer regs as well, if
5332   // any integer regs are available for argument passing.
5333   unsigned ArgOffset = LinkageSize;
5334   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5335
5336   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5337     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5338     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5339   };
5340   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5341     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5342     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5343   };
5344   static const MCPhysReg VR[] = {
5345     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5346     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5347   };
5348   const unsigned NumGPRs = array_lengthof(GPR_32);
5349   const unsigned NumFPRs = 13;
5350   const unsigned NumVRs  = array_lengthof(VR);
5351
5352   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5353
5354   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5355   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5356
5357   SmallVector<SDValue, 8> MemOpChains;
5358   for (unsigned i = 0; i != NumOps; ++i) {
5359     SDValue Arg = OutVals[i];
5360     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5361
5362     // PtrOff will be used to store the current argument to the stack if a
5363     // register cannot be found for it.
5364     SDValue PtrOff;
5365
5366     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5367
5368     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5369
5370     // On PPC64, promote integers to 64-bit values.
5371     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5372       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5373       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5374       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5375     }
5376
5377     // FIXME memcpy is used way more than necessary.  Correctness first.
5378     // Note: "by value" is code for passing a structure by value, not
5379     // basic types.
5380     if (Flags.isByVal()) {
5381       unsigned Size = Flags.getByValSize();
5382       // Very small objects are passed right-justified.  Everything else is
5383       // passed left-justified.
5384       if (Size==1 || Size==2) {
5385         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5386         if (GPR_idx != NumGPRs) {
5387           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5388                                         MachinePointerInfo(), VT,
5389                                         false, false, false, 0);
5390           MemOpChains.push_back(Load.getValue(1));
5391           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5392
5393           ArgOffset += PtrByteSize;
5394         } else {
5395           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5396                                           PtrOff.getValueType());
5397           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5398           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5399                                                             CallSeqStart,
5400                                                             Flags, DAG, dl);
5401           ArgOffset += PtrByteSize;
5402         }
5403         continue;
5404       }
5405       // Copy entire object into memory.  There are cases where gcc-generated
5406       // code assumes it is there, even if it could be put entirely into
5407       // registers.  (This is not what the doc says.)
5408       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5409                                                         CallSeqStart,
5410                                                         Flags, DAG, dl);
5411
5412       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5413       // copy the pieces of the object that fit into registers from the
5414       // parameter save area.
5415       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5416         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5417         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5418         if (GPR_idx != NumGPRs) {
5419           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5420                                      MachinePointerInfo(),
5421                                      false, false, false, 0);
5422           MemOpChains.push_back(Load.getValue(1));
5423           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5424           ArgOffset += PtrByteSize;
5425         } else {
5426           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5427           break;
5428         }
5429       }
5430       continue;
5431     }
5432
5433     switch (Arg.getSimpleValueType().SimpleTy) {
5434     default: llvm_unreachable("Unexpected ValueType for argument!");
5435     case MVT::i1:
5436     case MVT::i32:
5437     case MVT::i64:
5438       if (GPR_idx != NumGPRs) {
5439         if (Arg.getValueType() == MVT::i1)
5440           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5441
5442         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5443       } else {
5444         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5445                          isPPC64, isTailCall, false, MemOpChains,
5446                          TailCallArguments, dl);
5447       }
5448       ArgOffset += PtrByteSize;
5449       break;
5450     case MVT::f32:
5451     case MVT::f64:
5452       if (FPR_idx != NumFPRs) {
5453         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5454
5455         if (isVarArg) {
5456           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5457                                        MachinePointerInfo(), false, false, 0);
5458           MemOpChains.push_back(Store);
5459
5460           // Float varargs are always shadowed in available integer registers
5461           if (GPR_idx != NumGPRs) {
5462             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5463                                        MachinePointerInfo(), false, false,
5464                                        false, 0);
5465             MemOpChains.push_back(Load.getValue(1));
5466             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5467           }
5468           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5469             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5470             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5471             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5472                                        MachinePointerInfo(),
5473                                        false, false, false, 0);
5474             MemOpChains.push_back(Load.getValue(1));
5475             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5476           }
5477         } else {
5478           // If we have any FPRs remaining, we may also have GPRs remaining.
5479           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5480           // GPRs.
5481           if (GPR_idx != NumGPRs)
5482             ++GPR_idx;
5483           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5484               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5485             ++GPR_idx;
5486         }
5487       } else
5488         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5489                          isPPC64, isTailCall, false, MemOpChains,
5490                          TailCallArguments, dl);
5491       if (isPPC64)
5492         ArgOffset += 8;
5493       else
5494         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5495       break;
5496     case MVT::v4f32:
5497     case MVT::v4i32:
5498     case MVT::v8i16:
5499     case MVT::v16i8:
5500       if (isVarArg) {
5501         // These go aligned on the stack, or in the corresponding R registers
5502         // when within range.  The Darwin PPC ABI doc claims they also go in
5503         // V registers; in fact gcc does this only for arguments that are
5504         // prototyped, not for those that match the ...  We do it for all
5505         // arguments, seems to work.
5506         while (ArgOffset % 16 !=0) {
5507           ArgOffset += PtrByteSize;
5508           if (GPR_idx != NumGPRs)
5509             GPR_idx++;
5510         }
5511         // We could elide this store in the case where the object fits
5512         // entirely in R registers.  Maybe later.
5513         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5514                              DAG.getConstant(ArgOffset, dl, PtrVT));
5515         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5516                                      MachinePointerInfo(), false, false, 0);
5517         MemOpChains.push_back(Store);
5518         if (VR_idx != NumVRs) {
5519           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5520                                      MachinePointerInfo(),
5521                                      false, false, false, 0);
5522           MemOpChains.push_back(Load.getValue(1));
5523           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5524         }
5525         ArgOffset += 16;
5526         for (unsigned i=0; i<16; i+=PtrByteSize) {
5527           if (GPR_idx == NumGPRs)
5528             break;
5529           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5530                                    DAG.getConstant(i, dl, PtrVT));
5531           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5532                                      false, false, false, 0);
5533           MemOpChains.push_back(Load.getValue(1));
5534           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5535         }
5536         break;
5537       }
5538
5539       // Non-varargs Altivec params generally go in registers, but have
5540       // stack space allocated at the end.
5541       if (VR_idx != NumVRs) {
5542         // Doesn't have GPR space allocated.
5543         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5544       } else if (nAltivecParamsAtEnd==0) {
5545         // We are emitting Altivec params in order.
5546         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5547                          isPPC64, isTailCall, true, MemOpChains,
5548                          TailCallArguments, dl);
5549         ArgOffset += 16;
5550       }
5551       break;
5552     }
5553   }
5554   // If all Altivec parameters fit in registers, as they usually do,
5555   // they get stack space following the non-Altivec parameters.  We
5556   // don't track this here because nobody below needs it.
5557   // If there are more Altivec parameters than fit in registers emit
5558   // the stores here.
5559   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5560     unsigned j = 0;
5561     // Offset is aligned; skip 1st 12 params which go in V registers.
5562     ArgOffset = ((ArgOffset+15)/16)*16;
5563     ArgOffset += 12*16;
5564     for (unsigned i = 0; i != NumOps; ++i) {
5565       SDValue Arg = OutVals[i];
5566       EVT ArgType = Outs[i].VT;
5567       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5568           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5569         if (++j > NumVRs) {
5570           SDValue PtrOff;
5571           // We are emitting Altivec params in order.
5572           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5573                            isPPC64, isTailCall, true, MemOpChains,
5574                            TailCallArguments, dl);
5575           ArgOffset += 16;
5576         }
5577       }
5578     }
5579   }
5580
5581   if (!MemOpChains.empty())
5582     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5583
5584   // On Darwin, R12 must contain the address of an indirect callee.  This does
5585   // not mean the MTCTR instruction must use R12; it's easier to model this as
5586   // an extra parameter, so do that.
5587   if (!isTailCall &&
5588       !isFunctionGlobalAddress(Callee) &&
5589       !isa<ExternalSymbolSDNode>(Callee) &&
5590       !isBLACompatibleAddress(Callee, DAG))
5591     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5592                                                    PPC::R12), Callee));
5593
5594   // Build a sequence of copy-to-reg nodes chained together with token chain
5595   // and flag operands which copy the outgoing args into the appropriate regs.
5596   SDValue InFlag;
5597   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5598     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5599                              RegsToPass[i].second, InFlag);
5600     InFlag = Chain.getValue(1);
5601   }
5602
5603   if (isTailCall)
5604     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5605                     FPOp, true, TailCallArguments);
5606
5607   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5608                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5609                     NumBytes, Ins, InVals, CS);
5610 }
5611
5612 bool
5613 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5614                                   MachineFunction &MF, bool isVarArg,
5615                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5616                                   LLVMContext &Context) const {
5617   SmallVector<CCValAssign, 16> RVLocs;
5618   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5619   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5620 }
5621
5622 SDValue
5623 PPCTargetLowering::LowerReturn(SDValue Chain,
5624                                CallingConv::ID CallConv, bool isVarArg,
5625                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5626                                const SmallVectorImpl<SDValue> &OutVals,
5627                                SDLoc dl, SelectionDAG &DAG) const {
5628
5629   SmallVector<CCValAssign, 16> RVLocs;
5630   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5631                  *DAG.getContext());
5632   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5633
5634   SDValue Flag;
5635   SmallVector<SDValue, 4> RetOps(1, Chain);
5636
5637   // Copy the result values into the output registers.
5638   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5639     CCValAssign &VA = RVLocs[i];
5640     assert(VA.isRegLoc() && "Can only return in registers!");
5641
5642     SDValue Arg = OutVals[i];
5643
5644     switch (VA.getLocInfo()) {
5645     default: llvm_unreachable("Unknown loc info!");
5646     case CCValAssign::Full: break;
5647     case CCValAssign::AExt:
5648       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5649       break;
5650     case CCValAssign::ZExt:
5651       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5652       break;
5653     case CCValAssign::SExt:
5654       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5655       break;
5656     }
5657
5658     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5659     Flag = Chain.getValue(1);
5660     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5661   }
5662
5663   RetOps[0] = Chain;  // Update chain.
5664
5665   // Add the flag if we have it.
5666   if (Flag.getNode())
5667     RetOps.push_back(Flag);
5668
5669   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5670 }
5671
5672 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5673                                    const PPCSubtarget &Subtarget) const {
5674   // When we pop the dynamic allocation we need to restore the SP link.
5675   SDLoc dl(Op);
5676
5677   // Get the corect type for pointers.
5678   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5679
5680   // Construct the stack pointer operand.
5681   bool isPPC64 = Subtarget.isPPC64();
5682   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5683   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5684
5685   // Get the operands for the STACKRESTORE.
5686   SDValue Chain = Op.getOperand(0);
5687   SDValue SaveSP = Op.getOperand(1);
5688
5689   // Load the old link SP.
5690   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5691                                    MachinePointerInfo(),
5692                                    false, false, false, 0);
5693
5694   // Restore the stack pointer.
5695   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5696
5697   // Store the old link SP.
5698   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5699                       false, false, 0);
5700 }
5701
5702
5703
5704 SDValue
5705 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5706   MachineFunction &MF = DAG.getMachineFunction();
5707   bool isPPC64 = Subtarget.isPPC64();
5708   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5709
5710   // Get current frame pointer save index.  The users of this index will be
5711   // primarily DYNALLOC instructions.
5712   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5713   int RASI = FI->getReturnAddrSaveIndex();
5714
5715   // If the frame pointer save index hasn't been defined yet.
5716   if (!RASI) {
5717     // Find out what the fix offset of the frame pointer save area.
5718     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5719     // Allocate the frame index for frame pointer save area.
5720     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5721     // Save the result.
5722     FI->setReturnAddrSaveIndex(RASI);
5723   }
5724   return DAG.getFrameIndex(RASI, PtrVT);
5725 }
5726
5727 SDValue
5728 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5729   MachineFunction &MF = DAG.getMachineFunction();
5730   bool isPPC64 = Subtarget.isPPC64();
5731   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5732
5733   // Get current frame pointer save index.  The users of this index will be
5734   // primarily DYNALLOC instructions.
5735   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5736   int FPSI = FI->getFramePointerSaveIndex();
5737
5738   // If the frame pointer save index hasn't been defined yet.
5739   if (!FPSI) {
5740     // Find out what the fix offset of the frame pointer save area.
5741     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5742     // Allocate the frame index for frame pointer save area.
5743     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5744     // Save the result.
5745     FI->setFramePointerSaveIndex(FPSI);
5746   }
5747   return DAG.getFrameIndex(FPSI, PtrVT);
5748 }
5749
5750 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5751                                          SelectionDAG &DAG,
5752                                          const PPCSubtarget &Subtarget) const {
5753   // Get the inputs.
5754   SDValue Chain = Op.getOperand(0);
5755   SDValue Size  = Op.getOperand(1);
5756   SDLoc dl(Op);
5757
5758   // Get the corect type for pointers.
5759   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5760   // Negate the size.
5761   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5762                                 DAG.getConstant(0, dl, PtrVT), Size);
5763   // Construct a node for the frame pointer save index.
5764   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5765   // Build a DYNALLOC node.
5766   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5767   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5768   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5769 }
5770
5771 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5772                                                SelectionDAG &DAG) const {
5773   SDLoc DL(Op);
5774   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5775                      DAG.getVTList(MVT::i32, MVT::Other),
5776                      Op.getOperand(0), Op.getOperand(1));
5777 }
5778
5779 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5780                                                 SelectionDAG &DAG) const {
5781   SDLoc DL(Op);
5782   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5783                      Op.getOperand(0), Op.getOperand(1));
5784 }
5785
5786 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5787   if (Op.getValueType().isVector())
5788     return LowerVectorLoad(Op, DAG);
5789
5790   assert(Op.getValueType() == MVT::i1 &&
5791          "Custom lowering only for i1 loads");
5792
5793   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5794
5795   SDLoc dl(Op);
5796   LoadSDNode *LD = cast<LoadSDNode>(Op);
5797
5798   SDValue Chain = LD->getChain();
5799   SDValue BasePtr = LD->getBasePtr();
5800   MachineMemOperand *MMO = LD->getMemOperand();
5801
5802   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5803                                  BasePtr, MVT::i8, MMO);
5804   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5805
5806   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5807   return DAG.getMergeValues(Ops, dl);
5808 }
5809
5810 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5811   if (Op.getOperand(1).getValueType().isVector())
5812     return LowerVectorStore(Op, DAG);
5813
5814   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5815          "Custom lowering only for i1 stores");
5816
5817   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5818
5819   SDLoc dl(Op);
5820   StoreSDNode *ST = cast<StoreSDNode>(Op);
5821
5822   SDValue Chain = ST->getChain();
5823   SDValue BasePtr = ST->getBasePtr();
5824   SDValue Value = ST->getValue();
5825   MachineMemOperand *MMO = ST->getMemOperand();
5826
5827   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5828   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5829 }
5830
5831 // FIXME: Remove this once the ANDI glue bug is fixed:
5832 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5833   assert(Op.getValueType() == MVT::i1 &&
5834          "Custom lowering only for i1 results");
5835
5836   SDLoc DL(Op);
5837   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5838                      Op.getOperand(0));
5839 }
5840
5841 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5842 /// possible.
5843 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5844   // Not FP? Not a fsel.
5845   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5846       !Op.getOperand(2).getValueType().isFloatingPoint())
5847     return Op;
5848
5849   // We might be able to do better than this under some circumstances, but in
5850   // general, fsel-based lowering of select is a finite-math-only optimization.
5851   // For more information, see section F.3 of the 2.06 ISA specification.
5852   if (!DAG.getTarget().Options.NoInfsFPMath ||
5853       !DAG.getTarget().Options.NoNaNsFPMath)
5854     return Op;
5855
5856   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5857
5858   EVT ResVT = Op.getValueType();
5859   EVT CmpVT = Op.getOperand(0).getValueType();
5860   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5861   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5862   SDLoc dl(Op);
5863
5864   // If the RHS of the comparison is a 0.0, we don't need to do the
5865   // subtraction at all.
5866   SDValue Sel1;
5867   if (isFloatingPointZero(RHS))
5868     switch (CC) {
5869     default: break;       // SETUO etc aren't handled by fsel.
5870     case ISD::SETNE:
5871       std::swap(TV, FV);
5872     case ISD::SETEQ:
5873       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5874         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5875       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5876       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5877         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5878       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5879                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5880     case ISD::SETULT:
5881     case ISD::SETLT:
5882       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5883     case ISD::SETOGE:
5884     case ISD::SETGE:
5885       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5886         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5887       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5888     case ISD::SETUGT:
5889     case ISD::SETGT:
5890       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5891     case ISD::SETOLE:
5892     case ISD::SETLE:
5893       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5894         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5895       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5896                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5897     }
5898
5899   SDValue Cmp;
5900   switch (CC) {
5901   default: break;       // SETUO etc aren't handled by fsel.
5902   case ISD::SETNE:
5903     std::swap(TV, FV);
5904   case ISD::SETEQ:
5905     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5906     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5907       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5908     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5909     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5910       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5911     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5912                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5913   case ISD::SETULT:
5914   case ISD::SETLT:
5915     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5916     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5917       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5918     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5919   case ISD::SETOGE:
5920   case ISD::SETGE:
5921     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5922     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5923       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5924     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5925   case ISD::SETUGT:
5926   case ISD::SETGT:
5927     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5928     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5929       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5930     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5931   case ISD::SETOLE:
5932   case ISD::SETLE:
5933     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5934     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5935       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5936     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5937   }
5938   return Op;
5939 }
5940
5941 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5942                                                SelectionDAG &DAG,
5943                                                SDLoc dl) const {
5944   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5945   SDValue Src = Op.getOperand(0);
5946   if (Src.getValueType() == MVT::f32)
5947     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5948
5949   SDValue Tmp;
5950   switch (Op.getSimpleValueType().SimpleTy) {
5951   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5952   case MVT::i32:
5953     Tmp = DAG.getNode(
5954         Op.getOpcode() == ISD::FP_TO_SINT
5955             ? PPCISD::FCTIWZ
5956             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5957         dl, MVT::f64, Src);
5958     break;
5959   case MVT::i64:
5960     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5961            "i64 FP_TO_UINT is supported only with FPCVT");
5962     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5963                                                         PPCISD::FCTIDUZ,
5964                       dl, MVT::f64, Src);
5965     break;
5966   }
5967
5968   // Convert the FP value to an int value through memory.
5969   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5970     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5971   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5972   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5973   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5974
5975   // Emit a store to the stack slot.
5976   SDValue Chain;
5977   if (i32Stack) {
5978     MachineFunction &MF = DAG.getMachineFunction();
5979     MachineMemOperand *MMO =
5980       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5981     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5982     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5983               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5984   } else
5985     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5986                          MPI, false, false, 0);
5987
5988   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5989   // add in a bias.
5990   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5991     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5992                         DAG.getConstant(4, dl, FIPtr.getValueType()));
5993     MPI = MPI.getWithOffset(4);
5994   }
5995
5996   RLI.Chain = Chain;
5997   RLI.Ptr = FIPtr;
5998   RLI.MPI = MPI;
5999 }
6000
6001 /// \brief Custom lowers floating point to integer conversions to use
6002 /// the direct move instructions available in ISA 2.07 to avoid the
6003 /// need for load/store combinations.
6004 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6005                                                     SelectionDAG &DAG,
6006                                                     SDLoc dl) const {
6007   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6008   SDValue Src = Op.getOperand(0);
6009
6010   if (Src.getValueType() == MVT::f32)
6011     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6012
6013   SDValue Tmp;
6014   switch (Op.getSimpleValueType().SimpleTy) {
6015   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6016   case MVT::i32:
6017     Tmp = DAG.getNode(
6018         Op.getOpcode() == ISD::FP_TO_SINT
6019             ? PPCISD::FCTIWZ
6020             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6021         dl, MVT::f64, Src);
6022     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6023     break;
6024   case MVT::i64:
6025     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6026            "i64 FP_TO_UINT is supported only with FPCVT");
6027     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6028                                                         PPCISD::FCTIDUZ,
6029                       dl, MVT::f64, Src);
6030     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6031     break;
6032   }
6033   return Tmp;
6034 }
6035
6036 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6037                                           SDLoc dl) const {
6038   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6039     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6040
6041   ReuseLoadInfo RLI;
6042   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6043
6044   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6045                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6046                      RLI.Ranges);
6047 }
6048
6049 // We're trying to insert a regular store, S, and then a load, L. If the
6050 // incoming value, O, is a load, we might just be able to have our load use the
6051 // address used by O. However, we don't know if anything else will store to
6052 // that address before we can load from it. To prevent this situation, we need
6053 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6054 // the same chain operand as O, we create a token factor from the chain results
6055 // of O and L, and we replace all uses of O's chain result with that token
6056 // factor (see spliceIntoChain below for this last part).
6057 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6058                                             ReuseLoadInfo &RLI,
6059                                             SelectionDAG &DAG,
6060                                             ISD::LoadExtType ET) const {
6061   SDLoc dl(Op);
6062   if (ET == ISD::NON_EXTLOAD &&
6063       (Op.getOpcode() == ISD::FP_TO_UINT ||
6064        Op.getOpcode() == ISD::FP_TO_SINT) &&
6065       isOperationLegalOrCustom(Op.getOpcode(),
6066                                Op.getOperand(0).getValueType())) {
6067
6068     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6069     return true;
6070   }
6071
6072   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6073   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6074       LD->isNonTemporal())
6075     return false;
6076   if (LD->getMemoryVT() != MemVT)
6077     return false;
6078
6079   RLI.Ptr = LD->getBasePtr();
6080   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6081     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6082            "Non-pre-inc AM on PPC?");
6083     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6084                           LD->getOffset());
6085   }
6086
6087   RLI.Chain = LD->getChain();
6088   RLI.MPI = LD->getPointerInfo();
6089   RLI.IsInvariant = LD->isInvariant();
6090   RLI.Alignment = LD->getAlignment();
6091   RLI.AAInfo = LD->getAAInfo();
6092   RLI.Ranges = LD->getRanges();
6093
6094   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6095   return true;
6096 }
6097
6098 // Given the head of the old chain, ResChain, insert a token factor containing
6099 // it and NewResChain, and make users of ResChain now be users of that token
6100 // factor.
6101 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6102                                         SDValue NewResChain,
6103                                         SelectionDAG &DAG) const {
6104   if (!ResChain)
6105     return;
6106
6107   SDLoc dl(NewResChain);
6108
6109   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6110                            NewResChain, DAG.getUNDEF(MVT::Other));
6111   assert(TF.getNode() != NewResChain.getNode() &&
6112          "A new TF really is required here");
6113
6114   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6115   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6116 }
6117
6118 /// \brief Custom lowers integer to floating point conversions to use
6119 /// the direct move instructions available in ISA 2.07 to avoid the
6120 /// need for load/store combinations.
6121 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6122                                                     SelectionDAG &DAG,
6123                                                     SDLoc dl) const {
6124   assert((Op.getValueType() == MVT::f32 ||
6125           Op.getValueType() == MVT::f64) &&
6126          "Invalid floating point type as target of conversion");
6127   assert(Subtarget.hasFPCVT() &&
6128          "Int to FP conversions with direct moves require FPCVT");
6129   SDValue FP;
6130   SDValue Src = Op.getOperand(0);
6131   bool SinglePrec = Op.getValueType() == MVT::f32;
6132   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6133   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6134   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6135                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6136
6137   if (WordInt) {
6138     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6139                      dl, MVT::f64, Src);
6140     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6141   }
6142   else {
6143     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6144     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6145   }
6146
6147   return FP;
6148 }
6149
6150 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6151                                           SelectionDAG &DAG) const {
6152   SDLoc dl(Op);
6153
6154   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6155     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6156       return SDValue();
6157
6158     SDValue Value = Op.getOperand(0);
6159     // The values are now known to be -1 (false) or 1 (true). To convert this
6160     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6161     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6162     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6163   
6164     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6165     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6166                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6167   
6168     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6169
6170     if (Op.getValueType() != MVT::v4f64)
6171       Value = DAG.getNode(ISD::FP_ROUND, dl,
6172                           Op.getValueType(), Value,
6173                           DAG.getIntPtrConstant(1, dl));
6174     return Value;
6175   }
6176
6177   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6178   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6179     return SDValue();
6180
6181   if (Op.getOperand(0).getValueType() == MVT::i1)
6182     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6183                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6184                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6185
6186   // If we have direct moves, we can do all the conversion, skip the store/load
6187   // however, without FPCVT we can't do most conversions.
6188   if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6189     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6190
6191   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6192          "UINT_TO_FP is supported only with FPCVT");
6193
6194   // If we have FCFIDS, then use it when converting to single-precision.
6195   // Otherwise, convert to double-precision and then round.
6196   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6197                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6198                                                             : PPCISD::FCFIDS)
6199                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6200                                                             : PPCISD::FCFID);
6201   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6202                   ? MVT::f32
6203                   : MVT::f64;
6204
6205   if (Op.getOperand(0).getValueType() == MVT::i64) {
6206     SDValue SINT = Op.getOperand(0);
6207     // When converting to single-precision, we actually need to convert
6208     // to double-precision first and then round to single-precision.
6209     // To avoid double-rounding effects during that operation, we have
6210     // to prepare the input operand.  Bits that might be truncated when
6211     // converting to double-precision are replaced by a bit that won't
6212     // be lost at this stage, but is below the single-precision rounding
6213     // position.
6214     //
6215     // However, if -enable-unsafe-fp-math is in effect, accept double
6216     // rounding to avoid the extra overhead.
6217     if (Op.getValueType() == MVT::f32 &&
6218         !Subtarget.hasFPCVT() &&
6219         !DAG.getTarget().Options.UnsafeFPMath) {
6220
6221       // Twiddle input to make sure the low 11 bits are zero.  (If this
6222       // is the case, we are guaranteed the value will fit into the 53 bit
6223       // mantissa of an IEEE double-precision value without rounding.)
6224       // If any of those low 11 bits were not zero originally, make sure
6225       // bit 12 (value 2048) is set instead, so that the final rounding
6226       // to single-precision gets the correct result.
6227       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6228                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6229       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6230                           Round, DAG.getConstant(2047, dl, MVT::i64));
6231       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6232       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6233                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6234
6235       // However, we cannot use that value unconditionally: if the magnitude
6236       // of the input value is small, the bit-twiddling we did above might
6237       // end up visibly changing the output.  Fortunately, in that case, we
6238       // don't need to twiddle bits since the original input will convert
6239       // exactly to double-precision floating-point already.  Therefore,
6240       // construct a conditional to use the original value if the top 11
6241       // bits are all sign-bit copies, and use the rounded value computed
6242       // above otherwise.
6243       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6244                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6245       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6246                          Cond, DAG.getConstant(1, dl, MVT::i64));
6247       Cond = DAG.getSetCC(dl, MVT::i32,
6248                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6249
6250       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6251     }
6252
6253     ReuseLoadInfo RLI;
6254     SDValue Bits;
6255
6256     MachineFunction &MF = DAG.getMachineFunction();
6257     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6258       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6259                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6260                          RLI.Ranges);
6261       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6262     } else if (Subtarget.hasLFIWAX() &&
6263                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6264       MachineMemOperand *MMO =
6265         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6266                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6267       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6268       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6269                                      DAG.getVTList(MVT::f64, MVT::Other),
6270                                      Ops, MVT::i32, MMO);
6271       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6272     } else if (Subtarget.hasFPCVT() &&
6273                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6274       MachineMemOperand *MMO =
6275         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6276                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6277       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6278       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6279                                      DAG.getVTList(MVT::f64, MVT::Other),
6280                                      Ops, MVT::i32, MMO);
6281       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6282     } else if (((Subtarget.hasLFIWAX() &&
6283                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6284                 (Subtarget.hasFPCVT() &&
6285                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6286                SINT.getOperand(0).getValueType() == MVT::i32) {
6287       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6288       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6289
6290       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6291       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6292
6293       SDValue Store =
6294         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6295                      MachinePointerInfo::getFixedStack(FrameIdx),
6296                      false, false, 0);
6297
6298       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6299              "Expected an i32 store");
6300
6301       RLI.Ptr = FIdx;
6302       RLI.Chain = Store;
6303       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6304       RLI.Alignment = 4;
6305
6306       MachineMemOperand *MMO =
6307         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6308                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6309       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6310       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6311                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6312                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6313                                      Ops, MVT::i32, MMO);
6314     } else
6315       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6316
6317     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6318
6319     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6320       FP = DAG.getNode(ISD::FP_ROUND, dl,
6321                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6322     return FP;
6323   }
6324
6325   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6326          "Unhandled INT_TO_FP type in custom expander!");
6327   // Since we only generate this in 64-bit mode, we can take advantage of
6328   // 64-bit registers.  In particular, sign extend the input value into the
6329   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6330   // then lfd it and fcfid it.
6331   MachineFunction &MF = DAG.getMachineFunction();
6332   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6333   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6334
6335   SDValue Ld;
6336   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6337     ReuseLoadInfo RLI;
6338     bool ReusingLoad;
6339     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6340                                             DAG))) {
6341       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6342       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6343
6344       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6345                                    MachinePointerInfo::getFixedStack(FrameIdx),
6346                                    false, false, 0);
6347
6348       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6349              "Expected an i32 store");
6350
6351       RLI.Ptr = FIdx;
6352       RLI.Chain = Store;
6353       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6354       RLI.Alignment = 4;
6355     }
6356
6357     MachineMemOperand *MMO =
6358       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6359                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6360     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6361     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6362                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6363                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6364                                  Ops, MVT::i32, MMO);
6365     if (ReusingLoad)
6366       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6367   } else {
6368     assert(Subtarget.isPPC64() &&
6369            "i32->FP without LFIWAX supported only on PPC64");
6370
6371     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6372     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6373
6374     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6375                                 Op.getOperand(0));
6376
6377     // STD the extended value into the stack slot.
6378     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6379                                  MachinePointerInfo::getFixedStack(FrameIdx),
6380                                  false, false, 0);
6381
6382     // Load the value as a double.
6383     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6384                      MachinePointerInfo::getFixedStack(FrameIdx),
6385                      false, false, false, 0);
6386   }
6387
6388   // FCFID it and return it.
6389   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6390   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6391     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6392                      DAG.getIntPtrConstant(0, dl));
6393   return FP;
6394 }
6395
6396 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6397                                             SelectionDAG &DAG) const {
6398   SDLoc dl(Op);
6399   /*
6400    The rounding mode is in bits 30:31 of FPSR, and has the following
6401    settings:
6402      00 Round to nearest
6403      01 Round to 0
6404      10 Round to +inf
6405      11 Round to -inf
6406
6407   FLT_ROUNDS, on the other hand, expects the following:
6408     -1 Undefined
6409      0 Round to 0
6410      1 Round to nearest
6411      2 Round to +inf
6412      3 Round to -inf
6413
6414   To perform the conversion, we do:
6415     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6416   */
6417
6418   MachineFunction &MF = DAG.getMachineFunction();
6419   EVT VT = Op.getValueType();
6420   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6421
6422   // Save FP Control Word to register
6423   EVT NodeTys[] = {
6424     MVT::f64,    // return register
6425     MVT::Glue    // unused in this context
6426   };
6427   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6428
6429   // Save FP register to stack slot
6430   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6431   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6432   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6433                                StackSlot, MachinePointerInfo(), false, false,0);
6434
6435   // Load FP Control Word from low 32 bits of stack slot.
6436   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6437   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6438   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6439                             false, false, false, 0);
6440
6441   // Transform as necessary
6442   SDValue CWD1 =
6443     DAG.getNode(ISD::AND, dl, MVT::i32,
6444                 CWD, DAG.getConstant(3, dl, MVT::i32));
6445   SDValue CWD2 =
6446     DAG.getNode(ISD::SRL, dl, MVT::i32,
6447                 DAG.getNode(ISD::AND, dl, MVT::i32,
6448                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6449                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6450                             DAG.getConstant(3, dl, MVT::i32)),
6451                 DAG.getConstant(1, dl, MVT::i32));
6452
6453   SDValue RetVal =
6454     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6455
6456   return DAG.getNode((VT.getSizeInBits() < 16 ?
6457                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6458 }
6459
6460 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6461   EVT VT = Op.getValueType();
6462   unsigned BitWidth = VT.getSizeInBits();
6463   SDLoc dl(Op);
6464   assert(Op.getNumOperands() == 3 &&
6465          VT == Op.getOperand(1).getValueType() &&
6466          "Unexpected SHL!");
6467
6468   // Expand into a bunch of logical ops.  Note that these ops
6469   // depend on the PPC behavior for oversized shift amounts.
6470   SDValue Lo = Op.getOperand(0);
6471   SDValue Hi = Op.getOperand(1);
6472   SDValue Amt = Op.getOperand(2);
6473   EVT AmtVT = Amt.getValueType();
6474
6475   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6476                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6477   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6478   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6479   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6480   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6481                              DAG.getConstant(-BitWidth, dl, AmtVT));
6482   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6483   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6484   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6485   SDValue OutOps[] = { OutLo, OutHi };
6486   return DAG.getMergeValues(OutOps, dl);
6487 }
6488
6489 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6490   EVT VT = Op.getValueType();
6491   SDLoc dl(Op);
6492   unsigned BitWidth = VT.getSizeInBits();
6493   assert(Op.getNumOperands() == 3 &&
6494          VT == Op.getOperand(1).getValueType() &&
6495          "Unexpected SRL!");
6496
6497   // Expand into a bunch of logical ops.  Note that these ops
6498   // depend on the PPC behavior for oversized shift amounts.
6499   SDValue Lo = Op.getOperand(0);
6500   SDValue Hi = Op.getOperand(1);
6501   SDValue Amt = Op.getOperand(2);
6502   EVT AmtVT = Amt.getValueType();
6503
6504   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6505                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6506   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6507   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6508   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6509   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6510                              DAG.getConstant(-BitWidth, dl, AmtVT));
6511   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6512   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6513   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6514   SDValue OutOps[] = { OutLo, OutHi };
6515   return DAG.getMergeValues(OutOps, dl);
6516 }
6517
6518 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6519   SDLoc dl(Op);
6520   EVT VT = Op.getValueType();
6521   unsigned BitWidth = VT.getSizeInBits();
6522   assert(Op.getNumOperands() == 3 &&
6523          VT == Op.getOperand(1).getValueType() &&
6524          "Unexpected SRA!");
6525
6526   // Expand into a bunch of logical ops, followed by a select_cc.
6527   SDValue Lo = Op.getOperand(0);
6528   SDValue Hi = Op.getOperand(1);
6529   SDValue Amt = Op.getOperand(2);
6530   EVT AmtVT = Amt.getValueType();
6531
6532   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6533                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6534   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6535   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6536   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6537   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6538                              DAG.getConstant(-BitWidth, dl, AmtVT));
6539   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6540   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6541   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6542                                   Tmp4, Tmp6, ISD::SETLE);
6543   SDValue OutOps[] = { OutLo, OutHi };
6544   return DAG.getMergeValues(OutOps, dl);
6545 }
6546
6547 //===----------------------------------------------------------------------===//
6548 // Vector related lowering.
6549 //
6550
6551 /// BuildSplatI - Build a canonical splati of Val with an element size of
6552 /// SplatSize.  Cast the result to VT.
6553 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6554                              SelectionDAG &DAG, SDLoc dl) {
6555   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6556
6557   static const MVT VTys[] = { // canonical VT to use for each size.
6558     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6559   };
6560
6561   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6562
6563   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6564   if (Val == -1)
6565     SplatSize = 1;
6566
6567   EVT CanonicalVT = VTys[SplatSize-1];
6568
6569   // Build a canonical splat for this value.
6570   SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6571   SmallVector<SDValue, 8> Ops;
6572   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6573   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6574   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6575 }
6576
6577 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6578 /// specified intrinsic ID.
6579 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6580                                 SelectionDAG &DAG, SDLoc dl,
6581                                 EVT DestVT = MVT::Other) {
6582   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6583   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6584                      DAG.getConstant(IID, dl, MVT::i32), Op);
6585 }
6586
6587 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6588 /// specified intrinsic ID.
6589 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6590                                 SelectionDAG &DAG, SDLoc dl,
6591                                 EVT DestVT = MVT::Other) {
6592   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6593   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6594                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6595 }
6596
6597 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6598 /// specified intrinsic ID.
6599 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6600                                 SDValue Op2, SelectionDAG &DAG,
6601                                 SDLoc dl, EVT DestVT = MVT::Other) {
6602   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6603   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6604                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6605 }
6606
6607
6608 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6609 /// amount.  The result has the specified value type.
6610 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6611                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6612   // Force LHS/RHS to be the right type.
6613   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6614   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6615
6616   int Ops[16];
6617   for (unsigned i = 0; i != 16; ++i)
6618     Ops[i] = i + Amt;
6619   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6620   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6621 }
6622
6623 // If this is a case we can't handle, return null and let the default
6624 // expansion code take care of it.  If we CAN select this case, and if it
6625 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6626 // this case more efficiently than a constant pool load, lower it to the
6627 // sequence of ops that should be used.
6628 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6629                                              SelectionDAG &DAG) const {
6630   SDLoc dl(Op);
6631   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6632   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6633
6634   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6635     // We first build an i32 vector, load it into a QPX register,
6636     // then convert it to a floating-point vector and compare it
6637     // to a zero vector to get the boolean result.
6638     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6639     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6640     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6641     EVT PtrVT = getPointerTy();
6642     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6643
6644     assert(BVN->getNumOperands() == 4 &&
6645       "BUILD_VECTOR for v4i1 does not have 4 operands");
6646
6647     bool IsConst = true;
6648     for (unsigned i = 0; i < 4; ++i) {
6649       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6650       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6651         IsConst = false;
6652         break;
6653       }
6654     }
6655
6656     if (IsConst) {
6657       Constant *One =
6658         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6659       Constant *NegOne =
6660         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6661
6662       SmallVector<Constant*, 4> CV(4, NegOne);
6663       for (unsigned i = 0; i < 4; ++i) {
6664         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6665           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6666         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6667                    getConstantIntValue()->isZero())
6668           continue;
6669         else
6670           CV[i] = One;
6671       }
6672
6673       Constant *CP = ConstantVector::get(CV);
6674       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6675                       16 /* alignment */);
6676  
6677       SmallVector<SDValue, 2> Ops;
6678       Ops.push_back(DAG.getEntryNode());
6679       Ops.push_back(CPIdx);
6680
6681       SmallVector<EVT, 2> ValueVTs;
6682       ValueVTs.push_back(MVT::v4i1);
6683       ValueVTs.push_back(MVT::Other); // chain
6684       SDVTList VTs = DAG.getVTList(ValueVTs);
6685
6686       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6687         dl, VTs, Ops, MVT::v4f32,
6688         MachinePointerInfo::getConstantPool());
6689     }
6690
6691     SmallVector<SDValue, 4> Stores;
6692     for (unsigned i = 0; i < 4; ++i) {
6693       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6694
6695       unsigned Offset = 4*i;
6696       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6697       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6698
6699       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6700       if (StoreSize > 4) {
6701         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6702                                            BVN->getOperand(i), Idx,
6703                                            PtrInfo.getWithOffset(Offset),
6704                                            MVT::i32, false, false, 0));
6705       } else {
6706         SDValue StoreValue = BVN->getOperand(i);
6707         if (StoreSize < 4)
6708           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6709
6710         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6711                                       StoreValue, Idx,
6712                                       PtrInfo.getWithOffset(Offset),
6713                                       false, false, 0));
6714       }
6715     }
6716
6717     SDValue StoreChain;
6718     if (!Stores.empty())
6719       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6720     else
6721       StoreChain = DAG.getEntryNode();
6722
6723     // Now load from v4i32 into the QPX register; this will extend it to
6724     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6725     // is typed as v4f64 because the QPX register integer states are not
6726     // explicitly represented.
6727
6728     SmallVector<SDValue, 2> Ops;
6729     Ops.push_back(StoreChain);
6730     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6731     Ops.push_back(FIdx);
6732
6733     SmallVector<EVT, 2> ValueVTs;
6734     ValueVTs.push_back(MVT::v4f64);
6735     ValueVTs.push_back(MVT::Other); // chain
6736     SDVTList VTs = DAG.getVTList(ValueVTs);
6737
6738     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6739       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6740     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6741       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6742       LoadedVect);
6743
6744     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6745     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6746                           FPZeros, FPZeros, FPZeros, FPZeros);
6747
6748     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6749   }
6750
6751   // All other QPX vectors are handled by generic code.
6752   if (Subtarget.hasQPX())
6753     return SDValue();
6754
6755   // Check if this is a splat of a constant value.
6756   APInt APSplatBits, APSplatUndef;
6757   unsigned SplatBitSize;
6758   bool HasAnyUndefs;
6759   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6760                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6761       SplatBitSize > 32)
6762     return SDValue();
6763
6764   unsigned SplatBits = APSplatBits.getZExtValue();
6765   unsigned SplatUndef = APSplatUndef.getZExtValue();
6766   unsigned SplatSize = SplatBitSize / 8;
6767
6768   // First, handle single instruction cases.
6769
6770   // All zeros?
6771   if (SplatBits == 0) {
6772     // Canonicalize all zero vectors to be v4i32.
6773     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6774       SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6775       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6776       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6777     }
6778     return Op;
6779   }
6780
6781   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6782   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6783                     (32-SplatBitSize));
6784   if (SextVal >= -16 && SextVal <= 15)
6785     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6786
6787
6788   // Two instruction sequences.
6789
6790   // If this value is in the range [-32,30] and is even, use:
6791   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6792   // If this value is in the range [17,31] and is odd, use:
6793   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6794   // If this value is in the range [-31,-17] and is odd, use:
6795   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6796   // Note the last two are three-instruction sequences.
6797   if (SextVal >= -32 && SextVal <= 31) {
6798     // To avoid having these optimizations undone by constant folding,
6799     // we convert to a pseudo that will be expanded later into one of
6800     // the above forms.
6801     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6802     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6803               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6804     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6805     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6806     if (VT == Op.getValueType())
6807       return RetVal;
6808     else
6809       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6810   }
6811
6812   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6813   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6814   // for fneg/fabs.
6815   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6816     // Make -1 and vspltisw -1:
6817     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6818
6819     // Make the VSLW intrinsic, computing 0x8000_0000.
6820     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6821                                    OnesV, DAG, dl);
6822
6823     // xor by OnesV to invert it.
6824     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6825     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6826   }
6827
6828   // Check to see if this is a wide variety of vsplti*, binop self cases.
6829   static const signed char SplatCsts[] = {
6830     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6831     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6832   };
6833
6834   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6835     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6836     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6837     int i = SplatCsts[idx];
6838
6839     // Figure out what shift amount will be used by altivec if shifted by i in
6840     // this splat size.
6841     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6842
6843     // vsplti + shl self.
6844     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6845       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6846       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6847         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6848         Intrinsic::ppc_altivec_vslw
6849       };
6850       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6851       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6852     }
6853
6854     // vsplti + srl self.
6855     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6856       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6857       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6858         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6859         Intrinsic::ppc_altivec_vsrw
6860       };
6861       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6862       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6863     }
6864
6865     // vsplti + sra self.
6866     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6867       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6868       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6869         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6870         Intrinsic::ppc_altivec_vsraw
6871       };
6872       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6873       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6874     }
6875
6876     // vsplti + rol self.
6877     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6878                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6879       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6880       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6881         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6882         Intrinsic::ppc_altivec_vrlw
6883       };
6884       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6885       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6886     }
6887
6888     // t = vsplti c, result = vsldoi t, t, 1
6889     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6890       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6891       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6892     }
6893     // t = vsplti c, result = vsldoi t, t, 2
6894     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6895       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6896       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6897     }
6898     // t = vsplti c, result = vsldoi t, t, 3
6899     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6900       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6901       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6902     }
6903   }
6904
6905   return SDValue();
6906 }
6907
6908 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6909 /// the specified operations to build the shuffle.
6910 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6911                                       SDValue RHS, SelectionDAG &DAG,
6912                                       SDLoc dl) {
6913   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6914   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6915   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6916
6917   enum {
6918     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6919     OP_VMRGHW,
6920     OP_VMRGLW,
6921     OP_VSPLTISW0,
6922     OP_VSPLTISW1,
6923     OP_VSPLTISW2,
6924     OP_VSPLTISW3,
6925     OP_VSLDOI4,
6926     OP_VSLDOI8,
6927     OP_VSLDOI12
6928   };
6929
6930   if (OpNum == OP_COPY) {
6931     if (LHSID == (1*9+2)*9+3) return LHS;
6932     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6933     return RHS;
6934   }
6935
6936   SDValue OpLHS, OpRHS;
6937   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6938   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6939
6940   int ShufIdxs[16];
6941   switch (OpNum) {
6942   default: llvm_unreachable("Unknown i32 permute!");
6943   case OP_VMRGHW:
6944     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6945     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6946     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6947     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6948     break;
6949   case OP_VMRGLW:
6950     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6951     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6952     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6953     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6954     break;
6955   case OP_VSPLTISW0:
6956     for (unsigned i = 0; i != 16; ++i)
6957       ShufIdxs[i] = (i&3)+0;
6958     break;
6959   case OP_VSPLTISW1:
6960     for (unsigned i = 0; i != 16; ++i)
6961       ShufIdxs[i] = (i&3)+4;
6962     break;
6963   case OP_VSPLTISW2:
6964     for (unsigned i = 0; i != 16; ++i)
6965       ShufIdxs[i] = (i&3)+8;
6966     break;
6967   case OP_VSPLTISW3:
6968     for (unsigned i = 0; i != 16; ++i)
6969       ShufIdxs[i] = (i&3)+12;
6970     break;
6971   case OP_VSLDOI4:
6972     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6973   case OP_VSLDOI8:
6974     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6975   case OP_VSLDOI12:
6976     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6977   }
6978   EVT VT = OpLHS.getValueType();
6979   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6980   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6981   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6982   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6983 }
6984
6985 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6986 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6987 /// return the code it can be lowered into.  Worst case, it can always be
6988 /// lowered into a vperm.
6989 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6990                                                SelectionDAG &DAG) const {
6991   SDLoc dl(Op);
6992   SDValue V1 = Op.getOperand(0);
6993   SDValue V2 = Op.getOperand(1);
6994   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6995   EVT VT = Op.getValueType();
6996   bool isLittleEndian = Subtarget.isLittleEndian();
6997
6998   if (Subtarget.hasQPX()) {
6999     if (VT.getVectorNumElements() != 4)
7000       return SDValue();
7001
7002     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7003
7004     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7005     if (AlignIdx != -1) {
7006       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7007                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7008     } else if (SVOp->isSplat()) {
7009       int SplatIdx = SVOp->getSplatIndex();
7010       if (SplatIdx >= 4) {
7011         std::swap(V1, V2);
7012         SplatIdx -= 4;
7013       }
7014
7015       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7016       // nothing to do.
7017
7018       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7019                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7020     }
7021
7022     // Lower this into a qvgpci/qvfperm pair.
7023
7024     // Compute the qvgpci literal
7025     unsigned idx = 0;
7026     for (unsigned i = 0; i < 4; ++i) {
7027       int m = SVOp->getMaskElt(i);
7028       unsigned mm = m >= 0 ? (unsigned) m : i;
7029       idx |= mm << (3-i)*3;
7030     }
7031
7032     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7033                              DAG.getConstant(idx, dl, MVT::i32));
7034     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7035   }
7036
7037   // Cases that are handled by instructions that take permute immediates
7038   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7039   // selected by the instruction selector.
7040   if (V2.getOpcode() == ISD::UNDEF) {
7041     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7042         PPC::isSplatShuffleMask(SVOp, 2) ||
7043         PPC::isSplatShuffleMask(SVOp, 4) ||
7044         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7045         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7046         PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7047         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7048         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7049         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7050         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7051         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7052         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7053         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
7054       return Op;
7055     }
7056   }
7057
7058   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7059   // and produce a fixed permutation.  If any of these match, do not lower to
7060   // VPERM.
7061   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7062   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7063       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7064       PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7065       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7066       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7067       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7068       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7069       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7070       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7071       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
7072     return Op;
7073
7074   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7075   // perfect shuffle table to emit an optimal matching sequence.
7076   ArrayRef<int> PermMask = SVOp->getMask();
7077
7078   unsigned PFIndexes[4];
7079   bool isFourElementShuffle = true;
7080   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7081     unsigned EltNo = 8;   // Start out undef.
7082     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7083       if (PermMask[i*4+j] < 0)
7084         continue;   // Undef, ignore it.
7085
7086       unsigned ByteSource = PermMask[i*4+j];
7087       if ((ByteSource & 3) != j) {
7088         isFourElementShuffle = false;
7089         break;
7090       }
7091
7092       if (EltNo == 8) {
7093         EltNo = ByteSource/4;
7094       } else if (EltNo != ByteSource/4) {
7095         isFourElementShuffle = false;
7096         break;
7097       }
7098     }
7099     PFIndexes[i] = EltNo;
7100   }
7101
7102   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7103   // perfect shuffle vector to determine if it is cost effective to do this as
7104   // discrete instructions, or whether we should use a vperm.
7105   // For now, we skip this for little endian until such time as we have a
7106   // little-endian perfect shuffle table.
7107   if (isFourElementShuffle && !isLittleEndian) {
7108     // Compute the index in the perfect shuffle table.
7109     unsigned PFTableIndex =
7110       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7111
7112     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7113     unsigned Cost  = (PFEntry >> 30);
7114
7115     // Determining when to avoid vperm is tricky.  Many things affect the cost
7116     // of vperm, particularly how many times the perm mask needs to be computed.
7117     // For example, if the perm mask can be hoisted out of a loop or is already
7118     // used (perhaps because there are multiple permutes with the same shuffle
7119     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7120     // the loop requires an extra register.
7121     //
7122     // As a compromise, we only emit discrete instructions if the shuffle can be
7123     // generated in 3 or fewer operations.  When we have loop information
7124     // available, if this block is within a loop, we should avoid using vperm
7125     // for 3-operation perms and use a constant pool load instead.
7126     if (Cost < 3)
7127       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7128   }
7129
7130   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7131   // vector that will get spilled to the constant pool.
7132   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7133
7134   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7135   // that it is in input element units, not in bytes.  Convert now.
7136
7137   // For little endian, the order of the input vectors is reversed, and
7138   // the permutation mask is complemented with respect to 31.  This is
7139   // necessary to produce proper semantics with the big-endian-biased vperm
7140   // instruction.
7141   EVT EltVT = V1.getValueType().getVectorElementType();
7142   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7143
7144   SmallVector<SDValue, 16> ResultMask;
7145   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7146     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7147
7148     for (unsigned j = 0; j != BytesPerElement; ++j)
7149       if (isLittleEndian)
7150         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7151                                              dl, MVT::i32));
7152       else
7153         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7154                                              MVT::i32));
7155   }
7156
7157   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7158                                   ResultMask);
7159   if (isLittleEndian)
7160     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7161                        V2, V1, VPermMask);
7162   else
7163     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7164                        V1, V2, VPermMask);
7165 }
7166
7167 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7168 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7169 /// information about the intrinsic.
7170 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7171                                   bool &isDot, const PPCSubtarget &Subtarget) {
7172   unsigned IntrinsicID =
7173     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7174   CompareOpc = -1;
7175   isDot = false;
7176   switch (IntrinsicID) {
7177   default: return false;
7178     // Comparison predicates.
7179   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7180   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7181   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7182   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7183   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7184   case Intrinsic::ppc_altivec_vcmpequd_p: 
7185     if (Subtarget.hasP8Altivec()) {
7186       CompareOpc = 199; 
7187       isDot = 1; 
7188     }
7189     else 
7190       return false;
7191
7192     break;
7193   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7194   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7195   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7196   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7197   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7198   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7199     if (Subtarget.hasP8Altivec()) {
7200       CompareOpc = 967; 
7201       isDot = 1; 
7202     }
7203     else 
7204       return false;
7205
7206     break;
7207   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7208   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7209   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7210   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7211     if (Subtarget.hasP8Altivec()) {
7212       CompareOpc = 711; 
7213       isDot = 1; 
7214     }
7215     else 
7216       return false;
7217
7218     break;
7219       
7220     // Normal Comparisons.
7221   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7222   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7223   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7224   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7225   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7226   case Intrinsic::ppc_altivec_vcmpequd:
7227     if (Subtarget.hasP8Altivec()) {
7228       CompareOpc = 199; 
7229       isDot = 0; 
7230     }
7231     else
7232       return false;
7233
7234     break;
7235   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7236   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7237   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7238   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7239   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7240   case Intrinsic::ppc_altivec_vcmpgtsd:   
7241     if (Subtarget.hasP8Altivec()) {
7242       CompareOpc = 967; 
7243       isDot = 0; 
7244     }
7245     else
7246       return false;
7247
7248     break;
7249   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7250   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7251   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7252   case Intrinsic::ppc_altivec_vcmpgtud:   
7253     if (Subtarget.hasP8Altivec()) {
7254       CompareOpc = 711; 
7255       isDot = 0; 
7256     }
7257     else
7258       return false;
7259
7260     break;
7261   }
7262   return true;
7263 }
7264
7265 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7266 /// lower, do it, otherwise return null.
7267 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7268                                                    SelectionDAG &DAG) const {
7269   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7270   // opcode number of the comparison.
7271   SDLoc dl(Op);
7272   int CompareOpc;
7273   bool isDot;
7274   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7275     return SDValue();    // Don't custom lower most intrinsics.
7276
7277   // If this is a non-dot comparison, make the VCMP node and we are done.
7278   if (!isDot) {
7279     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7280                               Op.getOperand(1), Op.getOperand(2),
7281                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7282     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7283   }
7284
7285   // Create the PPCISD altivec 'dot' comparison node.
7286   SDValue Ops[] = {
7287     Op.getOperand(2),  // LHS
7288     Op.getOperand(3),  // RHS
7289     DAG.getConstant(CompareOpc, dl, MVT::i32)
7290   };
7291   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7292   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7293
7294   // Now that we have the comparison, emit a copy from the CR to a GPR.
7295   // This is flagged to the above dot comparison.
7296   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7297                                 DAG.getRegister(PPC::CR6, MVT::i32),
7298                                 CompNode.getValue(1));
7299
7300   // Unpack the result based on how the target uses it.
7301   unsigned BitNo;   // Bit # of CR6.
7302   bool InvertBit;   // Invert result?
7303   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7304   default:  // Can't happen, don't crash on invalid number though.
7305   case 0:   // Return the value of the EQ bit of CR6.
7306     BitNo = 0; InvertBit = false;
7307     break;
7308   case 1:   // Return the inverted value of the EQ bit of CR6.
7309     BitNo = 0; InvertBit = true;
7310     break;
7311   case 2:   // Return the value of the LT bit of CR6.
7312     BitNo = 2; InvertBit = false;
7313     break;
7314   case 3:   // Return the inverted value of the LT bit of CR6.
7315     BitNo = 2; InvertBit = true;
7316     break;
7317   }
7318
7319   // Shift the bit into the low position.
7320   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7321                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7322   // Isolate the bit.
7323   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7324                       DAG.getConstant(1, dl, MVT::i32));
7325
7326   // If we are supposed to, toggle the bit.
7327   if (InvertBit)
7328     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7329                         DAG.getConstant(1, dl, MVT::i32));
7330   return Flags;
7331 }
7332
7333 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7334                                                   SelectionDAG &DAG) const {
7335   SDLoc dl(Op);
7336   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7337   // instructions), but for smaller types, we need to first extend up to v2i32
7338   // before doing going farther.
7339   if (Op.getValueType() == MVT::v2i64) {
7340     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7341     if (ExtVT != MVT::v2i32) {
7342       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7343       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7344                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7345                                         ExtVT.getVectorElementType(), 4)));
7346       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7347       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7348                        DAG.getValueType(MVT::v2i32));
7349     }
7350
7351     return Op;
7352   }
7353
7354   return SDValue();
7355 }
7356
7357 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7358                                                    SelectionDAG &DAG) const {
7359   SDLoc dl(Op);
7360   // Create a stack slot that is 16-byte aligned.
7361   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7362   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7363   EVT PtrVT = getPointerTy();
7364   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7365
7366   // Store the input value into Value#0 of the stack slot.
7367   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7368                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7369                                false, false, 0);
7370   // Load it out.
7371   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7372                      false, false, false, 0);
7373 }
7374
7375 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7376                                                    SelectionDAG &DAG) const {
7377   SDLoc dl(Op);
7378   SDNode *N = Op.getNode();
7379
7380   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7381          "Unknown extract_vector_elt type");
7382
7383   SDValue Value = N->getOperand(0);
7384
7385   // The first part of this is like the store lowering except that we don't
7386   // need to track the chain.
7387
7388   // The values are now known to be -1 (false) or 1 (true). To convert this
7389   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7390   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7391   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7392
7393   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7394   // understand how to form the extending load.
7395   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7396   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7397                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7398
7399   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7400
7401   // Now convert to an integer and store.
7402   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7403     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7404     Value);
7405
7406   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7407   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7408   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7409   EVT PtrVT = getPointerTy();
7410   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7411
7412   SDValue StoreChain = DAG.getEntryNode();
7413   SmallVector<SDValue, 2> Ops;
7414   Ops.push_back(StoreChain);
7415   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7416   Ops.push_back(Value);
7417   Ops.push_back(FIdx);
7418
7419   SmallVector<EVT, 2> ValueVTs;
7420   ValueVTs.push_back(MVT::Other); // chain
7421   SDVTList VTs = DAG.getVTList(ValueVTs);
7422
7423   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7424     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7425
7426   // Extract the value requested.
7427   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7428   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7429   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7430
7431   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7432                                PtrInfo.getWithOffset(Offset),
7433                                false, false, false, 0);
7434
7435   if (!Subtarget.useCRBits())
7436     return IntVal;
7437
7438   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7439 }
7440
7441 /// Lowering for QPX v4i1 loads
7442 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7443                                            SelectionDAG &DAG) const {
7444   SDLoc dl(Op);
7445   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7446   SDValue LoadChain = LN->getChain();
7447   SDValue BasePtr = LN->getBasePtr();
7448
7449   if (Op.getValueType() == MVT::v4f64 ||
7450       Op.getValueType() == MVT::v4f32) {
7451     EVT MemVT = LN->getMemoryVT();
7452     unsigned Alignment = LN->getAlignment();
7453
7454     // If this load is properly aligned, then it is legal.
7455     if (Alignment >= MemVT.getStoreSize())
7456       return Op;
7457
7458     EVT ScalarVT = Op.getValueType().getScalarType(),
7459         ScalarMemVT = MemVT.getScalarType();
7460     unsigned Stride = ScalarMemVT.getStoreSize();
7461
7462     SmallVector<SDValue, 8> Vals, LoadChains;
7463     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7464       SDValue Load;
7465       if (ScalarVT != ScalarMemVT)
7466         Load =
7467           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7468                          BasePtr,
7469                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7470                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7471                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7472                          LN->getAAInfo());
7473       else
7474         Load =
7475           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7476                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7477                        LN->isVolatile(), LN->isNonTemporal(),
7478                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7479                        LN->getAAInfo());
7480
7481       if (Idx == 0 && LN->isIndexed()) {
7482         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7483                "Unknown addressing mode on vector load");
7484         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7485                                   LN->getAddressingMode());
7486       }
7487
7488       Vals.push_back(Load);
7489       LoadChains.push_back(Load.getValue(1));
7490
7491       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7492                             DAG.getConstant(Stride, dl,
7493                                             BasePtr.getValueType()));
7494     }
7495
7496     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7497     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7498                                 Op.getValueType(), Vals);
7499
7500     if (LN->isIndexed()) {
7501       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7502       return DAG.getMergeValues(RetOps, dl);
7503     }
7504
7505     SDValue RetOps[] = { Value, TF };
7506     return DAG.getMergeValues(RetOps, dl);
7507   }
7508
7509   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7510   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7511
7512   // To lower v4i1 from a byte array, we load the byte elements of the
7513   // vector and then reuse the BUILD_VECTOR logic.
7514
7515   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7516   for (unsigned i = 0; i < 4; ++i) {
7517     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7518     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7519
7520     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7521                         dl, MVT::i32, LoadChain, Idx,
7522                         LN->getPointerInfo().getWithOffset(i),
7523                         MVT::i8 /* memory type */,
7524                         LN->isVolatile(), LN->isNonTemporal(),
7525                         LN->isInvariant(),
7526                         1 /* alignment */, LN->getAAInfo()));
7527     VectElmtChains.push_back(VectElmts[i].getValue(1));
7528   }
7529
7530   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7531   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7532
7533   SDValue RVals[] = { Value, LoadChain };
7534   return DAG.getMergeValues(RVals, dl);
7535 }
7536
7537 /// Lowering for QPX v4i1 stores
7538 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7539                                             SelectionDAG &DAG) const {
7540   SDLoc dl(Op);
7541   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7542   SDValue StoreChain = SN->getChain();
7543   SDValue BasePtr = SN->getBasePtr();
7544   SDValue Value = SN->getValue();
7545
7546   if (Value.getValueType() == MVT::v4f64 ||
7547       Value.getValueType() == MVT::v4f32) {
7548     EVT MemVT = SN->getMemoryVT();
7549     unsigned Alignment = SN->getAlignment();
7550
7551     // If this store is properly aligned, then it is legal.
7552     if (Alignment >= MemVT.getStoreSize())
7553       return Op;
7554
7555     EVT ScalarVT = Value.getValueType().getScalarType(),
7556         ScalarMemVT = MemVT.getScalarType();
7557     unsigned Stride = ScalarMemVT.getStoreSize();
7558
7559     SmallVector<SDValue, 8> Stores;
7560     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7561       SDValue Ex =
7562         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7563                     DAG.getConstant(Idx, dl, getVectorIdxTy()));
7564       SDValue Store;
7565       if (ScalarVT != ScalarMemVT)
7566         Store =
7567           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7568                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7569                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7570                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7571       else
7572         Store =
7573           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7574                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7575                        SN->isVolatile(), SN->isNonTemporal(),
7576                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7577
7578       if (Idx == 0 && SN->isIndexed()) {
7579         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7580                "Unknown addressing mode on vector store");
7581         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7582                                     SN->getAddressingMode());
7583       }
7584
7585       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7586                             DAG.getConstant(Stride, dl,
7587                                             BasePtr.getValueType()));
7588       Stores.push_back(Store);
7589     }
7590
7591     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7592
7593     if (SN->isIndexed()) {
7594       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7595       return DAG.getMergeValues(RetOps, dl);
7596     }
7597
7598     return TF;
7599   }
7600
7601   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7602   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7603
7604   // The values are now known to be -1 (false) or 1 (true). To convert this
7605   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7606   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7607   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7608
7609   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7610   // understand how to form the extending load.
7611   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7612   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7613                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7614
7615   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7616
7617   // Now convert to an integer and store.
7618   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7619     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7620     Value);
7621
7622   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7623   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7624   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7625   EVT PtrVT = getPointerTy();
7626   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7627
7628   SmallVector<SDValue, 2> Ops;
7629   Ops.push_back(StoreChain);
7630   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7631   Ops.push_back(Value);
7632   Ops.push_back(FIdx);
7633
7634   SmallVector<EVT, 2> ValueVTs;
7635   ValueVTs.push_back(MVT::Other); // chain
7636   SDVTList VTs = DAG.getVTList(ValueVTs);
7637
7638   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7639     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7640
7641   // Move data into the byte array.
7642   SmallVector<SDValue, 4> Loads, LoadChains;
7643   for (unsigned i = 0; i < 4; ++i) {
7644     unsigned Offset = 4*i;
7645     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7646     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7647
7648     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7649                                    PtrInfo.getWithOffset(Offset),
7650                                    false, false, false, 0));
7651     LoadChains.push_back(Loads[i].getValue(1));
7652   }
7653
7654   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7655
7656   SmallVector<SDValue, 4> Stores;
7657   for (unsigned i = 0; i < 4; ++i) {
7658     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7659     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7660
7661     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7662                                        SN->getPointerInfo().getWithOffset(i),
7663                                        MVT::i8 /* memory type */,
7664                                        SN->isNonTemporal(), SN->isVolatile(), 
7665                                        1 /* alignment */, SN->getAAInfo()));
7666   }
7667
7668   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7669
7670   return StoreChain;
7671 }
7672
7673 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7674   SDLoc dl(Op);
7675   if (Op.getValueType() == MVT::v4i32) {
7676     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7677
7678     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7679     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7680
7681     SDValue RHSSwap =   // = vrlw RHS, 16
7682       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7683
7684     // Shrinkify inputs to v8i16.
7685     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7686     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7687     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7688
7689     // Low parts multiplied together, generating 32-bit results (we ignore the
7690     // top parts).
7691     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7692                                         LHS, RHS, DAG, dl, MVT::v4i32);
7693
7694     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7695                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7696     // Shift the high parts up 16 bits.
7697     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7698                               Neg16, DAG, dl);
7699     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7700   } else if (Op.getValueType() == MVT::v8i16) {
7701     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7702
7703     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7704
7705     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7706                             LHS, RHS, Zero, DAG, dl);
7707   } else if (Op.getValueType() == MVT::v16i8) {
7708     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7709     bool isLittleEndian = Subtarget.isLittleEndian();
7710
7711     // Multiply the even 8-bit parts, producing 16-bit sums.
7712     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7713                                            LHS, RHS, DAG, dl, MVT::v8i16);
7714     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7715
7716     // Multiply the odd 8-bit parts, producing 16-bit sums.
7717     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7718                                           LHS, RHS, DAG, dl, MVT::v8i16);
7719     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7720
7721     // Merge the results together.  Because vmuleub and vmuloub are
7722     // instructions with a big-endian bias, we must reverse the
7723     // element numbering and reverse the meaning of "odd" and "even"
7724     // when generating little endian code.
7725     int Ops[16];
7726     for (unsigned i = 0; i != 8; ++i) {
7727       if (isLittleEndian) {
7728         Ops[i*2  ] = 2*i;
7729         Ops[i*2+1] = 2*i+16;
7730       } else {
7731         Ops[i*2  ] = 2*i+1;
7732         Ops[i*2+1] = 2*i+1+16;
7733       }
7734     }
7735     if (isLittleEndian)
7736       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7737     else
7738       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7739   } else {
7740     llvm_unreachable("Unknown mul to lower!");
7741   }
7742 }
7743
7744 /// LowerOperation - Provide custom lowering hooks for some operations.
7745 ///
7746 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7747   switch (Op.getOpcode()) {
7748   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7749   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7750   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7751   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7752   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7753   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7754   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7755   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7756   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7757   case ISD::VASTART:
7758     return LowerVASTART(Op, DAG, Subtarget);
7759
7760   case ISD::VAARG:
7761     return LowerVAARG(Op, DAG, Subtarget);
7762
7763   case ISD::VACOPY:
7764     return LowerVACOPY(Op, DAG, Subtarget);
7765
7766   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7767   case ISD::DYNAMIC_STACKALLOC:
7768     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7769
7770   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7771   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7772
7773   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7774   case ISD::STORE:              return LowerSTORE(Op, DAG);
7775   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7776   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7777   case ISD::FP_TO_UINT:
7778   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7779                                                       SDLoc(Op));
7780   case ISD::UINT_TO_FP:
7781   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7782   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7783
7784   // Lower 64-bit shifts.
7785   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7786   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7787   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7788
7789   // Vector-related lowering.
7790   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7791   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7792   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7793   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7794   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7795   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7796   case ISD::MUL:                return LowerMUL(Op, DAG);
7797
7798   // For counter-based loop handling.
7799   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7800
7801   // Frame & Return address.
7802   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7803   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7804   }
7805 }
7806
7807 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7808                                            SmallVectorImpl<SDValue>&Results,
7809                                            SelectionDAG &DAG) const {
7810   SDLoc dl(N);
7811   switch (N->getOpcode()) {
7812   default:
7813     llvm_unreachable("Do not know how to custom type legalize this operation!");
7814   case ISD::READCYCLECOUNTER: {
7815     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7816     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7817
7818     Results.push_back(RTB);
7819     Results.push_back(RTB.getValue(1));
7820     Results.push_back(RTB.getValue(2));
7821     break;
7822   }
7823   case ISD::INTRINSIC_W_CHAIN: {
7824     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7825         Intrinsic::ppc_is_decremented_ctr_nonzero)
7826       break;
7827
7828     assert(N->getValueType(0) == MVT::i1 &&
7829            "Unexpected result type for CTR decrement intrinsic");
7830     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7831     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7832     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7833                                  N->getOperand(1)); 
7834
7835     Results.push_back(NewInt);
7836     Results.push_back(NewInt.getValue(1));
7837     break;
7838   }
7839   case ISD::VAARG: {
7840     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7841       return;
7842
7843     EVT VT = N->getValueType(0);
7844
7845     if (VT == MVT::i64) {
7846       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7847
7848       Results.push_back(NewNode);
7849       Results.push_back(NewNode.getValue(1));
7850     }
7851     return;
7852   }
7853   case ISD::FP_ROUND_INREG: {
7854     assert(N->getValueType(0) == MVT::ppcf128);
7855     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7856     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7857                              MVT::f64, N->getOperand(0),
7858                              DAG.getIntPtrConstant(0, dl));
7859     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7860                              MVT::f64, N->getOperand(0),
7861                              DAG.getIntPtrConstant(1, dl));
7862
7863     // Add the two halves of the long double in round-to-zero mode.
7864     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7865
7866     // We know the low half is about to be thrown away, so just use something
7867     // convenient.
7868     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7869                                 FPreg, FPreg));
7870     return;
7871   }
7872   case ISD::FP_TO_SINT:
7873   case ISD::FP_TO_UINT:
7874     // LowerFP_TO_INT() can only handle f32 and f64.
7875     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7876       return;
7877     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7878     return;
7879   }
7880 }
7881
7882
7883 //===----------------------------------------------------------------------===//
7884 //  Other Lowering Code
7885 //===----------------------------------------------------------------------===//
7886
7887 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7888   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7889   Function *Func = Intrinsic::getDeclaration(M, Id);
7890   return Builder.CreateCall(Func, {});
7891 }
7892
7893 // The mappings for emitLeading/TrailingFence is taken from
7894 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7895 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7896                                          AtomicOrdering Ord, bool IsStore,
7897                                          bool IsLoad) const {
7898   if (Ord == SequentiallyConsistent)
7899     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7900   if (isAtLeastRelease(Ord))
7901     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7902   return nullptr;
7903 }
7904
7905 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7906                                           AtomicOrdering Ord, bool IsStore,
7907                                           bool IsLoad) const {
7908   if (IsLoad && isAtLeastAcquire(Ord))
7909     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7910   // FIXME: this is too conservative, a dependent branch + isync is enough.
7911   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7912   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7913   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7914   return nullptr;
7915 }
7916
7917 MachineBasicBlock *
7918 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7919                                     unsigned AtomicSize,
7920                                     unsigned BinOpcode) const {
7921   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7922   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7923
7924   auto LoadMnemonic = PPC::LDARX;
7925   auto StoreMnemonic = PPC::STDCX;
7926   switch (AtomicSize) {
7927   default:
7928     llvm_unreachable("Unexpected size of atomic entity");
7929   case 1:
7930     LoadMnemonic = PPC::LBARX;
7931     StoreMnemonic = PPC::STBCX;
7932     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7933     break;
7934   case 2:
7935     LoadMnemonic = PPC::LHARX;
7936     StoreMnemonic = PPC::STHCX;
7937     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7938     break;
7939   case 4:
7940     LoadMnemonic = PPC::LWARX;
7941     StoreMnemonic = PPC::STWCX;
7942     break;
7943   case 8:
7944     LoadMnemonic = PPC::LDARX;
7945     StoreMnemonic = PPC::STDCX;
7946     break;
7947   }
7948
7949   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7950   MachineFunction *F = BB->getParent();
7951   MachineFunction::iterator It = BB;
7952   ++It;
7953
7954   unsigned dest = MI->getOperand(0).getReg();
7955   unsigned ptrA = MI->getOperand(1).getReg();
7956   unsigned ptrB = MI->getOperand(2).getReg();
7957   unsigned incr = MI->getOperand(3).getReg();
7958   DebugLoc dl = MI->getDebugLoc();
7959
7960   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7961   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7962   F->insert(It, loopMBB);
7963   F->insert(It, exitMBB);
7964   exitMBB->splice(exitMBB->begin(), BB,
7965                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7966   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7967
7968   MachineRegisterInfo &RegInfo = F->getRegInfo();
7969   unsigned TmpReg = (!BinOpcode) ? incr :
7970     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7971                                            : &PPC::GPRCRegClass);
7972
7973   //  thisMBB:
7974   //   ...
7975   //   fallthrough --> loopMBB
7976   BB->addSuccessor(loopMBB);
7977
7978   //  loopMBB:
7979   //   l[wd]arx dest, ptr
7980   //   add r0, dest, incr
7981   //   st[wd]cx. r0, ptr
7982   //   bne- loopMBB
7983   //   fallthrough --> exitMBB
7984   BB = loopMBB;
7985   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7986     .addReg(ptrA).addReg(ptrB);
7987   if (BinOpcode)
7988     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7989   BuildMI(BB, dl, TII->get(StoreMnemonic))
7990     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7991   BuildMI(BB, dl, TII->get(PPC::BCC))
7992     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7993   BB->addSuccessor(loopMBB);
7994   BB->addSuccessor(exitMBB);
7995
7996   //  exitMBB:
7997   //   ...
7998   BB = exitMBB;
7999   return BB;
8000 }
8001
8002 MachineBasicBlock *
8003 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8004                                             MachineBasicBlock *BB,
8005                                             bool is8bit,    // operation
8006                                             unsigned BinOpcode) const {
8007   // If we support part-word atomic mnemonics, just use them
8008   if (Subtarget.hasPartwordAtomics())
8009     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8010
8011   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8012   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8013   // In 64 bit mode we have to use 64 bits for addresses, even though the
8014   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8015   // registers without caring whether they're 32 or 64, but here we're
8016   // doing actual arithmetic on the addresses.
8017   bool is64bit = Subtarget.isPPC64();
8018   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8019
8020   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8021   MachineFunction *F = BB->getParent();
8022   MachineFunction::iterator It = BB;
8023   ++It;
8024
8025   unsigned dest = MI->getOperand(0).getReg();
8026   unsigned ptrA = MI->getOperand(1).getReg();
8027   unsigned ptrB = MI->getOperand(2).getReg();
8028   unsigned incr = MI->getOperand(3).getReg();
8029   DebugLoc dl = MI->getDebugLoc();
8030
8031   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8032   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8033   F->insert(It, loopMBB);
8034   F->insert(It, exitMBB);
8035   exitMBB->splice(exitMBB->begin(), BB,
8036                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8037   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8038
8039   MachineRegisterInfo &RegInfo = F->getRegInfo();
8040   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8041                                           : &PPC::GPRCRegClass;
8042   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8043   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8044   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8045   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8046   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8047   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8048   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8049   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8050   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8051   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8052   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8053   unsigned Ptr1Reg;
8054   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8055
8056   //  thisMBB:
8057   //   ...
8058   //   fallthrough --> loopMBB
8059   BB->addSuccessor(loopMBB);
8060
8061   // The 4-byte load must be aligned, while a char or short may be
8062   // anywhere in the word.  Hence all this nasty bookkeeping code.
8063   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8064   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8065   //   xori shift, shift1, 24 [16]
8066   //   rlwinm ptr, ptr1, 0, 0, 29
8067   //   slw incr2, incr, shift
8068   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8069   //   slw mask, mask2, shift
8070   //  loopMBB:
8071   //   lwarx tmpDest, ptr
8072   //   add tmp, tmpDest, incr2
8073   //   andc tmp2, tmpDest, mask
8074   //   and tmp3, tmp, mask
8075   //   or tmp4, tmp3, tmp2
8076   //   stwcx. tmp4, ptr
8077   //   bne- loopMBB
8078   //   fallthrough --> exitMBB
8079   //   srw dest, tmpDest, shift
8080   if (ptrA != ZeroReg) {
8081     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8082     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8083       .addReg(ptrA).addReg(ptrB);
8084   } else {
8085     Ptr1Reg = ptrB;
8086   }
8087   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8088       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8089   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8090       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8091   if (is64bit)
8092     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8093       .addReg(Ptr1Reg).addImm(0).addImm(61);
8094   else
8095     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8096       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8097   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8098       .addReg(incr).addReg(ShiftReg);
8099   if (is8bit)
8100     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8101   else {
8102     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8103     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8104   }
8105   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8106       .addReg(Mask2Reg).addReg(ShiftReg);
8107
8108   BB = loopMBB;
8109   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8110     .addReg(ZeroReg).addReg(PtrReg);
8111   if (BinOpcode)
8112     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8113       .addReg(Incr2Reg).addReg(TmpDestReg);
8114   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8115     .addReg(TmpDestReg).addReg(MaskReg);
8116   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8117     .addReg(TmpReg).addReg(MaskReg);
8118   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8119     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8120   BuildMI(BB, dl, TII->get(PPC::STWCX))
8121     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8122   BuildMI(BB, dl, TII->get(PPC::BCC))
8123     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8124   BB->addSuccessor(loopMBB);
8125   BB->addSuccessor(exitMBB);
8126
8127   //  exitMBB:
8128   //   ...
8129   BB = exitMBB;
8130   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8131     .addReg(ShiftReg);
8132   return BB;
8133 }
8134
8135 llvm::MachineBasicBlock*
8136 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8137                                     MachineBasicBlock *MBB) const {
8138   DebugLoc DL = MI->getDebugLoc();
8139   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8140
8141   MachineFunction *MF = MBB->getParent();
8142   MachineRegisterInfo &MRI = MF->getRegInfo();
8143
8144   const BasicBlock *BB = MBB->getBasicBlock();
8145   MachineFunction::iterator I = MBB;
8146   ++I;
8147
8148   // Memory Reference
8149   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8150   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8151
8152   unsigned DstReg = MI->getOperand(0).getReg();
8153   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8154   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8155   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8156   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8157
8158   MVT PVT = getPointerTy();
8159   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8160          "Invalid Pointer Size!");
8161   // For v = setjmp(buf), we generate
8162   //
8163   // thisMBB:
8164   //  SjLjSetup mainMBB
8165   //  bl mainMBB
8166   //  v_restore = 1
8167   //  b sinkMBB
8168   //
8169   // mainMBB:
8170   //  buf[LabelOffset] = LR
8171   //  v_main = 0
8172   //
8173   // sinkMBB:
8174   //  v = phi(main, restore)
8175   //
8176
8177   MachineBasicBlock *thisMBB = MBB;
8178   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8179   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8180   MF->insert(I, mainMBB);
8181   MF->insert(I, sinkMBB);
8182
8183   MachineInstrBuilder MIB;
8184
8185   // Transfer the remainder of BB and its successor edges to sinkMBB.
8186   sinkMBB->splice(sinkMBB->begin(), MBB,
8187                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8188   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8189
8190   // Note that the structure of the jmp_buf used here is not compatible
8191   // with that used by libc, and is not designed to be. Specifically, it
8192   // stores only those 'reserved' registers that LLVM does not otherwise
8193   // understand how to spill. Also, by convention, by the time this
8194   // intrinsic is called, Clang has already stored the frame address in the
8195   // first slot of the buffer and stack address in the third. Following the
8196   // X86 target code, we'll store the jump address in the second slot. We also
8197   // need to save the TOC pointer (R2) to handle jumps between shared
8198   // libraries, and that will be stored in the fourth slot. The thread
8199   // identifier (R13) is not affected.
8200
8201   // thisMBB:
8202   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8203   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8204   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8205
8206   // Prepare IP either in reg.
8207   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8208   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8209   unsigned BufReg = MI->getOperand(1).getReg();
8210
8211   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8212     setUsesTOCBasePtr(*MBB->getParent());
8213     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8214             .addReg(PPC::X2)
8215             .addImm(TOCOffset)
8216             .addReg(BufReg);
8217     MIB.setMemRefs(MMOBegin, MMOEnd);
8218   }
8219
8220   // Naked functions never have a base pointer, and so we use r1. For all
8221   // other functions, this decision must be delayed until during PEI.
8222   unsigned BaseReg;
8223   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8224     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8225   else
8226     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8227
8228   MIB = BuildMI(*thisMBB, MI, DL,
8229                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8230             .addReg(BaseReg)
8231             .addImm(BPOffset)
8232             .addReg(BufReg);
8233   MIB.setMemRefs(MMOBegin, MMOEnd);
8234
8235   // Setup
8236   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8237   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8238   MIB.addRegMask(TRI->getNoPreservedMask());
8239
8240   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8241
8242   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8243           .addMBB(mainMBB);
8244   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8245
8246   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8247   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8248
8249   // mainMBB:
8250   //  mainDstReg = 0
8251   MIB =
8252       BuildMI(mainMBB, DL,
8253               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8254
8255   // Store IP
8256   if (Subtarget.isPPC64()) {
8257     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8258             .addReg(LabelReg)
8259             .addImm(LabelOffset)
8260             .addReg(BufReg);
8261   } else {
8262     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8263             .addReg(LabelReg)
8264             .addImm(LabelOffset)
8265             .addReg(BufReg);
8266   }
8267
8268   MIB.setMemRefs(MMOBegin, MMOEnd);
8269
8270   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8271   mainMBB->addSuccessor(sinkMBB);
8272
8273   // sinkMBB:
8274   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8275           TII->get(PPC::PHI), DstReg)
8276     .addReg(mainDstReg).addMBB(mainMBB)
8277     .addReg(restoreDstReg).addMBB(thisMBB);
8278
8279   MI->eraseFromParent();
8280   return sinkMBB;
8281 }
8282
8283 MachineBasicBlock *
8284 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8285                                      MachineBasicBlock *MBB) const {
8286   DebugLoc DL = MI->getDebugLoc();
8287   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8288
8289   MachineFunction *MF = MBB->getParent();
8290   MachineRegisterInfo &MRI = MF->getRegInfo();
8291
8292   // Memory Reference
8293   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8294   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8295
8296   MVT PVT = getPointerTy();
8297   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8298          "Invalid Pointer Size!");
8299
8300   const TargetRegisterClass *RC =
8301     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8302   unsigned Tmp = MRI.createVirtualRegister(RC);
8303   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8304   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8305   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8306   unsigned BP =
8307       (PVT == MVT::i64)
8308           ? PPC::X30
8309           : (Subtarget.isSVR4ABI() &&
8310                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8311                  ? PPC::R29
8312                  : PPC::R30);
8313
8314   MachineInstrBuilder MIB;
8315
8316   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8317   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8318   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8319   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8320
8321   unsigned BufReg = MI->getOperand(0).getReg();
8322
8323   // Reload FP (the jumped-to function may not have had a
8324   // frame pointer, and if so, then its r31 will be restored
8325   // as necessary).
8326   if (PVT == MVT::i64) {
8327     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8328             .addImm(0)
8329             .addReg(BufReg);
8330   } else {
8331     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8332             .addImm(0)
8333             .addReg(BufReg);
8334   }
8335   MIB.setMemRefs(MMOBegin, MMOEnd);
8336
8337   // Reload IP
8338   if (PVT == MVT::i64) {
8339     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8340             .addImm(LabelOffset)
8341             .addReg(BufReg);
8342   } else {
8343     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8344             .addImm(LabelOffset)
8345             .addReg(BufReg);
8346   }
8347   MIB.setMemRefs(MMOBegin, MMOEnd);
8348
8349   // Reload SP
8350   if (PVT == MVT::i64) {
8351     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8352             .addImm(SPOffset)
8353             .addReg(BufReg);
8354   } else {
8355     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8356             .addImm(SPOffset)
8357             .addReg(BufReg);
8358   }
8359   MIB.setMemRefs(MMOBegin, MMOEnd);
8360
8361   // Reload BP
8362   if (PVT == MVT::i64) {
8363     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8364             .addImm(BPOffset)
8365             .addReg(BufReg);
8366   } else {
8367     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8368             .addImm(BPOffset)
8369             .addReg(BufReg);
8370   }
8371   MIB.setMemRefs(MMOBegin, MMOEnd);
8372
8373   // Reload TOC
8374   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8375     setUsesTOCBasePtr(*MBB->getParent());
8376     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8377             .addImm(TOCOffset)
8378             .addReg(BufReg);
8379
8380     MIB.setMemRefs(MMOBegin, MMOEnd);
8381   }
8382
8383   // Jump
8384   BuildMI(*MBB, MI, DL,
8385           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8386   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8387
8388   MI->eraseFromParent();
8389   return MBB;
8390 }
8391
8392 MachineBasicBlock *
8393 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8394                                                MachineBasicBlock *BB) const {
8395   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8396       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8397     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8398         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8399       // Call lowering should have added an r2 operand to indicate a dependence
8400       // on the TOC base pointer value. It can't however, because there is no
8401       // way to mark the dependence as implicit there, and so the stackmap code
8402       // will confuse it with a regular operand. Instead, add the dependence
8403       // here.
8404       setUsesTOCBasePtr(*BB->getParent());
8405       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8406     }
8407
8408     return emitPatchPoint(MI, BB);
8409   }
8410
8411   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8412       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8413     return emitEHSjLjSetJmp(MI, BB);
8414   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8415              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8416     return emitEHSjLjLongJmp(MI, BB);
8417   }
8418
8419   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8420
8421   // To "insert" these instructions we actually have to insert their
8422   // control-flow patterns.
8423   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8424   MachineFunction::iterator It = BB;
8425   ++It;
8426
8427   MachineFunction *F = BB->getParent();
8428
8429   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8430                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8431                               MI->getOpcode() == PPC::SELECT_I4 ||
8432                               MI->getOpcode() == PPC::SELECT_I8)) {
8433     SmallVector<MachineOperand, 2> Cond;
8434     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8435         MI->getOpcode() == PPC::SELECT_CC_I8)
8436       Cond.push_back(MI->getOperand(4));
8437     else
8438       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8439     Cond.push_back(MI->getOperand(1));
8440
8441     DebugLoc dl = MI->getDebugLoc();
8442     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8443                       Cond, MI->getOperand(2).getReg(),
8444                       MI->getOperand(3).getReg());
8445   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8446              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8447              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8448              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8449              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8450              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8451              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8452              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8453              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8454              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8455              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8456              MI->getOpcode() == PPC::SELECT_I4 ||
8457              MI->getOpcode() == PPC::SELECT_I8 ||
8458              MI->getOpcode() == PPC::SELECT_F4 ||
8459              MI->getOpcode() == PPC::SELECT_F8 ||
8460              MI->getOpcode() == PPC::SELECT_QFRC ||
8461              MI->getOpcode() == PPC::SELECT_QSRC ||
8462              MI->getOpcode() == PPC::SELECT_QBRC ||
8463              MI->getOpcode() == PPC::SELECT_VRRC ||
8464              MI->getOpcode() == PPC::SELECT_VSFRC ||
8465              MI->getOpcode() == PPC::SELECT_VSSRC ||
8466              MI->getOpcode() == PPC::SELECT_VSRC) {
8467     // The incoming instruction knows the destination vreg to set, the
8468     // condition code register to branch on, the true/false values to
8469     // select between, and a branch opcode to use.
8470
8471     //  thisMBB:
8472     //  ...
8473     //   TrueVal = ...
8474     //   cmpTY ccX, r1, r2
8475     //   bCC copy1MBB
8476     //   fallthrough --> copy0MBB
8477     MachineBasicBlock *thisMBB = BB;
8478     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8479     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8480     DebugLoc dl = MI->getDebugLoc();
8481     F->insert(It, copy0MBB);
8482     F->insert(It, sinkMBB);
8483
8484     // Transfer the remainder of BB and its successor edges to sinkMBB.
8485     sinkMBB->splice(sinkMBB->begin(), BB,
8486                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8487     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8488
8489     // Next, add the true and fallthrough blocks as its successors.
8490     BB->addSuccessor(copy0MBB);
8491     BB->addSuccessor(sinkMBB);
8492
8493     if (MI->getOpcode() == PPC::SELECT_I4 ||
8494         MI->getOpcode() == PPC::SELECT_I8 ||
8495         MI->getOpcode() == PPC::SELECT_F4 ||
8496         MI->getOpcode() == PPC::SELECT_F8 ||
8497         MI->getOpcode() == PPC::SELECT_QFRC ||
8498         MI->getOpcode() == PPC::SELECT_QSRC ||
8499         MI->getOpcode() == PPC::SELECT_QBRC ||
8500         MI->getOpcode() == PPC::SELECT_VRRC ||
8501         MI->getOpcode() == PPC::SELECT_VSFRC ||
8502         MI->getOpcode() == PPC::SELECT_VSSRC ||
8503         MI->getOpcode() == PPC::SELECT_VSRC) {
8504       BuildMI(BB, dl, TII->get(PPC::BC))
8505         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8506     } else {
8507       unsigned SelectPred = MI->getOperand(4).getImm();
8508       BuildMI(BB, dl, TII->get(PPC::BCC))
8509         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8510     }
8511
8512     //  copy0MBB:
8513     //   %FalseValue = ...
8514     //   # fallthrough to sinkMBB
8515     BB = copy0MBB;
8516
8517     // Update machine-CFG edges
8518     BB->addSuccessor(sinkMBB);
8519
8520     //  sinkMBB:
8521     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8522     //  ...
8523     BB = sinkMBB;
8524     BuildMI(*BB, BB->begin(), dl,
8525             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8526       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8527       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8528   } else if (MI->getOpcode() == PPC::ReadTB) {
8529     // To read the 64-bit time-base register on a 32-bit target, we read the
8530     // two halves. Should the counter have wrapped while it was being read, we
8531     // need to try again.
8532     // ...
8533     // readLoop:
8534     // mfspr Rx,TBU # load from TBU
8535     // mfspr Ry,TB  # load from TB
8536     // mfspr Rz,TBU # load from TBU
8537     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8538     // bne readLoop   # branch if they're not equal
8539     // ...
8540
8541     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8542     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8543     DebugLoc dl = MI->getDebugLoc();
8544     F->insert(It, readMBB);
8545     F->insert(It, sinkMBB);
8546
8547     // Transfer the remainder of BB and its successor edges to sinkMBB.
8548     sinkMBB->splice(sinkMBB->begin(), BB,
8549                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8550     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8551
8552     BB->addSuccessor(readMBB);
8553     BB = readMBB;
8554
8555     MachineRegisterInfo &RegInfo = F->getRegInfo();
8556     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8557     unsigned LoReg = MI->getOperand(0).getReg();
8558     unsigned HiReg = MI->getOperand(1).getReg();
8559
8560     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8561     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8562     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8563
8564     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8565
8566     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8567       .addReg(HiReg).addReg(ReadAgainReg);
8568     BuildMI(BB, dl, TII->get(PPC::BCC))
8569       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8570
8571     BB->addSuccessor(readMBB);
8572     BB->addSuccessor(sinkMBB);
8573   }
8574   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8575     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8576   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8577     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8578   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8579     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8580   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8581     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8582
8583   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8584     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8585   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8586     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8587   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8588     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8589   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8590     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8591
8592   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8593     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8594   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8595     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8596   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8597     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8598   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8599     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8600
8601   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8602     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8603   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8604     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8605   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8606     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8607   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8608     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8609
8610   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8611     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8612   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8613     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8614   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8615     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8616   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8617     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8618
8619   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8620     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8621   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8622     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8623   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8624     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8625   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8626     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8627
8628   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8629     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8630   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8631     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8632   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8633     BB = EmitAtomicBinary(MI, BB, 4, 0);
8634   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8635     BB = EmitAtomicBinary(MI, BB, 8, 0);
8636
8637   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8638            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8639            (Subtarget.hasPartwordAtomics() &&
8640             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8641            (Subtarget.hasPartwordAtomics() &&
8642             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8643     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8644
8645     auto LoadMnemonic = PPC::LDARX;
8646     auto StoreMnemonic = PPC::STDCX;
8647     switch(MI->getOpcode()) {
8648     default:
8649       llvm_unreachable("Compare and swap of unknown size");
8650     case PPC::ATOMIC_CMP_SWAP_I8:
8651       LoadMnemonic = PPC::LBARX;
8652       StoreMnemonic = PPC::STBCX;
8653       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8654       break;
8655     case PPC::ATOMIC_CMP_SWAP_I16:
8656       LoadMnemonic = PPC::LHARX;
8657       StoreMnemonic = PPC::STHCX;
8658       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8659       break;
8660     case PPC::ATOMIC_CMP_SWAP_I32:
8661       LoadMnemonic = PPC::LWARX;
8662       StoreMnemonic = PPC::STWCX;
8663       break;
8664     case PPC::ATOMIC_CMP_SWAP_I64:
8665       LoadMnemonic = PPC::LDARX;
8666       StoreMnemonic = PPC::STDCX;
8667       break;
8668     }
8669     unsigned dest   = MI->getOperand(0).getReg();
8670     unsigned ptrA   = MI->getOperand(1).getReg();
8671     unsigned ptrB   = MI->getOperand(2).getReg();
8672     unsigned oldval = MI->getOperand(3).getReg();
8673     unsigned newval = MI->getOperand(4).getReg();
8674     DebugLoc dl     = MI->getDebugLoc();
8675
8676     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8677     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8678     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8679     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8680     F->insert(It, loop1MBB);
8681     F->insert(It, loop2MBB);
8682     F->insert(It, midMBB);
8683     F->insert(It, exitMBB);
8684     exitMBB->splice(exitMBB->begin(), BB,
8685                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8686     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8687
8688     //  thisMBB:
8689     //   ...
8690     //   fallthrough --> loopMBB
8691     BB->addSuccessor(loop1MBB);
8692
8693     // loop1MBB:
8694     //   l[bhwd]arx dest, ptr
8695     //   cmp[wd] dest, oldval
8696     //   bne- midMBB
8697     // loop2MBB:
8698     //   st[bhwd]cx. newval, ptr
8699     //   bne- loopMBB
8700     //   b exitBB
8701     // midMBB:
8702     //   st[bhwd]cx. dest, ptr
8703     // exitBB:
8704     BB = loop1MBB;
8705     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8706       .addReg(ptrA).addReg(ptrB);
8707     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8708       .addReg(oldval).addReg(dest);
8709     BuildMI(BB, dl, TII->get(PPC::BCC))
8710       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8711     BB->addSuccessor(loop2MBB);
8712     BB->addSuccessor(midMBB);
8713
8714     BB = loop2MBB;
8715     BuildMI(BB, dl, TII->get(StoreMnemonic))
8716       .addReg(newval).addReg(ptrA).addReg(ptrB);
8717     BuildMI(BB, dl, TII->get(PPC::BCC))
8718       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8719     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8720     BB->addSuccessor(loop1MBB);
8721     BB->addSuccessor(exitMBB);
8722
8723     BB = midMBB;
8724     BuildMI(BB, dl, TII->get(StoreMnemonic))
8725       .addReg(dest).addReg(ptrA).addReg(ptrB);
8726     BB->addSuccessor(exitMBB);
8727
8728     //  exitMBB:
8729     //   ...
8730     BB = exitMBB;
8731   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8732              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8733     // We must use 64-bit registers for addresses when targeting 64-bit,
8734     // since we're actually doing arithmetic on them.  Other registers
8735     // can be 32-bit.
8736     bool is64bit = Subtarget.isPPC64();
8737     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8738
8739     unsigned dest   = MI->getOperand(0).getReg();
8740     unsigned ptrA   = MI->getOperand(1).getReg();
8741     unsigned ptrB   = MI->getOperand(2).getReg();
8742     unsigned oldval = MI->getOperand(3).getReg();
8743     unsigned newval = MI->getOperand(4).getReg();
8744     DebugLoc dl     = MI->getDebugLoc();
8745
8746     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8747     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8748     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8749     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8750     F->insert(It, loop1MBB);
8751     F->insert(It, loop2MBB);
8752     F->insert(It, midMBB);
8753     F->insert(It, exitMBB);
8754     exitMBB->splice(exitMBB->begin(), BB,
8755                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8756     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8757
8758     MachineRegisterInfo &RegInfo = F->getRegInfo();
8759     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8760                                             : &PPC::GPRCRegClass;
8761     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8762     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8763     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8764     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8765     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8766     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8767     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8768     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8769     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8770     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8771     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8772     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8773     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8774     unsigned Ptr1Reg;
8775     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8776     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8777     //  thisMBB:
8778     //   ...
8779     //   fallthrough --> loopMBB
8780     BB->addSuccessor(loop1MBB);
8781
8782     // The 4-byte load must be aligned, while a char or short may be
8783     // anywhere in the word.  Hence all this nasty bookkeeping code.
8784     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8785     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8786     //   xori shift, shift1, 24 [16]
8787     //   rlwinm ptr, ptr1, 0, 0, 29
8788     //   slw newval2, newval, shift
8789     //   slw oldval2, oldval,shift
8790     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8791     //   slw mask, mask2, shift
8792     //   and newval3, newval2, mask
8793     //   and oldval3, oldval2, mask
8794     // loop1MBB:
8795     //   lwarx tmpDest, ptr
8796     //   and tmp, tmpDest, mask
8797     //   cmpw tmp, oldval3
8798     //   bne- midMBB
8799     // loop2MBB:
8800     //   andc tmp2, tmpDest, mask
8801     //   or tmp4, tmp2, newval3
8802     //   stwcx. tmp4, ptr
8803     //   bne- loop1MBB
8804     //   b exitBB
8805     // midMBB:
8806     //   stwcx. tmpDest, ptr
8807     // exitBB:
8808     //   srw dest, tmpDest, shift
8809     if (ptrA != ZeroReg) {
8810       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8811       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8812         .addReg(ptrA).addReg(ptrB);
8813     } else {
8814       Ptr1Reg = ptrB;
8815     }
8816     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8817         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8818     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8819         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8820     if (is64bit)
8821       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8822         .addReg(Ptr1Reg).addImm(0).addImm(61);
8823     else
8824       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8825         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8826     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8827         .addReg(newval).addReg(ShiftReg);
8828     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8829         .addReg(oldval).addReg(ShiftReg);
8830     if (is8bit)
8831       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8832     else {
8833       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8834       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8835         .addReg(Mask3Reg).addImm(65535);
8836     }
8837     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8838         .addReg(Mask2Reg).addReg(ShiftReg);
8839     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8840         .addReg(NewVal2Reg).addReg(MaskReg);
8841     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8842         .addReg(OldVal2Reg).addReg(MaskReg);
8843
8844     BB = loop1MBB;
8845     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8846         .addReg(ZeroReg).addReg(PtrReg);
8847     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8848         .addReg(TmpDestReg).addReg(MaskReg);
8849     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8850         .addReg(TmpReg).addReg(OldVal3Reg);
8851     BuildMI(BB, dl, TII->get(PPC::BCC))
8852         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8853     BB->addSuccessor(loop2MBB);
8854     BB->addSuccessor(midMBB);
8855
8856     BB = loop2MBB;
8857     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8858         .addReg(TmpDestReg).addReg(MaskReg);
8859     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8860         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8861     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8862         .addReg(ZeroReg).addReg(PtrReg);
8863     BuildMI(BB, dl, TII->get(PPC::BCC))
8864       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8865     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8866     BB->addSuccessor(loop1MBB);
8867     BB->addSuccessor(exitMBB);
8868
8869     BB = midMBB;
8870     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8871       .addReg(ZeroReg).addReg(PtrReg);
8872     BB->addSuccessor(exitMBB);
8873
8874     //  exitMBB:
8875     //   ...
8876     BB = exitMBB;
8877     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8878       .addReg(ShiftReg);
8879   } else if (MI->getOpcode() == PPC::FADDrtz) {
8880     // This pseudo performs an FADD with rounding mode temporarily forced
8881     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8882     // is not modeled at the SelectionDAG level.
8883     unsigned Dest = MI->getOperand(0).getReg();
8884     unsigned Src1 = MI->getOperand(1).getReg();
8885     unsigned Src2 = MI->getOperand(2).getReg();
8886     DebugLoc dl   = MI->getDebugLoc();
8887
8888     MachineRegisterInfo &RegInfo = F->getRegInfo();
8889     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8890
8891     // Save FPSCR value.
8892     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8893
8894     // Set rounding mode to round-to-zero.
8895     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8896     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8897
8898     // Perform addition.
8899     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8900
8901     // Restore FPSCR value.
8902     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8903   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8904              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8905              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8906              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8907     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8908                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8909                       PPC::ANDIo8 : PPC::ANDIo;
8910     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8911                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8912
8913     MachineRegisterInfo &RegInfo = F->getRegInfo();
8914     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8915                                                   &PPC::GPRCRegClass :
8916                                                   &PPC::G8RCRegClass);
8917
8918     DebugLoc dl   = MI->getDebugLoc();
8919     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8920       .addReg(MI->getOperand(1).getReg()).addImm(1);
8921     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8922             MI->getOperand(0).getReg())
8923       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8924   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8925     DebugLoc Dl = MI->getDebugLoc();
8926     MachineRegisterInfo &RegInfo = F->getRegInfo();
8927     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8928     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8929     return BB;
8930   } else {
8931     llvm_unreachable("Unexpected instr type to insert");
8932   }
8933
8934   MI->eraseFromParent();   // The pseudo instruction is gone now.
8935   return BB;
8936 }
8937
8938 //===----------------------------------------------------------------------===//
8939 // Target Optimization Hooks
8940 //===----------------------------------------------------------------------===//
8941
8942 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8943                                             DAGCombinerInfo &DCI,
8944                                             unsigned &RefinementSteps,
8945                                             bool &UseOneConstNR) const {
8946   EVT VT = Operand.getValueType();
8947   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8948       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8949       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8950       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8951       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8952       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8953     // Convergence is quadratic, so we essentially double the number of digits
8954     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8955     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8956     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8957     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8958     if (VT.getScalarType() == MVT::f64)
8959       ++RefinementSteps;
8960     UseOneConstNR = true;
8961     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8962   }
8963   return SDValue();
8964 }
8965
8966 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8967                                             DAGCombinerInfo &DCI,
8968                                             unsigned &RefinementSteps) const {
8969   EVT VT = Operand.getValueType();
8970   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8971       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8972       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8973       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8974       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8975       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8976     // Convergence is quadratic, so we essentially double the number of digits
8977     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8978     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8979     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8980     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8981     if (VT.getScalarType() == MVT::f64)
8982       ++RefinementSteps;
8983     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8984   }
8985   return SDValue();
8986 }
8987
8988 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8989   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8990   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8991   // enabled for division), this functionality is redundant with the default
8992   // combiner logic (once the division -> reciprocal/multiply transformation
8993   // has taken place). As a result, this matters more for older cores than for
8994   // newer ones.
8995
8996   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8997   // reciprocal if there are two or more FDIVs (for embedded cores with only
8998   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8999   switch (Subtarget.getDarwinDirective()) {
9000   default:
9001     return NumUsers > 2;
9002   case PPC::DIR_440:
9003   case PPC::DIR_A2:
9004   case PPC::DIR_E500mc:
9005   case PPC::DIR_E5500:
9006     return NumUsers > 1;
9007   }
9008 }
9009
9010 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9011                             unsigned Bytes, int Dist,
9012                             SelectionDAG &DAG) {
9013   if (VT.getSizeInBits() / 8 != Bytes)
9014     return false;
9015
9016   SDValue BaseLoc = Base->getBasePtr();
9017   if (Loc.getOpcode() == ISD::FrameIndex) {
9018     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9019       return false;
9020     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9021     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9022     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9023     int FS  = MFI->getObjectSize(FI);
9024     int BFS = MFI->getObjectSize(BFI);
9025     if (FS != BFS || FS != (int)Bytes) return false;
9026     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9027   }
9028
9029   // Handle X+C
9030   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
9031       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
9032     return true;
9033
9034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9035   const GlobalValue *GV1 = nullptr;
9036   const GlobalValue *GV2 = nullptr;
9037   int64_t Offset1 = 0;
9038   int64_t Offset2 = 0;
9039   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9040   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9041   if (isGA1 && isGA2 && GV1 == GV2)
9042     return Offset1 == (Offset2 + Dist*Bytes);
9043   return false;
9044 }
9045
9046 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9047 // not enforce equality of the chain operands.
9048 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9049                             unsigned Bytes, int Dist,
9050                             SelectionDAG &DAG) {
9051   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9052     EVT VT = LS->getMemoryVT();
9053     SDValue Loc = LS->getBasePtr();
9054     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9055   }
9056
9057   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9058     EVT VT;
9059     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9060     default: return false;
9061     case Intrinsic::ppc_qpx_qvlfd:
9062     case Intrinsic::ppc_qpx_qvlfda:
9063       VT = MVT::v4f64;
9064       break;
9065     case Intrinsic::ppc_qpx_qvlfs:
9066     case Intrinsic::ppc_qpx_qvlfsa:
9067       VT = MVT::v4f32;
9068       break;
9069     case Intrinsic::ppc_qpx_qvlfcd:
9070     case Intrinsic::ppc_qpx_qvlfcda:
9071       VT = MVT::v2f64;
9072       break;
9073     case Intrinsic::ppc_qpx_qvlfcs:
9074     case Intrinsic::ppc_qpx_qvlfcsa:
9075       VT = MVT::v2f32;
9076       break;
9077     case Intrinsic::ppc_qpx_qvlfiwa:
9078     case Intrinsic::ppc_qpx_qvlfiwz:
9079     case Intrinsic::ppc_altivec_lvx:
9080     case Intrinsic::ppc_altivec_lvxl:
9081     case Intrinsic::ppc_vsx_lxvw4x:
9082       VT = MVT::v4i32;
9083       break;
9084     case Intrinsic::ppc_vsx_lxvd2x:
9085       VT = MVT::v2f64;
9086       break;
9087     case Intrinsic::ppc_altivec_lvebx:
9088       VT = MVT::i8;
9089       break;
9090     case Intrinsic::ppc_altivec_lvehx:
9091       VT = MVT::i16;
9092       break;
9093     case Intrinsic::ppc_altivec_lvewx:
9094       VT = MVT::i32;
9095       break;
9096     }
9097
9098     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9099   }
9100
9101   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9102     EVT VT;
9103     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9104     default: return false;
9105     case Intrinsic::ppc_qpx_qvstfd:
9106     case Intrinsic::ppc_qpx_qvstfda:
9107       VT = MVT::v4f64;
9108       break;
9109     case Intrinsic::ppc_qpx_qvstfs:
9110     case Intrinsic::ppc_qpx_qvstfsa:
9111       VT = MVT::v4f32;
9112       break;
9113     case Intrinsic::ppc_qpx_qvstfcd:
9114     case Intrinsic::ppc_qpx_qvstfcda:
9115       VT = MVT::v2f64;
9116       break;
9117     case Intrinsic::ppc_qpx_qvstfcs:
9118     case Intrinsic::ppc_qpx_qvstfcsa:
9119       VT = MVT::v2f32;
9120       break;
9121     case Intrinsic::ppc_qpx_qvstfiw:
9122     case Intrinsic::ppc_qpx_qvstfiwa:
9123     case Intrinsic::ppc_altivec_stvx:
9124     case Intrinsic::ppc_altivec_stvxl:
9125     case Intrinsic::ppc_vsx_stxvw4x:
9126       VT = MVT::v4i32;
9127       break;
9128     case Intrinsic::ppc_vsx_stxvd2x:
9129       VT = MVT::v2f64;
9130       break;
9131     case Intrinsic::ppc_altivec_stvebx:
9132       VT = MVT::i8;
9133       break;
9134     case Intrinsic::ppc_altivec_stvehx:
9135       VT = MVT::i16;
9136       break;
9137     case Intrinsic::ppc_altivec_stvewx:
9138       VT = MVT::i32;
9139       break;
9140     }
9141
9142     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9143   }
9144
9145   return false;
9146 }
9147
9148 // Return true is there is a nearyby consecutive load to the one provided
9149 // (regardless of alignment). We search up and down the chain, looking though
9150 // token factors and other loads (but nothing else). As a result, a true result
9151 // indicates that it is safe to create a new consecutive load adjacent to the
9152 // load provided.
9153 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9154   SDValue Chain = LD->getChain();
9155   EVT VT = LD->getMemoryVT();
9156
9157   SmallSet<SDNode *, 16> LoadRoots;
9158   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9159   SmallSet<SDNode *, 16> Visited;
9160
9161   // First, search up the chain, branching to follow all token-factor operands.
9162   // If we find a consecutive load, then we're done, otherwise, record all
9163   // nodes just above the top-level loads and token factors.
9164   while (!Queue.empty()) {
9165     SDNode *ChainNext = Queue.pop_back_val();
9166     if (!Visited.insert(ChainNext).second)
9167       continue;
9168
9169     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9170       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9171         return true;
9172
9173       if (!Visited.count(ChainLD->getChain().getNode()))
9174         Queue.push_back(ChainLD->getChain().getNode());
9175     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9176       for (const SDUse &O : ChainNext->ops())
9177         if (!Visited.count(O.getNode()))
9178           Queue.push_back(O.getNode());
9179     } else
9180       LoadRoots.insert(ChainNext);
9181   }
9182
9183   // Second, search down the chain, starting from the top-level nodes recorded
9184   // in the first phase. These top-level nodes are the nodes just above all
9185   // loads and token factors. Starting with their uses, recursively look though
9186   // all loads (just the chain uses) and token factors to find a consecutive
9187   // load.
9188   Visited.clear();
9189   Queue.clear();
9190
9191   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9192        IE = LoadRoots.end(); I != IE; ++I) {
9193     Queue.push_back(*I);
9194        
9195     while (!Queue.empty()) {
9196       SDNode *LoadRoot = Queue.pop_back_val();
9197       if (!Visited.insert(LoadRoot).second)
9198         continue;
9199
9200       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9201         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9202           return true;
9203
9204       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9205            UE = LoadRoot->use_end(); UI != UE; ++UI)
9206         if (((isa<MemSDNode>(*UI) &&
9207             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9208             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9209           Queue.push_back(*UI);
9210     }
9211   }
9212
9213   return false;
9214 }
9215
9216 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9217                                                   DAGCombinerInfo &DCI) const {
9218   SelectionDAG &DAG = DCI.DAG;
9219   SDLoc dl(N);
9220
9221   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9222   // If we're tracking CR bits, we need to be careful that we don't have:
9223   //   trunc(binary-ops(zext(x), zext(y)))
9224   // or
9225   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9226   // such that we're unnecessarily moving things into GPRs when it would be
9227   // better to keep them in CR bits.
9228
9229   // Note that trunc here can be an actual i1 trunc, or can be the effective
9230   // truncation that comes from a setcc or select_cc.
9231   if (N->getOpcode() == ISD::TRUNCATE &&
9232       N->getValueType(0) != MVT::i1)
9233     return SDValue();
9234
9235   if (N->getOperand(0).getValueType() != MVT::i32 &&
9236       N->getOperand(0).getValueType() != MVT::i64)
9237     return SDValue();
9238
9239   if (N->getOpcode() == ISD::SETCC ||
9240       N->getOpcode() == ISD::SELECT_CC) {
9241     // If we're looking at a comparison, then we need to make sure that the
9242     // high bits (all except for the first) don't matter the result.
9243     ISD::CondCode CC =
9244       cast<CondCodeSDNode>(N->getOperand(
9245         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9246     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9247
9248     if (ISD::isSignedIntSetCC(CC)) {
9249       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9250           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9251         return SDValue();
9252     } else if (ISD::isUnsignedIntSetCC(CC)) {
9253       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9254                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9255           !DAG.MaskedValueIsZero(N->getOperand(1),
9256                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9257         return SDValue();
9258     } else {
9259       // This is neither a signed nor an unsigned comparison, just make sure
9260       // that the high bits are equal.
9261       APInt Op1Zero, Op1One;
9262       APInt Op2Zero, Op2One;
9263       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9264       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9265
9266       // We don't really care about what is known about the first bit (if
9267       // anything), so clear it in all masks prior to comparing them.
9268       Op1Zero.clearBit(0); Op1One.clearBit(0);
9269       Op2Zero.clearBit(0); Op2One.clearBit(0);
9270
9271       if (Op1Zero != Op2Zero || Op1One != Op2One)
9272         return SDValue();
9273     }
9274   }
9275
9276   // We now know that the higher-order bits are irrelevant, we just need to
9277   // make sure that all of the intermediate operations are bit operations, and
9278   // all inputs are extensions.
9279   if (N->getOperand(0).getOpcode() != ISD::AND &&
9280       N->getOperand(0).getOpcode() != ISD::OR  &&
9281       N->getOperand(0).getOpcode() != ISD::XOR &&
9282       N->getOperand(0).getOpcode() != ISD::SELECT &&
9283       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9284       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9285       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9286       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9287       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9288     return SDValue();
9289
9290   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9291       N->getOperand(1).getOpcode() != ISD::AND &&
9292       N->getOperand(1).getOpcode() != ISD::OR  &&
9293       N->getOperand(1).getOpcode() != ISD::XOR &&
9294       N->getOperand(1).getOpcode() != ISD::SELECT &&
9295       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9296       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9297       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9298       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9299       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9300     return SDValue();
9301
9302   SmallVector<SDValue, 4> Inputs;
9303   SmallVector<SDValue, 8> BinOps, PromOps;
9304   SmallPtrSet<SDNode *, 16> Visited;
9305
9306   for (unsigned i = 0; i < 2; ++i) {
9307     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9308           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9309           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9310           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9311         isa<ConstantSDNode>(N->getOperand(i)))
9312       Inputs.push_back(N->getOperand(i));
9313     else
9314       BinOps.push_back(N->getOperand(i));
9315
9316     if (N->getOpcode() == ISD::TRUNCATE)
9317       break;
9318   }
9319
9320   // Visit all inputs, collect all binary operations (and, or, xor and
9321   // select) that are all fed by extensions. 
9322   while (!BinOps.empty()) {
9323     SDValue BinOp = BinOps.back();
9324     BinOps.pop_back();
9325
9326     if (!Visited.insert(BinOp.getNode()).second)
9327       continue;
9328
9329     PromOps.push_back(BinOp);
9330
9331     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9332       // The condition of the select is not promoted.
9333       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9334         continue;
9335       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9336         continue;
9337
9338       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9339             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9340             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9341            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9342           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9343         Inputs.push_back(BinOp.getOperand(i)); 
9344       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9345                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9346                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9347                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9348                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9349                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9350                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9351                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9352                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9353         BinOps.push_back(BinOp.getOperand(i));
9354       } else {
9355         // We have an input that is not an extension or another binary
9356         // operation; we'll abort this transformation.
9357         return SDValue();
9358       }
9359     }
9360   }
9361
9362   // Make sure that this is a self-contained cluster of operations (which
9363   // is not quite the same thing as saying that everything has only one
9364   // use).
9365   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9366     if (isa<ConstantSDNode>(Inputs[i]))
9367       continue;
9368
9369     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9370                               UE = Inputs[i].getNode()->use_end();
9371          UI != UE; ++UI) {
9372       SDNode *User = *UI;
9373       if (User != N && !Visited.count(User))
9374         return SDValue();
9375
9376       // Make sure that we're not going to promote the non-output-value
9377       // operand(s) or SELECT or SELECT_CC.
9378       // FIXME: Although we could sometimes handle this, and it does occur in
9379       // practice that one of the condition inputs to the select is also one of
9380       // the outputs, we currently can't deal with this.
9381       if (User->getOpcode() == ISD::SELECT) {
9382         if (User->getOperand(0) == Inputs[i])
9383           return SDValue();
9384       } else if (User->getOpcode() == ISD::SELECT_CC) {
9385         if (User->getOperand(0) == Inputs[i] ||
9386             User->getOperand(1) == Inputs[i])
9387           return SDValue();
9388       }
9389     }
9390   }
9391
9392   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9393     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9394                               UE = PromOps[i].getNode()->use_end();
9395          UI != UE; ++UI) {
9396       SDNode *User = *UI;
9397       if (User != N && !Visited.count(User))
9398         return SDValue();
9399
9400       // Make sure that we're not going to promote the non-output-value
9401       // operand(s) or SELECT or SELECT_CC.
9402       // FIXME: Although we could sometimes handle this, and it does occur in
9403       // practice that one of the condition inputs to the select is also one of
9404       // the outputs, we currently can't deal with this.
9405       if (User->getOpcode() == ISD::SELECT) {
9406         if (User->getOperand(0) == PromOps[i])
9407           return SDValue();
9408       } else if (User->getOpcode() == ISD::SELECT_CC) {
9409         if (User->getOperand(0) == PromOps[i] ||
9410             User->getOperand(1) == PromOps[i])
9411           return SDValue();
9412       }
9413     }
9414   }
9415
9416   // Replace all inputs with the extension operand.
9417   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9418     // Constants may have users outside the cluster of to-be-promoted nodes,
9419     // and so we need to replace those as we do the promotions.
9420     if (isa<ConstantSDNode>(Inputs[i]))
9421       continue;
9422     else
9423       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9424   }
9425
9426   // Replace all operations (these are all the same, but have a different
9427   // (i1) return type). DAG.getNode will validate that the types of
9428   // a binary operator match, so go through the list in reverse so that
9429   // we've likely promoted both operands first. Any intermediate truncations or
9430   // extensions disappear.
9431   while (!PromOps.empty()) {
9432     SDValue PromOp = PromOps.back();
9433     PromOps.pop_back();
9434
9435     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9436         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9437         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9438         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9439       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9440           PromOp.getOperand(0).getValueType() != MVT::i1) {
9441         // The operand is not yet ready (see comment below).
9442         PromOps.insert(PromOps.begin(), PromOp);
9443         continue;
9444       }
9445
9446       SDValue RepValue = PromOp.getOperand(0);
9447       if (isa<ConstantSDNode>(RepValue))
9448         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9449
9450       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9451       continue;
9452     }
9453
9454     unsigned C;
9455     switch (PromOp.getOpcode()) {
9456     default:             C = 0; break;
9457     case ISD::SELECT:    C = 1; break;
9458     case ISD::SELECT_CC: C = 2; break;
9459     }
9460
9461     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9462          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9463         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9464          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9465       // The to-be-promoted operands of this node have not yet been
9466       // promoted (this should be rare because we're going through the
9467       // list backward, but if one of the operands has several users in
9468       // this cluster of to-be-promoted nodes, it is possible).
9469       PromOps.insert(PromOps.begin(), PromOp);
9470       continue;
9471     }
9472
9473     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9474                                 PromOp.getNode()->op_end());
9475
9476     // If there are any constant inputs, make sure they're replaced now.
9477     for (unsigned i = 0; i < 2; ++i)
9478       if (isa<ConstantSDNode>(Ops[C+i]))
9479         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9480
9481     DAG.ReplaceAllUsesOfValueWith(PromOp,
9482       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9483   }
9484
9485   // Now we're left with the initial truncation itself.
9486   if (N->getOpcode() == ISD::TRUNCATE)
9487     return N->getOperand(0);
9488
9489   // Otherwise, this is a comparison. The operands to be compared have just
9490   // changed type (to i1), but everything else is the same.
9491   return SDValue(N, 0);
9492 }
9493
9494 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9495                                                   DAGCombinerInfo &DCI) const {
9496   SelectionDAG &DAG = DCI.DAG;
9497   SDLoc dl(N);
9498
9499   // If we're tracking CR bits, we need to be careful that we don't have:
9500   //   zext(binary-ops(trunc(x), trunc(y)))
9501   // or
9502   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9503   // such that we're unnecessarily moving things into CR bits that can more
9504   // efficiently stay in GPRs. Note that if we're not certain that the high
9505   // bits are set as required by the final extension, we still may need to do
9506   // some masking to get the proper behavior.
9507
9508   // This same functionality is important on PPC64 when dealing with
9509   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9510   // the return values of functions. Because it is so similar, it is handled
9511   // here as well.
9512
9513   if (N->getValueType(0) != MVT::i32 &&
9514       N->getValueType(0) != MVT::i64)
9515     return SDValue();
9516
9517   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9518         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9519     return SDValue();
9520
9521   if (N->getOperand(0).getOpcode() != ISD::AND &&
9522       N->getOperand(0).getOpcode() != ISD::OR  &&
9523       N->getOperand(0).getOpcode() != ISD::XOR &&
9524       N->getOperand(0).getOpcode() != ISD::SELECT &&
9525       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9526     return SDValue();
9527
9528   SmallVector<SDValue, 4> Inputs;
9529   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9530   SmallPtrSet<SDNode *, 16> Visited;
9531
9532   // Visit all inputs, collect all binary operations (and, or, xor and
9533   // select) that are all fed by truncations. 
9534   while (!BinOps.empty()) {
9535     SDValue BinOp = BinOps.back();
9536     BinOps.pop_back();
9537
9538     if (!Visited.insert(BinOp.getNode()).second)
9539       continue;
9540
9541     PromOps.push_back(BinOp);
9542
9543     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9544       // The condition of the select is not promoted.
9545       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9546         continue;
9547       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9548         continue;
9549
9550       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9551           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9552         Inputs.push_back(BinOp.getOperand(i)); 
9553       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9554                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9555                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9556                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9557                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9558         BinOps.push_back(BinOp.getOperand(i));
9559       } else {
9560         // We have an input that is not a truncation or another binary
9561         // operation; we'll abort this transformation.
9562         return SDValue();
9563       }
9564     }
9565   }
9566
9567   // The operands of a select that must be truncated when the select is
9568   // promoted because the operand is actually part of the to-be-promoted set.
9569   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9570
9571   // Make sure that this is a self-contained cluster of operations (which
9572   // is not quite the same thing as saying that everything has only one
9573   // use).
9574   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9575     if (isa<ConstantSDNode>(Inputs[i]))
9576       continue;
9577
9578     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9579                               UE = Inputs[i].getNode()->use_end();
9580          UI != UE; ++UI) {
9581       SDNode *User = *UI;
9582       if (User != N && !Visited.count(User))
9583         return SDValue();
9584
9585       // If we're going to promote the non-output-value operand(s) or SELECT or
9586       // SELECT_CC, record them for truncation.
9587       if (User->getOpcode() == ISD::SELECT) {
9588         if (User->getOperand(0) == Inputs[i])
9589           SelectTruncOp[0].insert(std::make_pair(User,
9590                                     User->getOperand(0).getValueType()));
9591       } else if (User->getOpcode() == ISD::SELECT_CC) {
9592         if (User->getOperand(0) == Inputs[i])
9593           SelectTruncOp[0].insert(std::make_pair(User,
9594                                     User->getOperand(0).getValueType()));
9595         if (User->getOperand(1) == Inputs[i])
9596           SelectTruncOp[1].insert(std::make_pair(User,
9597                                     User->getOperand(1).getValueType()));
9598       }
9599     }
9600   }
9601
9602   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9603     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9604                               UE = PromOps[i].getNode()->use_end();
9605          UI != UE; ++UI) {
9606       SDNode *User = *UI;
9607       if (User != N && !Visited.count(User))
9608         return SDValue();
9609
9610       // If we're going to promote the non-output-value operand(s) or SELECT or
9611       // SELECT_CC, record them for truncation.
9612       if (User->getOpcode() == ISD::SELECT) {
9613         if (User->getOperand(0) == PromOps[i])
9614           SelectTruncOp[0].insert(std::make_pair(User,
9615                                     User->getOperand(0).getValueType()));
9616       } else if (User->getOpcode() == ISD::SELECT_CC) {
9617         if (User->getOperand(0) == PromOps[i])
9618           SelectTruncOp[0].insert(std::make_pair(User,
9619                                     User->getOperand(0).getValueType()));
9620         if (User->getOperand(1) == PromOps[i])
9621           SelectTruncOp[1].insert(std::make_pair(User,
9622                                     User->getOperand(1).getValueType()));
9623       }
9624     }
9625   }
9626
9627   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9628   bool ReallyNeedsExt = false;
9629   if (N->getOpcode() != ISD::ANY_EXTEND) {
9630     // If all of the inputs are not already sign/zero extended, then
9631     // we'll still need to do that at the end.
9632     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9633       if (isa<ConstantSDNode>(Inputs[i]))
9634         continue;
9635
9636       unsigned OpBits =
9637         Inputs[i].getOperand(0).getValueSizeInBits();
9638       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9639
9640       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9641            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9642                                   APInt::getHighBitsSet(OpBits,
9643                                                         OpBits-PromBits))) ||
9644           (N->getOpcode() == ISD::SIGN_EXTEND &&
9645            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9646              (OpBits-(PromBits-1)))) {
9647         ReallyNeedsExt = true;
9648         break;
9649       }
9650     }
9651   }
9652
9653   // Replace all inputs, either with the truncation operand, or a
9654   // truncation or extension to the final output type.
9655   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9656     // Constant inputs need to be replaced with the to-be-promoted nodes that
9657     // use them because they might have users outside of the cluster of
9658     // promoted nodes.
9659     if (isa<ConstantSDNode>(Inputs[i]))
9660       continue;
9661
9662     SDValue InSrc = Inputs[i].getOperand(0);
9663     if (Inputs[i].getValueType() == N->getValueType(0))
9664       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9665     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9666       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9667         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9668     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9669       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9670         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9671     else
9672       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9673         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9674   }
9675
9676   // Replace all operations (these are all the same, but have a different
9677   // (promoted) return type). DAG.getNode will validate that the types of
9678   // a binary operator match, so go through the list in reverse so that
9679   // we've likely promoted both operands first.
9680   while (!PromOps.empty()) {
9681     SDValue PromOp = PromOps.back();
9682     PromOps.pop_back();
9683
9684     unsigned C;
9685     switch (PromOp.getOpcode()) {
9686     default:             C = 0; break;
9687     case ISD::SELECT:    C = 1; break;
9688     case ISD::SELECT_CC: C = 2; break;
9689     }
9690
9691     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9692          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9693         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9694          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9695       // The to-be-promoted operands of this node have not yet been
9696       // promoted (this should be rare because we're going through the
9697       // list backward, but if one of the operands has several users in
9698       // this cluster of to-be-promoted nodes, it is possible).
9699       PromOps.insert(PromOps.begin(), PromOp);
9700       continue;
9701     }
9702
9703     // For SELECT and SELECT_CC nodes, we do a similar check for any
9704     // to-be-promoted comparison inputs.
9705     if (PromOp.getOpcode() == ISD::SELECT ||
9706         PromOp.getOpcode() == ISD::SELECT_CC) {
9707       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9708            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9709           (SelectTruncOp[1].count(PromOp.getNode()) &&
9710            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9711         PromOps.insert(PromOps.begin(), PromOp);
9712         continue;
9713       }
9714     }
9715
9716     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9717                                 PromOp.getNode()->op_end());
9718
9719     // If this node has constant inputs, then they'll need to be promoted here.
9720     for (unsigned i = 0; i < 2; ++i) {
9721       if (!isa<ConstantSDNode>(Ops[C+i]))
9722         continue;
9723       if (Ops[C+i].getValueType() == N->getValueType(0))
9724         continue;
9725
9726       if (N->getOpcode() == ISD::SIGN_EXTEND)
9727         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9728       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9729         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9730       else
9731         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9732     }
9733
9734     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9735     // truncate them again to the original value type.
9736     if (PromOp.getOpcode() == ISD::SELECT ||
9737         PromOp.getOpcode() == ISD::SELECT_CC) {
9738       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9739       if (SI0 != SelectTruncOp[0].end())
9740         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9741       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9742       if (SI1 != SelectTruncOp[1].end())
9743         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9744     }
9745
9746     DAG.ReplaceAllUsesOfValueWith(PromOp,
9747       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9748   }
9749
9750   // Now we're left with the initial extension itself.
9751   if (!ReallyNeedsExt)
9752     return N->getOperand(0);
9753
9754   // To zero extend, just mask off everything except for the first bit (in the
9755   // i1 case).
9756   if (N->getOpcode() == ISD::ZERO_EXTEND)
9757     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9758                        DAG.getConstant(APInt::getLowBitsSet(
9759                                          N->getValueSizeInBits(0), PromBits),
9760                                        dl, N->getValueType(0)));
9761
9762   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9763          "Invalid extension type");
9764   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9765   SDValue ShiftCst =
9766     DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9767   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9768                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9769                                  N->getOperand(0), ShiftCst), ShiftCst);
9770 }
9771
9772 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9773                                               DAGCombinerInfo &DCI) const {
9774   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9775           N->getOpcode() == ISD::UINT_TO_FP) &&
9776          "Need an int -> FP conversion node here");
9777
9778   if (!Subtarget.has64BitSupport())
9779     return SDValue();
9780
9781   SelectionDAG &DAG = DCI.DAG;
9782   SDLoc dl(N);
9783   SDValue Op(N, 0);
9784
9785   // Don't handle ppc_fp128 here or i1 conversions.
9786   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9787     return SDValue();
9788   if (Op.getOperand(0).getValueType() == MVT::i1)
9789     return SDValue();
9790
9791   // For i32 intermediate values, unfortunately, the conversion functions
9792   // leave the upper 32 bits of the value are undefined. Within the set of
9793   // scalar instructions, we have no method for zero- or sign-extending the
9794   // value. Thus, we cannot handle i32 intermediate values here.
9795   if (Op.getOperand(0).getValueType() == MVT::i32)
9796     return SDValue();
9797
9798   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9799          "UINT_TO_FP is supported only with FPCVT");
9800
9801   // If we have FCFIDS, then use it when converting to single-precision.
9802   // Otherwise, convert to double-precision and then round.
9803   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9804                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9805                                                             : PPCISD::FCFIDS)
9806                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9807                                                             : PPCISD::FCFID);
9808   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9809                   ? MVT::f32
9810                   : MVT::f64;
9811
9812   // If we're converting from a float, to an int, and back to a float again,
9813   // then we don't need the store/load pair at all.
9814   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9815        Subtarget.hasFPCVT()) ||
9816       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9817     SDValue Src = Op.getOperand(0).getOperand(0);
9818     if (Src.getValueType() == MVT::f32) {
9819       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9820       DCI.AddToWorklist(Src.getNode());
9821     }
9822
9823     unsigned FCTOp =
9824       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9825                                                         PPCISD::FCTIDUZ;
9826
9827     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9828     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9829
9830     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9831       FP = DAG.getNode(ISD::FP_ROUND, dl,
9832                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
9833       DCI.AddToWorklist(FP.getNode());
9834     }
9835
9836     return FP;
9837   }
9838
9839   return SDValue();
9840 }
9841
9842 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9843 // builtins) into loads with swaps.
9844 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9845                                               DAGCombinerInfo &DCI) const {
9846   SelectionDAG &DAG = DCI.DAG;
9847   SDLoc dl(N);
9848   SDValue Chain;
9849   SDValue Base;
9850   MachineMemOperand *MMO;
9851
9852   switch (N->getOpcode()) {
9853   default:
9854     llvm_unreachable("Unexpected opcode for little endian VSX load");
9855   case ISD::LOAD: {
9856     LoadSDNode *LD = cast<LoadSDNode>(N);
9857     Chain = LD->getChain();
9858     Base = LD->getBasePtr();
9859     MMO = LD->getMemOperand();
9860     // If the MMO suggests this isn't a load of a full vector, leave
9861     // things alone.  For a built-in, we have to make the change for
9862     // correctness, so if there is a size problem that will be a bug.
9863     if (MMO->getSize() < 16)
9864       return SDValue();
9865     break;
9866   }
9867   case ISD::INTRINSIC_W_CHAIN: {
9868     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9869     Chain = Intrin->getChain();
9870     Base = Intrin->getBasePtr();
9871     MMO = Intrin->getMemOperand();
9872     break;
9873   }
9874   }
9875
9876   MVT VecTy = N->getValueType(0).getSimpleVT();
9877   SDValue LoadOps[] = { Chain, Base };
9878   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9879                                          DAG.getVTList(VecTy, MVT::Other),
9880                                          LoadOps, VecTy, MMO);
9881   DCI.AddToWorklist(Load.getNode());
9882   Chain = Load.getValue(1);
9883   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9884                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9885   DCI.AddToWorklist(Swap.getNode());
9886   return Swap;
9887 }
9888
9889 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9890 // builtins) into stores with swaps.
9891 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9892                                                DAGCombinerInfo &DCI) const {
9893   SelectionDAG &DAG = DCI.DAG;
9894   SDLoc dl(N);
9895   SDValue Chain;
9896   SDValue Base;
9897   unsigned SrcOpnd;
9898   MachineMemOperand *MMO;
9899
9900   switch (N->getOpcode()) {
9901   default:
9902     llvm_unreachable("Unexpected opcode for little endian VSX store");
9903   case ISD::STORE: {
9904     StoreSDNode *ST = cast<StoreSDNode>(N);
9905     Chain = ST->getChain();
9906     Base = ST->getBasePtr();
9907     MMO = ST->getMemOperand();
9908     SrcOpnd = 1;
9909     // If the MMO suggests this isn't a store of a full vector, leave
9910     // things alone.  For a built-in, we have to make the change for
9911     // correctness, so if there is a size problem that will be a bug.
9912     if (MMO->getSize() < 16)
9913       return SDValue();
9914     break;
9915   }
9916   case ISD::INTRINSIC_VOID: {
9917     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9918     Chain = Intrin->getChain();
9919     // Intrin->getBasePtr() oddly does not get what we want.
9920     Base = Intrin->getOperand(3);
9921     MMO = Intrin->getMemOperand();
9922     SrcOpnd = 2;
9923     break;
9924   }
9925   }
9926
9927   SDValue Src = N->getOperand(SrcOpnd);
9928   MVT VecTy = Src.getValueType().getSimpleVT();
9929   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9930                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9931   DCI.AddToWorklist(Swap.getNode());
9932   Chain = Swap.getValue(1);
9933   SDValue StoreOps[] = { Chain, Swap, Base };
9934   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9935                                           DAG.getVTList(MVT::Other),
9936                                           StoreOps, VecTy, MMO);
9937   DCI.AddToWorklist(Store.getNode());
9938   return Store;
9939 }
9940
9941 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9942                                              DAGCombinerInfo &DCI) const {
9943   SelectionDAG &DAG = DCI.DAG;
9944   SDLoc dl(N);
9945   switch (N->getOpcode()) {
9946   default: break;
9947   case PPCISD::SHL:
9948     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9949       if (C->isNullValue())   // 0 << V -> 0.
9950         return N->getOperand(0);
9951     }
9952     break;
9953   case PPCISD::SRL:
9954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9955       if (C->isNullValue())   // 0 >>u V -> 0.
9956         return N->getOperand(0);
9957     }
9958     break;
9959   case PPCISD::SRA:
9960     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9961       if (C->isNullValue() ||   //  0 >>s V -> 0.
9962           C->isAllOnesValue())    // -1 >>s V -> -1.
9963         return N->getOperand(0);
9964     }
9965     break;
9966   case ISD::SIGN_EXTEND:
9967   case ISD::ZERO_EXTEND:
9968   case ISD::ANY_EXTEND: 
9969     return DAGCombineExtBoolTrunc(N, DCI);
9970   case ISD::TRUNCATE:
9971   case ISD::SETCC:
9972   case ISD::SELECT_CC:
9973     return DAGCombineTruncBoolExt(N, DCI);
9974   case ISD::SINT_TO_FP:
9975   case ISD::UINT_TO_FP:
9976     return combineFPToIntToFP(N, DCI);
9977   case ISD::STORE: {
9978     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9979     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9980         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9981         N->getOperand(1).getValueType() == MVT::i32 &&
9982         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9983       SDValue Val = N->getOperand(1).getOperand(0);
9984       if (Val.getValueType() == MVT::f32) {
9985         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9986         DCI.AddToWorklist(Val.getNode());
9987       }
9988       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9989       DCI.AddToWorklist(Val.getNode());
9990
9991       SDValue Ops[] = {
9992         N->getOperand(0), Val, N->getOperand(2),
9993         DAG.getValueType(N->getOperand(1).getValueType())
9994       };
9995
9996       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9997               DAG.getVTList(MVT::Other), Ops,
9998               cast<StoreSDNode>(N)->getMemoryVT(),
9999               cast<StoreSDNode>(N)->getMemOperand());
10000       DCI.AddToWorklist(Val.getNode());
10001       return Val;
10002     }
10003
10004     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10005     if (cast<StoreSDNode>(N)->isUnindexed() &&
10006         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10007         N->getOperand(1).getNode()->hasOneUse() &&
10008         (N->getOperand(1).getValueType() == MVT::i32 ||
10009          N->getOperand(1).getValueType() == MVT::i16 ||
10010          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10011           N->getOperand(1).getValueType() == MVT::i64))) {
10012       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10013       // Do an any-extend to 32-bits if this is a half-word input.
10014       if (BSwapOp.getValueType() == MVT::i16)
10015         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10016
10017       SDValue Ops[] = {
10018         N->getOperand(0), BSwapOp, N->getOperand(2),
10019         DAG.getValueType(N->getOperand(1).getValueType())
10020       };
10021       return
10022         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10023                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10024                                 cast<StoreSDNode>(N)->getMemOperand());
10025     }
10026
10027     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10028     EVT VT = N->getOperand(1).getValueType();
10029     if (VT.isSimple()) {
10030       MVT StoreVT = VT.getSimpleVT();
10031       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10032           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10033            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10034         return expandVSXStoreForLE(N, DCI);
10035     }
10036     break;
10037   }
10038   case ISD::LOAD: {
10039     LoadSDNode *LD = cast<LoadSDNode>(N);
10040     EVT VT = LD->getValueType(0);
10041
10042     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10043     if (VT.isSimple()) {
10044       MVT LoadVT = VT.getSimpleVT();
10045       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10046           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10047            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10048         return expandVSXLoadForLE(N, DCI);
10049     }
10050
10051     EVT MemVT = LD->getMemoryVT();
10052     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10053     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
10054     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10055     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
10056     if (LD->isUnindexed() && VT.isVector() &&
10057         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10058           // P8 and later hardware should just use LOAD.
10059           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10060                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10061          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10062           LD->getAlignment() >= ScalarABIAlignment)) &&
10063         LD->getAlignment() < ABIAlignment) {
10064       // This is a type-legal unaligned Altivec or QPX load.
10065       SDValue Chain = LD->getChain();
10066       SDValue Ptr = LD->getBasePtr();
10067       bool isLittleEndian = Subtarget.isLittleEndian();
10068
10069       // This implements the loading of unaligned vectors as described in
10070       // the venerable Apple Velocity Engine overview. Specifically:
10071       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10072       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10073       //
10074       // The general idea is to expand a sequence of one or more unaligned
10075       // loads into an alignment-based permutation-control instruction (lvsl
10076       // or lvsr), a series of regular vector loads (which always truncate
10077       // their input address to an aligned address), and a series of
10078       // permutations.  The results of these permutations are the requested
10079       // loaded values.  The trick is that the last "extra" load is not taken
10080       // from the address you might suspect (sizeof(vector) bytes after the
10081       // last requested load), but rather sizeof(vector) - 1 bytes after the
10082       // last requested vector. The point of this is to avoid a page fault if
10083       // the base address happened to be aligned. This works because if the
10084       // base address is aligned, then adding less than a full vector length
10085       // will cause the last vector in the sequence to be (re)loaded.
10086       // Otherwise, the next vector will be fetched as you might suspect was
10087       // necessary.
10088
10089       // We might be able to reuse the permutation generation from
10090       // a different base address offset from this one by an aligned amount.
10091       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10092       // optimization later.
10093       Intrinsic::ID Intr, IntrLD, IntrPerm;
10094       MVT PermCntlTy, PermTy, LDTy;
10095       if (Subtarget.hasAltivec()) {
10096         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10097                                  Intrinsic::ppc_altivec_lvsl;
10098         IntrLD = Intrinsic::ppc_altivec_lvx;
10099         IntrPerm = Intrinsic::ppc_altivec_vperm;
10100         PermCntlTy = MVT::v16i8;
10101         PermTy = MVT::v4i32;
10102         LDTy = MVT::v4i32;
10103       } else {
10104         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10105                                        Intrinsic::ppc_qpx_qvlpcls;
10106         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10107                                        Intrinsic::ppc_qpx_qvlfs;
10108         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10109         PermCntlTy = MVT::v4f64;
10110         PermTy = MVT::v4f64;
10111         LDTy = MemVT.getSimpleVT();
10112       }
10113
10114       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10115
10116       // Create the new MMO for the new base load. It is like the original MMO,
10117       // but represents an area in memory almost twice the vector size centered
10118       // on the original address. If the address is unaligned, we might start
10119       // reading up to (sizeof(vector)-1) bytes below the address of the
10120       // original unaligned load.
10121       MachineFunction &MF = DAG.getMachineFunction();
10122       MachineMemOperand *BaseMMO =
10123         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10124                                 2*MemVT.getStoreSize()-1);
10125
10126       // Create the new base load.
10127       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, dl, getPointerTy());
10128       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10129       SDValue BaseLoad =
10130         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10131                                 DAG.getVTList(PermTy, MVT::Other),
10132                                 BaseLoadOps, LDTy, BaseMMO);
10133
10134       // Note that the value of IncOffset (which is provided to the next
10135       // load's pointer info offset value, and thus used to calculate the
10136       // alignment), and the value of IncValue (which is actually used to
10137       // increment the pointer value) are different! This is because we
10138       // require the next load to appear to be aligned, even though it
10139       // is actually offset from the base pointer by a lesser amount.
10140       int IncOffset = VT.getSizeInBits() / 8;
10141       int IncValue = IncOffset;
10142
10143       // Walk (both up and down) the chain looking for another load at the real
10144       // (aligned) offset (the alignment of the other load does not matter in
10145       // this case). If found, then do not use the offset reduction trick, as
10146       // that will prevent the loads from being later combined (as they would
10147       // otherwise be duplicates).
10148       if (!findConsecutiveLoad(LD, DAG))
10149         --IncValue;
10150
10151       SDValue Increment = DAG.getConstant(IncValue, dl, getPointerTy());
10152       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10153
10154       MachineMemOperand *ExtraMMO =
10155         MF.getMachineMemOperand(LD->getMemOperand(),
10156                                 1, 2*MemVT.getStoreSize()-1);
10157       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10158       SDValue ExtraLoad =
10159         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10160                                 DAG.getVTList(PermTy, MVT::Other),
10161                                 ExtraLoadOps, LDTy, ExtraMMO);
10162
10163       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10164         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10165
10166       // Because vperm has a big-endian bias, we must reverse the order
10167       // of the input vectors and complement the permute control vector
10168       // when generating little endian code.  We have already handled the
10169       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10170       // and ExtraLoad here.
10171       SDValue Perm;
10172       if (isLittleEndian)
10173         Perm = BuildIntrinsicOp(IntrPerm,
10174                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10175       else
10176         Perm = BuildIntrinsicOp(IntrPerm,
10177                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10178
10179       if (VT != PermTy)
10180         Perm = Subtarget.hasAltivec() ?
10181                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10182                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10183                                DAG.getTargetConstant(1, dl, MVT::i64));
10184                                // second argument is 1 because this rounding
10185                                // is always exact.
10186
10187       // The output of the permutation is our loaded result, the TokenFactor is
10188       // our new chain.
10189       DCI.CombineTo(N, Perm, TF);
10190       return SDValue(N, 0);
10191     }
10192     }
10193     break;
10194     case ISD::INTRINSIC_WO_CHAIN: {
10195       bool isLittleEndian = Subtarget.isLittleEndian();
10196       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10197       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10198                                            : Intrinsic::ppc_altivec_lvsl);
10199       if ((IID == Intr ||
10200            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10201            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10202         N->getOperand(1)->getOpcode() == ISD::ADD) {
10203         SDValue Add = N->getOperand(1);
10204
10205         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10206                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10207
10208         if (DAG.MaskedValueIsZero(
10209                 Add->getOperand(1),
10210                 APInt::getAllOnesValue(Bits /* alignment */)
10211                     .zext(
10212                         Add.getValueType().getScalarType().getSizeInBits()))) {
10213           SDNode *BasePtr = Add->getOperand(0).getNode();
10214           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10215                                     UE = BasePtr->use_end();
10216                UI != UE; ++UI) {
10217             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10218                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10219               // We've found another LVSL/LVSR, and this address is an aligned
10220               // multiple of that one. The results will be the same, so use the
10221               // one we've just found instead.
10222
10223               return SDValue(*UI, 0);
10224             }
10225           }
10226         }
10227
10228         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10229           SDNode *BasePtr = Add->getOperand(0).getNode();
10230           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10231                UE = BasePtr->use_end(); UI != UE; ++UI) {
10232             if (UI->getOpcode() == ISD::ADD &&
10233                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10234                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10235                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10236                 (1ULL << Bits) == 0) {
10237               SDNode *OtherAdd = *UI;
10238               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10239                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10240                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10241                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10242                   return SDValue(*VI, 0);
10243                 }
10244               }
10245             }
10246           }
10247         }
10248       }
10249     }
10250
10251     break;
10252   case ISD::INTRINSIC_W_CHAIN: {
10253     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10254     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10255       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10256       default:
10257         break;
10258       case Intrinsic::ppc_vsx_lxvw4x:
10259       case Intrinsic::ppc_vsx_lxvd2x:
10260         return expandVSXLoadForLE(N, DCI);
10261       }
10262     }
10263     break;
10264   }
10265   case ISD::INTRINSIC_VOID: {
10266     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10267     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10268       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10269       default:
10270         break;
10271       case Intrinsic::ppc_vsx_stxvw4x:
10272       case Intrinsic::ppc_vsx_stxvd2x:
10273         return expandVSXStoreForLE(N, DCI);
10274       }
10275     }
10276     break;
10277   }
10278   case ISD::BSWAP:
10279     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10280     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10281         N->getOperand(0).hasOneUse() &&
10282         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10283          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10284           N->getValueType(0) == MVT::i64))) {
10285       SDValue Load = N->getOperand(0);
10286       LoadSDNode *LD = cast<LoadSDNode>(Load);
10287       // Create the byte-swapping load.
10288       SDValue Ops[] = {
10289         LD->getChain(),    // Chain
10290         LD->getBasePtr(),  // Ptr
10291         DAG.getValueType(N->getValueType(0)) // VT
10292       };
10293       SDValue BSLoad =
10294         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10295                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10296                                               MVT::i64 : MVT::i32, MVT::Other),
10297                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10298
10299       // If this is an i16 load, insert the truncate.
10300       SDValue ResVal = BSLoad;
10301       if (N->getValueType(0) == MVT::i16)
10302         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10303
10304       // First, combine the bswap away.  This makes the value produced by the
10305       // load dead.
10306       DCI.CombineTo(N, ResVal);
10307
10308       // Next, combine the load away, we give it a bogus result value but a real
10309       // chain result.  The result value is dead because the bswap is dead.
10310       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10311
10312       // Return N so it doesn't get rechecked!
10313       return SDValue(N, 0);
10314     }
10315
10316     break;
10317   case PPCISD::VCMP: {
10318     // If a VCMPo node already exists with exactly the same operands as this
10319     // node, use its result instead of this node (VCMPo computes both a CR6 and
10320     // a normal output).
10321     //
10322     if (!N->getOperand(0).hasOneUse() &&
10323         !N->getOperand(1).hasOneUse() &&
10324         !N->getOperand(2).hasOneUse()) {
10325
10326       // Scan all of the users of the LHS, looking for VCMPo's that match.
10327       SDNode *VCMPoNode = nullptr;
10328
10329       SDNode *LHSN = N->getOperand(0).getNode();
10330       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10331            UI != E; ++UI)
10332         if (UI->getOpcode() == PPCISD::VCMPo &&
10333             UI->getOperand(1) == N->getOperand(1) &&
10334             UI->getOperand(2) == N->getOperand(2) &&
10335             UI->getOperand(0) == N->getOperand(0)) {
10336           VCMPoNode = *UI;
10337           break;
10338         }
10339
10340       // If there is no VCMPo node, or if the flag value has a single use, don't
10341       // transform this.
10342       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10343         break;
10344
10345       // Look at the (necessarily single) use of the flag value.  If it has a
10346       // chain, this transformation is more complex.  Note that multiple things
10347       // could use the value result, which we should ignore.
10348       SDNode *FlagUser = nullptr;
10349       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10350            FlagUser == nullptr; ++UI) {
10351         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10352         SDNode *User = *UI;
10353         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10354           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10355             FlagUser = User;
10356             break;
10357           }
10358         }
10359       }
10360
10361       // If the user is a MFOCRF instruction, we know this is safe.
10362       // Otherwise we give up for right now.
10363       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10364         return SDValue(VCMPoNode, 0);
10365     }
10366     break;
10367   }
10368   case ISD::BRCOND: {
10369     SDValue Cond = N->getOperand(1);
10370     SDValue Target = N->getOperand(2);
10371  
10372     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10373         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10374           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10375
10376       // We now need to make the intrinsic dead (it cannot be instruction
10377       // selected).
10378       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10379       assert(Cond.getNode()->hasOneUse() &&
10380              "Counter decrement has more than one use");
10381
10382       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10383                          N->getOperand(0), Target);
10384     }
10385   }
10386   break;
10387   case ISD::BR_CC: {
10388     // If this is a branch on an altivec predicate comparison, lower this so
10389     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10390     // lowering is done pre-legalize, because the legalizer lowers the predicate
10391     // compare down to code that is difficult to reassemble.
10392     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10393     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10394
10395     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10396     // value. If so, pass-through the AND to get to the intrinsic.
10397     if (LHS.getOpcode() == ISD::AND &&
10398         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10399         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10400           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10401         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10402         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10403           isZero())
10404       LHS = LHS.getOperand(0);
10405
10406     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10407         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10408           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10409         isa<ConstantSDNode>(RHS)) {
10410       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10411              "Counter decrement comparison is not EQ or NE");
10412
10413       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10414       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10415                     (CC == ISD::SETNE && !Val);
10416
10417       // We now need to make the intrinsic dead (it cannot be instruction
10418       // selected).
10419       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10420       assert(LHS.getNode()->hasOneUse() &&
10421              "Counter decrement has more than one use");
10422
10423       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10424                          N->getOperand(0), N->getOperand(4));
10425     }
10426
10427     int CompareOpc;
10428     bool isDot;
10429
10430     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10431         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10432         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10433       assert(isDot && "Can't compare against a vector result!");
10434
10435       // If this is a comparison against something other than 0/1, then we know
10436       // that the condition is never/always true.
10437       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10438       if (Val != 0 && Val != 1) {
10439         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10440           return N->getOperand(0);
10441         // Always !=, turn it into an unconditional branch.
10442         return DAG.getNode(ISD::BR, dl, MVT::Other,
10443                            N->getOperand(0), N->getOperand(4));
10444       }
10445
10446       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10447
10448       // Create the PPCISD altivec 'dot' comparison node.
10449       SDValue Ops[] = {
10450         LHS.getOperand(2),  // LHS of compare
10451         LHS.getOperand(3),  // RHS of compare
10452         DAG.getConstant(CompareOpc, dl, MVT::i32)
10453       };
10454       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10455       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10456
10457       // Unpack the result based on how the target uses it.
10458       PPC::Predicate CompOpc;
10459       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10460       default:  // Can't happen, don't crash on invalid number though.
10461       case 0:   // Branch on the value of the EQ bit of CR6.
10462         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10463         break;
10464       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10465         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10466         break;
10467       case 2:   // Branch on the value of the LT bit of CR6.
10468         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10469         break;
10470       case 3:   // Branch on the inverted value of the LT bit of CR6.
10471         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10472         break;
10473       }
10474
10475       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10476                          DAG.getConstant(CompOpc, dl, MVT::i32),
10477                          DAG.getRegister(PPC::CR6, MVT::i32),
10478                          N->getOperand(4), CompNode.getValue(1));
10479     }
10480     break;
10481   }
10482   }
10483
10484   return SDValue();
10485 }
10486
10487 SDValue
10488 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10489                                   SelectionDAG &DAG,
10490                                   std::vector<SDNode *> *Created) const {
10491   // fold (sdiv X, pow2)
10492   EVT VT = N->getValueType(0);
10493   if (VT == MVT::i64 && !Subtarget.isPPC64())
10494     return SDValue();
10495   if ((VT != MVT::i32 && VT != MVT::i64) ||
10496       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10497     return SDValue();
10498
10499   SDLoc DL(N);
10500   SDValue N0 = N->getOperand(0);
10501
10502   bool IsNegPow2 = (-Divisor).isPowerOf2();
10503   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10504   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10505
10506   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10507   if (Created)
10508     Created->push_back(Op.getNode());
10509
10510   if (IsNegPow2) {
10511     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10512     if (Created)
10513       Created->push_back(Op.getNode());
10514   }
10515
10516   return Op;
10517 }
10518
10519 //===----------------------------------------------------------------------===//
10520 // Inline Assembly Support
10521 //===----------------------------------------------------------------------===//
10522
10523 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10524                                                       APInt &KnownZero,
10525                                                       APInt &KnownOne,
10526                                                       const SelectionDAG &DAG,
10527                                                       unsigned Depth) const {
10528   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10529   switch (Op.getOpcode()) {
10530   default: break;
10531   case PPCISD::LBRX: {
10532     // lhbrx is known to have the top bits cleared out.
10533     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10534       KnownZero = 0xFFFF0000;
10535     break;
10536   }
10537   case ISD::INTRINSIC_WO_CHAIN: {
10538     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10539     default: break;
10540     case Intrinsic::ppc_altivec_vcmpbfp_p:
10541     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10542     case Intrinsic::ppc_altivec_vcmpequb_p:
10543     case Intrinsic::ppc_altivec_vcmpequh_p:
10544     case Intrinsic::ppc_altivec_vcmpequw_p:
10545     case Intrinsic::ppc_altivec_vcmpequd_p:
10546     case Intrinsic::ppc_altivec_vcmpgefp_p:
10547     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10548     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10549     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10550     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10551     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10552     case Intrinsic::ppc_altivec_vcmpgtub_p:
10553     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10554     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10555     case Intrinsic::ppc_altivec_vcmpgtud_p:
10556       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10557       break;
10558     }
10559   }
10560   }
10561 }
10562
10563 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10564   switch (Subtarget.getDarwinDirective()) {
10565   default: break;
10566   case PPC::DIR_970:
10567   case PPC::DIR_PWR4:
10568   case PPC::DIR_PWR5:
10569   case PPC::DIR_PWR5X:
10570   case PPC::DIR_PWR6:
10571   case PPC::DIR_PWR6X:
10572   case PPC::DIR_PWR7:
10573   case PPC::DIR_PWR8: {
10574     if (!ML)
10575       break;
10576
10577     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10578
10579     // For small loops (between 5 and 8 instructions), align to a 32-byte
10580     // boundary so that the entire loop fits in one instruction-cache line.
10581     uint64_t LoopSize = 0;
10582     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10583       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10584         LoopSize += TII->GetInstSizeInBytes(J);
10585
10586     if (LoopSize > 16 && LoopSize <= 32)
10587       return 5;
10588
10589     break;
10590   }
10591   }
10592
10593   return TargetLowering::getPrefLoopAlignment(ML);
10594 }
10595
10596 /// getConstraintType - Given a constraint, return the type of
10597 /// constraint it is for this target.
10598 PPCTargetLowering::ConstraintType
10599 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10600   if (Constraint.size() == 1) {
10601     switch (Constraint[0]) {
10602     default: break;
10603     case 'b':
10604     case 'r':
10605     case 'f':
10606     case 'v':
10607     case 'y':
10608       return C_RegisterClass;
10609     case 'Z':
10610       // FIXME: While Z does indicate a memory constraint, it specifically
10611       // indicates an r+r address (used in conjunction with the 'y' modifier
10612       // in the replacement string). Currently, we're forcing the base
10613       // register to be r0 in the asm printer (which is interpreted as zero)
10614       // and forming the complete address in the second register. This is
10615       // suboptimal.
10616       return C_Memory;
10617     }
10618   } else if (Constraint == "wc") { // individual CR bits.
10619     return C_RegisterClass;
10620   } else if (Constraint == "wa" || Constraint == "wd" ||
10621              Constraint == "wf" || Constraint == "ws") {
10622     return C_RegisterClass; // VSX registers.
10623   }
10624   return TargetLowering::getConstraintType(Constraint);
10625 }
10626
10627 /// Examine constraint type and operand type and determine a weight value.
10628 /// This object must already have been set up with the operand type
10629 /// and the current alternative constraint selected.
10630 TargetLowering::ConstraintWeight
10631 PPCTargetLowering::getSingleConstraintMatchWeight(
10632     AsmOperandInfo &info, const char *constraint) const {
10633   ConstraintWeight weight = CW_Invalid;
10634   Value *CallOperandVal = info.CallOperandVal;
10635     // If we don't have a value, we can't do a match,
10636     // but allow it at the lowest weight.
10637   if (!CallOperandVal)
10638     return CW_Default;
10639   Type *type = CallOperandVal->getType();
10640
10641   // Look at the constraint type.
10642   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10643     return CW_Register; // an individual CR bit.
10644   else if ((StringRef(constraint) == "wa" ||
10645             StringRef(constraint) == "wd" ||
10646             StringRef(constraint) == "wf") &&
10647            type->isVectorTy())
10648     return CW_Register;
10649   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10650     return CW_Register;
10651
10652   switch (*constraint) {
10653   default:
10654     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10655     break;
10656   case 'b':
10657     if (type->isIntegerTy())
10658       weight = CW_Register;
10659     break;
10660   case 'f':
10661     if (type->isFloatTy())
10662       weight = CW_Register;
10663     break;
10664   case 'd':
10665     if (type->isDoubleTy())
10666       weight = CW_Register;
10667     break;
10668   case 'v':
10669     if (type->isVectorTy())
10670       weight = CW_Register;
10671     break;
10672   case 'y':
10673     weight = CW_Register;
10674     break;
10675   case 'Z':
10676     weight = CW_Memory;
10677     break;
10678   }
10679   return weight;
10680 }
10681
10682 std::pair<unsigned, const TargetRegisterClass *>
10683 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10684                                                 const std::string &Constraint,
10685                                                 MVT VT) const {
10686   if (Constraint.size() == 1) {
10687     // GCC RS6000 Constraint Letters
10688     switch (Constraint[0]) {
10689     case 'b':   // R1-R31
10690       if (VT == MVT::i64 && Subtarget.isPPC64())
10691         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10692       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10693     case 'r':   // R0-R31
10694       if (VT == MVT::i64 && Subtarget.isPPC64())
10695         return std::make_pair(0U, &PPC::G8RCRegClass);
10696       return std::make_pair(0U, &PPC::GPRCRegClass);
10697     case 'f':
10698       if (VT == MVT::f32 || VT == MVT::i32)
10699         return std::make_pair(0U, &PPC::F4RCRegClass);
10700       if (VT == MVT::f64 || VT == MVT::i64)
10701         return std::make_pair(0U, &PPC::F8RCRegClass);
10702       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10703         return std::make_pair(0U, &PPC::QFRCRegClass);
10704       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10705         return std::make_pair(0U, &PPC::QSRCRegClass);
10706       break;
10707     case 'v':
10708       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10709         return std::make_pair(0U, &PPC::QFRCRegClass);
10710       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10711         return std::make_pair(0U, &PPC::QSRCRegClass);
10712       return std::make_pair(0U, &PPC::VRRCRegClass);
10713     case 'y':   // crrc
10714       return std::make_pair(0U, &PPC::CRRCRegClass);
10715     }
10716   } else if (Constraint == "wc") { // an individual CR bit.
10717     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10718   } else if (Constraint == "wa" || Constraint == "wd" ||
10719              Constraint == "wf") {
10720     return std::make_pair(0U, &PPC::VSRCRegClass);
10721   } else if (Constraint == "ws") {
10722     if (VT == MVT::f32)
10723       return std::make_pair(0U, &PPC::VSSRCRegClass);
10724     else
10725       return std::make_pair(0U, &PPC::VSFRCRegClass);
10726   }
10727
10728   std::pair<unsigned, const TargetRegisterClass *> R =
10729       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10730
10731   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10732   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10733   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10734   // register.
10735   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10736   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10737   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10738       PPC::GPRCRegClass.contains(R.first))
10739     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10740                             PPC::sub_32, &PPC::G8RCRegClass),
10741                           &PPC::G8RCRegClass);
10742
10743   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10744   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10745     R.first = PPC::CR0;
10746     R.second = &PPC::CRRCRegClass;
10747   }
10748
10749   return R;
10750 }
10751
10752
10753 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10754 /// vector.  If it is invalid, don't add anything to Ops.
10755 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10756                                                      std::string &Constraint,
10757                                                      std::vector<SDValue>&Ops,
10758                                                      SelectionDAG &DAG) const {
10759   SDValue Result;
10760
10761   // Only support length 1 constraints.
10762   if (Constraint.length() > 1) return;
10763
10764   char Letter = Constraint[0];
10765   switch (Letter) {
10766   default: break;
10767   case 'I':
10768   case 'J':
10769   case 'K':
10770   case 'L':
10771   case 'M':
10772   case 'N':
10773   case 'O':
10774   case 'P': {
10775     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10776     if (!CST) return; // Must be an immediate to match.
10777     SDLoc dl(Op);
10778     int64_t Value = CST->getSExtValue();
10779     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10780                          // numbers are printed as such.
10781     switch (Letter) {
10782     default: llvm_unreachable("Unknown constraint letter!");
10783     case 'I':  // "I" is a signed 16-bit constant.
10784       if (isInt<16>(Value))
10785         Result = DAG.getTargetConstant(Value, dl, TCVT);
10786       break;
10787     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10788       if (isShiftedUInt<16, 16>(Value))
10789         Result = DAG.getTargetConstant(Value, dl, TCVT);
10790       break;
10791     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10792       if (isShiftedInt<16, 16>(Value))
10793         Result = DAG.getTargetConstant(Value, dl, TCVT);
10794       break;
10795     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10796       if (isUInt<16>(Value))
10797         Result = DAG.getTargetConstant(Value, dl, TCVT);
10798       break;
10799     case 'M':  // "M" is a constant that is greater than 31.
10800       if (Value > 31)
10801         Result = DAG.getTargetConstant(Value, dl, TCVT);
10802       break;
10803     case 'N':  // "N" is a positive constant that is an exact power of two.
10804       if (Value > 0 && isPowerOf2_64(Value))
10805         Result = DAG.getTargetConstant(Value, dl, TCVT);
10806       break;
10807     case 'O':  // "O" is the constant zero.
10808       if (Value == 0)
10809         Result = DAG.getTargetConstant(Value, dl, TCVT);
10810       break;
10811     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10812       if (isInt<16>(-Value))
10813         Result = DAG.getTargetConstant(Value, dl, TCVT);
10814       break;
10815     }
10816     break;
10817   }
10818   }
10819
10820   if (Result.getNode()) {
10821     Ops.push_back(Result);
10822     return;
10823   }
10824
10825   // Handle standard constraint letters.
10826   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10827 }
10828
10829 // isLegalAddressingMode - Return true if the addressing mode represented
10830 // by AM is legal for this target, for a load/store of the specified type.
10831 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10832                                               Type *Ty) const {
10833   // PPC does not allow r+i addressing modes for vectors!
10834   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10835     return false;
10836
10837   // PPC allows a sign-extended 16-bit immediate field.
10838   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10839     return false;
10840
10841   // No global is ever allowed as a base.
10842   if (AM.BaseGV)
10843     return false;
10844
10845   // PPC only support r+r,
10846   switch (AM.Scale) {
10847   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10848     break;
10849   case 1:
10850     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10851       return false;
10852     // Otherwise we have r+r or r+i.
10853     break;
10854   case 2:
10855     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10856       return false;
10857     // Allow 2*r as r+r.
10858     break;
10859   default:
10860     // No other scales are supported.
10861     return false;
10862   }
10863
10864   return true;
10865 }
10866
10867 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10868                                            SelectionDAG &DAG) const {
10869   MachineFunction &MF = DAG.getMachineFunction();
10870   MachineFrameInfo *MFI = MF.getFrameInfo();
10871   MFI->setReturnAddressIsTaken(true);
10872
10873   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10874     return SDValue();
10875
10876   SDLoc dl(Op);
10877   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10878
10879   // Make sure the function does not optimize away the store of the RA to
10880   // the stack.
10881   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10882   FuncInfo->setLRStoreRequired();
10883   bool isPPC64 = Subtarget.isPPC64();
10884
10885   if (Depth > 0) {
10886     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10887     SDValue Offset =
10888         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
10889                         isPPC64 ? MVT::i64 : MVT::i32);
10890     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10891                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10892                                    FrameAddr, Offset),
10893                        MachinePointerInfo(), false, false, false, 0);
10894   }
10895
10896   // Just load the return address off the stack.
10897   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10898   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10899                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10900 }
10901
10902 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10903                                           SelectionDAG &DAG) const {
10904   SDLoc dl(Op);
10905   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10906
10907   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10908   bool isPPC64 = PtrVT == MVT::i64;
10909
10910   MachineFunction &MF = DAG.getMachineFunction();
10911   MachineFrameInfo *MFI = MF.getFrameInfo();
10912   MFI->setFrameAddressIsTaken(true);
10913
10914   // Naked functions never have a frame pointer, and so we use r1. For all
10915   // other functions, this decision must be delayed until during PEI.
10916   unsigned FrameReg;
10917   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10918     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10919   else
10920     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10921
10922   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10923                                          PtrVT);
10924   while (Depth--)
10925     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10926                             FrameAddr, MachinePointerInfo(), false, false,
10927                             false, 0);
10928   return FrameAddr;
10929 }
10930
10931 // FIXME? Maybe this could be a TableGen attribute on some registers and
10932 // this table could be generated automatically from RegInfo.
10933 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10934                                               EVT VT) const {
10935   bool isPPC64 = Subtarget.isPPC64();
10936   bool isDarwinABI = Subtarget.isDarwinABI();
10937
10938   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10939       (!isPPC64 && VT != MVT::i32))
10940     report_fatal_error("Invalid register global variable type");
10941
10942   bool is64Bit = isPPC64 && VT == MVT::i64;
10943   unsigned Reg = StringSwitch<unsigned>(RegName)
10944                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10945                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10946                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10947                                   (is64Bit ? PPC::X13 : PPC::R13))
10948                    .Default(0);
10949
10950   if (Reg)
10951     return Reg;
10952   report_fatal_error("Invalid register name global variable");
10953 }
10954
10955 bool
10956 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10957   // The PowerPC target isn't yet aware of offsets.
10958   return false;
10959 }
10960
10961 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10962                                            const CallInst &I,
10963                                            unsigned Intrinsic) const {
10964
10965   switch (Intrinsic) {
10966   case Intrinsic::ppc_qpx_qvlfd:
10967   case Intrinsic::ppc_qpx_qvlfs:
10968   case Intrinsic::ppc_qpx_qvlfcd:
10969   case Intrinsic::ppc_qpx_qvlfcs:
10970   case Intrinsic::ppc_qpx_qvlfiwa:
10971   case Intrinsic::ppc_qpx_qvlfiwz:
10972   case Intrinsic::ppc_altivec_lvx:
10973   case Intrinsic::ppc_altivec_lvxl:
10974   case Intrinsic::ppc_altivec_lvebx:
10975   case Intrinsic::ppc_altivec_lvehx:
10976   case Intrinsic::ppc_altivec_lvewx:
10977   case Intrinsic::ppc_vsx_lxvd2x:
10978   case Intrinsic::ppc_vsx_lxvw4x: {
10979     EVT VT;
10980     switch (Intrinsic) {
10981     case Intrinsic::ppc_altivec_lvebx:
10982       VT = MVT::i8;
10983       break;
10984     case Intrinsic::ppc_altivec_lvehx:
10985       VT = MVT::i16;
10986       break;
10987     case Intrinsic::ppc_altivec_lvewx:
10988       VT = MVT::i32;
10989       break;
10990     case Intrinsic::ppc_vsx_lxvd2x:
10991       VT = MVT::v2f64;
10992       break;
10993     case Intrinsic::ppc_qpx_qvlfd:
10994       VT = MVT::v4f64;
10995       break;
10996     case Intrinsic::ppc_qpx_qvlfs:
10997       VT = MVT::v4f32;
10998       break;
10999     case Intrinsic::ppc_qpx_qvlfcd:
11000       VT = MVT::v2f64;
11001       break;
11002     case Intrinsic::ppc_qpx_qvlfcs:
11003       VT = MVT::v2f32;
11004       break;
11005     default:
11006       VT = MVT::v4i32;
11007       break;
11008     }
11009
11010     Info.opc = ISD::INTRINSIC_W_CHAIN;
11011     Info.memVT = VT;
11012     Info.ptrVal = I.getArgOperand(0);
11013     Info.offset = -VT.getStoreSize()+1;
11014     Info.size = 2*VT.getStoreSize()-1;
11015     Info.align = 1;
11016     Info.vol = false;
11017     Info.readMem = true;
11018     Info.writeMem = false;
11019     return true;
11020   }
11021   case Intrinsic::ppc_qpx_qvlfda:
11022   case Intrinsic::ppc_qpx_qvlfsa:
11023   case Intrinsic::ppc_qpx_qvlfcda:
11024   case Intrinsic::ppc_qpx_qvlfcsa:
11025   case Intrinsic::ppc_qpx_qvlfiwaa:
11026   case Intrinsic::ppc_qpx_qvlfiwza: {
11027     EVT VT;
11028     switch (Intrinsic) {
11029     case Intrinsic::ppc_qpx_qvlfda:
11030       VT = MVT::v4f64;
11031       break;
11032     case Intrinsic::ppc_qpx_qvlfsa:
11033       VT = MVT::v4f32;
11034       break;
11035     case Intrinsic::ppc_qpx_qvlfcda:
11036       VT = MVT::v2f64;
11037       break;
11038     case Intrinsic::ppc_qpx_qvlfcsa:
11039       VT = MVT::v2f32;
11040       break;
11041     default:
11042       VT = MVT::v4i32;
11043       break;
11044     }
11045
11046     Info.opc = ISD::INTRINSIC_W_CHAIN;
11047     Info.memVT = VT;
11048     Info.ptrVal = I.getArgOperand(0);
11049     Info.offset = 0;
11050     Info.size = VT.getStoreSize();
11051     Info.align = 1;
11052     Info.vol = false;
11053     Info.readMem = true;
11054     Info.writeMem = false;
11055     return true;
11056   }
11057   case Intrinsic::ppc_qpx_qvstfd:
11058   case Intrinsic::ppc_qpx_qvstfs:
11059   case Intrinsic::ppc_qpx_qvstfcd:
11060   case Intrinsic::ppc_qpx_qvstfcs:
11061   case Intrinsic::ppc_qpx_qvstfiw:
11062   case Intrinsic::ppc_altivec_stvx:
11063   case Intrinsic::ppc_altivec_stvxl:
11064   case Intrinsic::ppc_altivec_stvebx:
11065   case Intrinsic::ppc_altivec_stvehx:
11066   case Intrinsic::ppc_altivec_stvewx:
11067   case Intrinsic::ppc_vsx_stxvd2x:
11068   case Intrinsic::ppc_vsx_stxvw4x: {
11069     EVT VT;
11070     switch (Intrinsic) {
11071     case Intrinsic::ppc_altivec_stvebx:
11072       VT = MVT::i8;
11073       break;
11074     case Intrinsic::ppc_altivec_stvehx:
11075       VT = MVT::i16;
11076       break;
11077     case Intrinsic::ppc_altivec_stvewx:
11078       VT = MVT::i32;
11079       break;
11080     case Intrinsic::ppc_vsx_stxvd2x:
11081       VT = MVT::v2f64;
11082       break;
11083     case Intrinsic::ppc_qpx_qvstfd:
11084       VT = MVT::v4f64;
11085       break;
11086     case Intrinsic::ppc_qpx_qvstfs:
11087       VT = MVT::v4f32;
11088       break;
11089     case Intrinsic::ppc_qpx_qvstfcd:
11090       VT = MVT::v2f64;
11091       break;
11092     case Intrinsic::ppc_qpx_qvstfcs:
11093       VT = MVT::v2f32;
11094       break;
11095     default:
11096       VT = MVT::v4i32;
11097       break;
11098     }
11099
11100     Info.opc = ISD::INTRINSIC_VOID;
11101     Info.memVT = VT;
11102     Info.ptrVal = I.getArgOperand(1);
11103     Info.offset = -VT.getStoreSize()+1;
11104     Info.size = 2*VT.getStoreSize()-1;
11105     Info.align = 1;
11106     Info.vol = false;
11107     Info.readMem = false;
11108     Info.writeMem = true;
11109     return true;
11110   }
11111   case Intrinsic::ppc_qpx_qvstfda:
11112   case Intrinsic::ppc_qpx_qvstfsa:
11113   case Intrinsic::ppc_qpx_qvstfcda:
11114   case Intrinsic::ppc_qpx_qvstfcsa:
11115   case Intrinsic::ppc_qpx_qvstfiwa: {
11116     EVT VT;
11117     switch (Intrinsic) {
11118     case Intrinsic::ppc_qpx_qvstfda:
11119       VT = MVT::v4f64;
11120       break;
11121     case Intrinsic::ppc_qpx_qvstfsa:
11122       VT = MVT::v4f32;
11123       break;
11124     case Intrinsic::ppc_qpx_qvstfcda:
11125       VT = MVT::v2f64;
11126       break;
11127     case Intrinsic::ppc_qpx_qvstfcsa:
11128       VT = MVT::v2f32;
11129       break;
11130     default:
11131       VT = MVT::v4i32;
11132       break;
11133     }
11134
11135     Info.opc = ISD::INTRINSIC_VOID;
11136     Info.memVT = VT;
11137     Info.ptrVal = I.getArgOperand(1);
11138     Info.offset = 0;
11139     Info.size = VT.getStoreSize();
11140     Info.align = 1;
11141     Info.vol = false;
11142     Info.readMem = false;
11143     Info.writeMem = true;
11144     return true;
11145   }
11146   default:
11147     break;
11148   }
11149
11150   return false;
11151 }
11152
11153 /// getOptimalMemOpType - Returns the target specific optimal type for load
11154 /// and store operations as a result of memset, memcpy, and memmove
11155 /// lowering. If DstAlign is zero that means it's safe to destination
11156 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11157 /// means there isn't a need to check it against alignment requirement,
11158 /// probably because the source does not need to be loaded. If 'IsMemset' is
11159 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11160 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11161 /// source is constant so it does not need to be loaded.
11162 /// It returns EVT::Other if the type should be determined using generic
11163 /// target-independent logic.
11164 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11165                                            unsigned DstAlign, unsigned SrcAlign,
11166                                            bool IsMemset, bool ZeroMemset,
11167                                            bool MemcpyStrSrc,
11168                                            MachineFunction &MF) const {
11169   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11170     const Function *F = MF.getFunction();
11171     // When expanding a memset, require at least two QPX instructions to cover
11172     // the cost of loading the value to be stored from the constant pool.
11173     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11174        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11175         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11176       return MVT::v4f64;
11177     }
11178
11179     // We should use Altivec/VSX loads and stores when available. For unaligned
11180     // addresses, unaligned VSX loads are only fast starting with the P8.
11181     if (Subtarget.hasAltivec() && Size >= 16 &&
11182         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11183          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11184       return MVT::v4i32;
11185   }
11186
11187   if (Subtarget.isPPC64()) {
11188     return MVT::i64;
11189   }
11190
11191   return MVT::i32;
11192 }
11193
11194 /// \brief Returns true if it is beneficial to convert a load of a constant
11195 /// to just the constant itself.
11196 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11197                                                           Type *Ty) const {
11198   assert(Ty->isIntegerTy());
11199
11200   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11201   if (BitSize == 0 || BitSize > 64)
11202     return false;
11203   return true;
11204 }
11205
11206 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11207   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11208     return false;
11209   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11210   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11211   return NumBits1 == 64 && NumBits2 == 32;
11212 }
11213
11214 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11215   if (!VT1.isInteger() || !VT2.isInteger())
11216     return false;
11217   unsigned NumBits1 = VT1.getSizeInBits();
11218   unsigned NumBits2 = VT2.getSizeInBits();
11219   return NumBits1 == 64 && NumBits2 == 32;
11220 }
11221
11222 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11223   // Generally speaking, zexts are not free, but they are free when they can be
11224   // folded with other operations.
11225   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11226     EVT MemVT = LD->getMemoryVT();
11227     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11228          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11229         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11230          LD->getExtensionType() == ISD::ZEXTLOAD))
11231       return true;
11232   }
11233
11234   // FIXME: Add other cases...
11235   //  - 32-bit shifts with a zext to i64
11236   //  - zext after ctlz, bswap, etc.
11237   //  - zext after and by a constant mask
11238
11239   return TargetLowering::isZExtFree(Val, VT2);
11240 }
11241
11242 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11243   assert(VT.isFloatingPoint());
11244   return true;
11245 }
11246
11247 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11248   return isInt<16>(Imm) || isUInt<16>(Imm);
11249 }
11250
11251 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11252   return isInt<16>(Imm) || isUInt<16>(Imm);
11253 }
11254
11255 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11256                                                        unsigned,
11257                                                        unsigned,
11258                                                        bool *Fast) const {
11259   if (DisablePPCUnaligned)
11260     return false;
11261
11262   // PowerPC supports unaligned memory access for simple non-vector types.
11263   // Although accessing unaligned addresses is not as efficient as accessing
11264   // aligned addresses, it is generally more efficient than manual expansion,
11265   // and generally only traps for software emulation when crossing page
11266   // boundaries.
11267
11268   if (!VT.isSimple())
11269     return false;
11270
11271   if (VT.getSimpleVT().isVector()) {
11272     if (Subtarget.hasVSX()) {
11273       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11274           VT != MVT::v4f32 && VT != MVT::v4i32)
11275         return false;
11276     } else {
11277       return false;
11278     }
11279   }
11280
11281   if (VT == MVT::ppcf128)
11282     return false;
11283
11284   if (Fast)
11285     *Fast = true;
11286
11287   return true;
11288 }
11289
11290 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11291   VT = VT.getScalarType();
11292
11293   if (!VT.isSimple())
11294     return false;
11295
11296   switch (VT.getSimpleVT().SimpleTy) {
11297   case MVT::f32:
11298   case MVT::f64:
11299     return true;
11300   default:
11301     break;
11302   }
11303
11304   return false;
11305 }
11306
11307 const MCPhysReg *
11308 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11309   // LR is a callee-save register, but we must treat it as clobbered by any call
11310   // site. Hence we include LR in the scratch registers, which are in turn added
11311   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11312   // to CTR, which is used by any indirect call.
11313   static const MCPhysReg ScratchRegs[] = {
11314     PPC::X12, PPC::LR8, PPC::CTR8, 0
11315   };
11316
11317   return ScratchRegs;
11318 }
11319
11320 bool
11321 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11322                      EVT VT , unsigned DefinedValues) const {
11323   if (VT == MVT::v2i64)
11324     return false;
11325
11326   if (Subtarget.hasQPX()) {
11327     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11328       return true;
11329   }
11330
11331   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11332 }
11333
11334 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11335   if (DisableILPPref || Subtarget.enableMachineScheduler())
11336     return TargetLowering::getSchedulingPreference(N);
11337
11338   return Sched::ILP;
11339 }
11340
11341 // Create a fast isel object.
11342 FastISel *
11343 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11344                                   const TargetLibraryInfo *LibInfo) const {
11345   return PPC::createFastISel(FuncInfo, LibInfo);
11346 }