]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Update tcpdump to 4.9.0.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "PPCCCState.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCPerfectShuffle.h"
20 #include "PPCTargetMachine.h"
21 #include "PPCTargetObjectFile.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include <list>
46
47 using namespace llvm;
48
49 #define DEBUG_TYPE "ppc-lowering"
50
51 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
52 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
55 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
56
57 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
58 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
59
60 static cl::opt<bool> DisableSCO("disable-ppc-sco",
61 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
62
63 STATISTIC(NumTailCalls, "Number of tail calls");
64 STATISTIC(NumSiblingCalls, "Number of sibling calls");
65
66 // FIXME: Remove this once the bug has been fixed!
67 extern cl::opt<bool> ANDIGlueBug;
68
69 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
70                                      const PPCSubtarget &STI)
71     : TargetLowering(TM), Subtarget(STI) {
72   // Use _setjmp/_longjmp instead of setjmp/longjmp.
73   setUseUnderscoreSetJmp(true);
74   setUseUnderscoreLongJmp(true);
75
76   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77   // arguments are at least 4/8 bytes aligned.
78   bool isPPC64 = Subtarget.isPPC64();
79   setMinStackArgumentAlignment(isPPC64 ? 8:4);
80
81   // Set up the register classes.
82   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
83   if (!useSoftFloat()) {
84     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
85     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
86   }
87
88   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
89   for (MVT VT : MVT::integer_valuetypes()) {
90     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
91     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
92   }
93
94   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
95
96   // PowerPC has pre-inc load and store's.
97   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
98   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
99   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
100   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
101   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
102   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
103   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
104   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
105   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
106   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
107   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
108   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
110   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
111
112   if (Subtarget.useCRBits()) {
113     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
114
115     if (isPPC64 || Subtarget.hasFPCVT()) {
116       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
117       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
118                          isPPC64 ? MVT::i64 : MVT::i32);
119       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
120       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
121                         isPPC64 ? MVT::i64 : MVT::i32);
122     } else {
123       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
124       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
125     }
126
127     // PowerPC does not support direct load / store of condition registers
128     setOperationAction(ISD::LOAD, MVT::i1, Custom);
129     setOperationAction(ISD::STORE, MVT::i1, Custom);
130
131     // FIXME: Remove this once the ANDI glue bug is fixed:
132     if (ANDIGlueBug)
133       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
134
135     for (MVT VT : MVT::integer_valuetypes()) {
136       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
137       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
138       setTruncStoreAction(VT, MVT::i1, Expand);
139     }
140
141     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
142   }
143
144   // This is used in the ppcf128->int sequence.  Note it has different semantics
145   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
146   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
147
148   // We do not currently implement these libm ops for PowerPC.
149   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
150   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
151   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
152   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
153   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
154   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
155
156   // PowerPC has no SREM/UREM instructions
157   setOperationAction(ISD::SREM, MVT::i32, Expand);
158   setOperationAction(ISD::UREM, MVT::i32, Expand);
159   setOperationAction(ISD::SREM, MVT::i64, Expand);
160   setOperationAction(ISD::UREM, MVT::i64, Expand);
161
162   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
163   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
164   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
165   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
166   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
167   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
168   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
169   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
170   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
171
172   // We don't support sin/cos/sqrt/fmod/pow
173   setOperationAction(ISD::FSIN , MVT::f64, Expand);
174   setOperationAction(ISD::FCOS , MVT::f64, Expand);
175   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
176   setOperationAction(ISD::FREM , MVT::f64, Expand);
177   setOperationAction(ISD::FPOW , MVT::f64, Expand);
178   setOperationAction(ISD::FMA  , MVT::f64, Legal);
179   setOperationAction(ISD::FSIN , MVT::f32, Expand);
180   setOperationAction(ISD::FCOS , MVT::f32, Expand);
181   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
182   setOperationAction(ISD::FREM , MVT::f32, Expand);
183   setOperationAction(ISD::FPOW , MVT::f32, Expand);
184   setOperationAction(ISD::FMA  , MVT::f32, Legal);
185
186   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
187
188   // If we're enabling GP optimizations, use hardware square root
189   if (!Subtarget.hasFSQRT() &&
190       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
191         Subtarget.hasFRE()))
192     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
193
194   if (!Subtarget.hasFSQRT() &&
195       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
196         Subtarget.hasFRES()))
197     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
198
199   if (Subtarget.hasFCPSGN()) {
200     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
201     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
202   } else {
203     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
204     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
205   }
206
207   if (Subtarget.hasFPRND()) {
208     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
209     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
210     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
211     setOperationAction(ISD::FROUND, MVT::f64, Legal);
212
213     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
214     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
215     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
216     setOperationAction(ISD::FROUND, MVT::f32, Legal);
217   }
218
219   // PowerPC does not have BSWAP, CTPOP or CTTZ
220   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
221   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
222   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
223   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
224
225   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
226     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
227     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
228   } else {
229     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
230     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
231   }
232
233   // PowerPC does not have ROTR
234   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
235   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
236
237   if (!Subtarget.useCRBits()) {
238     // PowerPC does not have Select
239     setOperationAction(ISD::SELECT, MVT::i32, Expand);
240     setOperationAction(ISD::SELECT, MVT::i64, Expand);
241     setOperationAction(ISD::SELECT, MVT::f32, Expand);
242     setOperationAction(ISD::SELECT, MVT::f64, Expand);
243   }
244
245   // PowerPC wants to turn select_cc of FP into fsel when possible.
246   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
247   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
248
249   // PowerPC wants to optimize integer setcc a bit
250   if (!Subtarget.useCRBits())
251     setOperationAction(ISD::SETCC, MVT::i32, Custom);
252
253   // PowerPC does not have BRCOND which requires SetCC
254   if (!Subtarget.useCRBits())
255     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
256
257   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
258
259   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
260   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261
262   // PowerPC does not have [U|S]INT_TO_FP
263   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
264   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
265
266   if (Subtarget.hasDirectMove() && isPPC64) {
267     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
268     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
269     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
270     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
271   } else {
272     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
273     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
274     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
275     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
276   }
277
278   // We cannot sextinreg(i1).  Expand to shifts.
279   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
280
281   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
282   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
283   // support continuation, user-level threading, and etc.. As a result, no
284   // other SjLj exception interfaces are implemented and please don't build
285   // your own exception handling based on them.
286   // LLVM/Clang supports zero-cost DWARF exception handling.
287   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
288   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
289
290   // We want to legalize GlobalAddress and ConstantPool nodes into the
291   // appropriate instructions to materialize the address.
292   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
293   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
294   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
295   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
296   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
297   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
298   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
299   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
300   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
301   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
302
303   // TRAP is legal.
304   setOperationAction(ISD::TRAP, MVT::Other, Legal);
305
306   // TRAMPOLINE is custom lowered.
307   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
308   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
309
310   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
312
313   if (Subtarget.isSVR4ABI()) {
314     if (isPPC64) {
315       // VAARG always uses double-word chunks, so promote anything smaller.
316       setOperationAction(ISD::VAARG, MVT::i1, Promote);
317       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
318       setOperationAction(ISD::VAARG, MVT::i8, Promote);
319       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
320       setOperationAction(ISD::VAARG, MVT::i16, Promote);
321       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
322       setOperationAction(ISD::VAARG, MVT::i32, Promote);
323       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
324       setOperationAction(ISD::VAARG, MVT::Other, Expand);
325     } else {
326       // VAARG is custom lowered with the 32-bit SVR4 ABI.
327       setOperationAction(ISD::VAARG, MVT::Other, Custom);
328       setOperationAction(ISD::VAARG, MVT::i64, Custom);
329     }
330   } else
331     setOperationAction(ISD::VAARG, MVT::Other, Expand);
332
333   if (Subtarget.isSVR4ABI() && !isPPC64)
334     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
335     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
336   else
337     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
338
339   // Use the default implementation.
340   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
341   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
342   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
343   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
344   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
345   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
346   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
347   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
348   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
349
350   // We want to custom lower some of our intrinsics.
351   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
352
353   // To handle counter-based loop conditions.
354   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
355
356   // Comparisons that require checking two conditions.
357   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
358   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
359   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
360   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
361   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
362   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
363   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
364   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
365   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
366   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
367   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
368   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
369
370   if (Subtarget.has64BitSupport()) {
371     // They also have instructions for converting between i64 and fp.
372     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
374     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
376     // This is just the low 32 bits of a (signed) fp->i64 conversion.
377     // We cannot do this with Promote because i64 is not a legal type.
378     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
379
380     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
381       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382   } else {
383     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
384     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
385   }
386
387   // With the instructions enabled under FPCVT, we can do everything.
388   if (Subtarget.hasFPCVT()) {
389     if (Subtarget.has64BitSupport()) {
390       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
391       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
392       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
393       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
394     }
395
396     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
397     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
398     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
399     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
400   }
401
402   if (Subtarget.use64BitRegs()) {
403     // 64-bit PowerPC implementations can support i64 types directly
404     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
405     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
406     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
407     // 64-bit PowerPC wants to expand i128 shifts itself.
408     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
409     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
410     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
411   } else {
412     // 32-bit PowerPC wants to expand i64 shifts itself.
413     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
414     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
415     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
416   }
417
418   if (Subtarget.hasAltivec()) {
419     // First set operation action for all vector types to expand. Then we
420     // will selectively turn on ones that can be effectively codegen'd.
421     for (MVT VT : MVT::vector_valuetypes()) {
422       // add/sub are legal for all supported vector VT's.
423       setOperationAction(ISD::ADD, VT, Legal);
424       setOperationAction(ISD::SUB, VT, Legal);
425
426       // Vector instructions introduced in P8
427       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
428         setOperationAction(ISD::CTPOP, VT, Legal);
429         setOperationAction(ISD::CTLZ, VT, Legal);
430       }
431       else {
432         setOperationAction(ISD::CTPOP, VT, Expand);
433         setOperationAction(ISD::CTLZ, VT, Expand);
434       }
435
436       // We promote all shuffles to v16i8.
437       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
438       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
439
440       // We promote all non-typed operations to v4i32.
441       setOperationAction(ISD::AND   , VT, Promote);
442       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
443       setOperationAction(ISD::OR    , VT, Promote);
444       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
445       setOperationAction(ISD::XOR   , VT, Promote);
446       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
447       setOperationAction(ISD::LOAD  , VT, Promote);
448       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
449       setOperationAction(ISD::SELECT, VT, Promote);
450       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
451       setOperationAction(ISD::SELECT_CC, VT, Promote);
452       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
453       setOperationAction(ISD::STORE, VT, Promote);
454       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
455
456       // No other operations are legal.
457       setOperationAction(ISD::MUL , VT, Expand);
458       setOperationAction(ISD::SDIV, VT, Expand);
459       setOperationAction(ISD::SREM, VT, Expand);
460       setOperationAction(ISD::UDIV, VT, Expand);
461       setOperationAction(ISD::UREM, VT, Expand);
462       setOperationAction(ISD::FDIV, VT, Expand);
463       setOperationAction(ISD::FREM, VT, Expand);
464       setOperationAction(ISD::FNEG, VT, Expand);
465       setOperationAction(ISD::FSQRT, VT, Expand);
466       setOperationAction(ISD::FLOG, VT, Expand);
467       setOperationAction(ISD::FLOG10, VT, Expand);
468       setOperationAction(ISD::FLOG2, VT, Expand);
469       setOperationAction(ISD::FEXP, VT, Expand);
470       setOperationAction(ISD::FEXP2, VT, Expand);
471       setOperationAction(ISD::FSIN, VT, Expand);
472       setOperationAction(ISD::FCOS, VT, Expand);
473       setOperationAction(ISD::FABS, VT, Expand);
474       setOperationAction(ISD::FPOWI, VT, Expand);
475       setOperationAction(ISD::FFLOOR, VT, Expand);
476       setOperationAction(ISD::FCEIL,  VT, Expand);
477       setOperationAction(ISD::FTRUNC, VT, Expand);
478       setOperationAction(ISD::FRINT,  VT, Expand);
479       setOperationAction(ISD::FNEARBYINT, VT, Expand);
480       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
481       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
482       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
483       setOperationAction(ISD::MULHU, VT, Expand);
484       setOperationAction(ISD::MULHS, VT, Expand);
485       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
486       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
487       setOperationAction(ISD::UDIVREM, VT, Expand);
488       setOperationAction(ISD::SDIVREM, VT, Expand);
489       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
490       setOperationAction(ISD::FPOW, VT, Expand);
491       setOperationAction(ISD::BSWAP, VT, Expand);
492       setOperationAction(ISD::CTTZ, VT, Expand);
493       setOperationAction(ISD::VSELECT, VT, Expand);
494       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
495       setOperationAction(ISD::ROTL, VT, Expand);
496       setOperationAction(ISD::ROTR, VT, Expand);
497
498       for (MVT InnerVT : MVT::vector_valuetypes()) {
499         setTruncStoreAction(VT, InnerVT, Expand);
500         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
501         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
502         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
503       }
504     }
505
506     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
507     // with merges, splats, etc.
508     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
509
510     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
511     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
512     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
513     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
514     setOperationAction(ISD::SELECT, MVT::v4i32,
515                        Subtarget.useCRBits() ? Legal : Expand);
516     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
517     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
518     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
519     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
520     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
521     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
524     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
525
526     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
527     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
528     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
529     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
530
531     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
532     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
533
534     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
535       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
536       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
537     }
538
539     if (Subtarget.hasP8Altivec())
540       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
541     else
542       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
543
544     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
545     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
546
547     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
548     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
549
550     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
551     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
552     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
553     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
554
555     // Altivec does not contain unordered floating-point compare instructions
556     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
557     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
558     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
559     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
560
561     if (Subtarget.hasVSX()) {
562       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
563       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
564       if (Subtarget.hasP8Vector()) {
565         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
566         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
567       }
568       if (Subtarget.hasDirectMove() && isPPC64) {
569         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
570         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
571         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
572         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
573         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
574         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
575         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
576         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
577       }
578       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
579
580       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
581       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
582       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
583       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
584       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
585
586       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
587
588       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
589       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
590
591       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
592       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
593
594       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
595       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
596       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
597       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
598       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
599
600       // Share the Altivec comparison restrictions.
601       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
602       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
603       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
604       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
605
606       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
607       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
608
609       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
610
611       if (Subtarget.hasP8Vector())
612         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
613
614       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
615
616       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
617       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
618       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
619
620       if (Subtarget.hasP8Altivec()) {
621         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
622         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
623         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
624
625         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
626       }
627       else {
628         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
629         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
630         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
631
632         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
633
634         // VSX v2i64 only supports non-arithmetic operations.
635         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
636         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
637       }
638
639       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
640       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
641       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
642       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
643
644       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
645
646       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
647       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
648       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
649       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
650
651       // Vector operation legalization checks the result type of
652       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
653       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
654       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
655       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
656       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
657
658       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
659       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
660       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
661       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
662
663       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
664     }
665
666     if (Subtarget.hasP8Altivec()) {
667       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
668       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
669     }
670
671     if (Subtarget.hasP9Vector()) {
672       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
673       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
674     }
675   }
676
677   if (Subtarget.hasQPX()) {
678     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
679     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
680     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
681     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
682
683     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
684     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
685
686     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
687     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
688
689     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
690     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
691
692     if (!Subtarget.useCRBits())
693       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
694     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
695
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
697     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
698     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
699     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
701     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
702     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
703
704     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
705     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
706
707     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
708     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
709     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
710
711     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
712     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
713     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
714     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
715     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
716     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
717     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
718     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
719     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
720     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
721     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
722
723     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
724     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
725
726     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
727     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
728
729     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
730
731     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
732     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
733     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
734     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
735
736     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
737     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
738
739     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
740     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
741
742     if (!Subtarget.useCRBits())
743       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
744     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
745
746     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
747     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
748     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
749     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
750     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
751     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
752     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
753
754     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
755     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
756
757     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
758     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
759     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
760     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
761     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
762     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
763     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
764     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
765     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
766     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
767     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
768
769     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
770     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
771
772     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
773     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
774
775     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
776
777     setOperationAction(ISD::AND , MVT::v4i1, Legal);
778     setOperationAction(ISD::OR , MVT::v4i1, Legal);
779     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
780
781     if (!Subtarget.useCRBits())
782       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
783     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
784
785     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
786     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
787
788     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
789     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
790     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
791     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
792     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
793     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
794     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
795
796     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
797     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
798
799     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
800
801     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
802     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
803     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
804     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
805
806     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
807     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
808     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
809     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
810
811     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
812     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
813
814     // These need to set FE_INEXACT, and so cannot be vectorized here.
815     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
816     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
817
818     if (TM.Options.UnsafeFPMath) {
819       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
820       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
821
822       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
823       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
824     } else {
825       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
826       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
827
828       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
829       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
830     }
831   }
832
833   if (Subtarget.has64BitSupport())
834     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
835
836   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
837
838   if (!isPPC64) {
839     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
840     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
841   }
842
843   setBooleanContents(ZeroOrOneBooleanContent);
844
845   if (Subtarget.hasAltivec()) {
846     // Altivec instructions set fields to all zeros or all ones.
847     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
848   }
849
850   if (!isPPC64) {
851     // These libcalls are not available in 32-bit.
852     setLibcallName(RTLIB::SHL_I128, nullptr);
853     setLibcallName(RTLIB::SRL_I128, nullptr);
854     setLibcallName(RTLIB::SRA_I128, nullptr);
855   }
856
857   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
858
859   // We have target-specific dag combine patterns for the following nodes:
860   setTargetDAGCombine(ISD::SINT_TO_FP);
861   setTargetDAGCombine(ISD::BUILD_VECTOR);
862   if (Subtarget.hasFPCVT())
863     setTargetDAGCombine(ISD::UINT_TO_FP);
864   setTargetDAGCombine(ISD::LOAD);
865   setTargetDAGCombine(ISD::STORE);
866   setTargetDAGCombine(ISD::BR_CC);
867   if (Subtarget.useCRBits())
868     setTargetDAGCombine(ISD::BRCOND);
869   setTargetDAGCombine(ISD::BSWAP);
870   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
871   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
872   setTargetDAGCombine(ISD::INTRINSIC_VOID);
873
874   setTargetDAGCombine(ISD::SIGN_EXTEND);
875   setTargetDAGCombine(ISD::ZERO_EXTEND);
876   setTargetDAGCombine(ISD::ANY_EXTEND);
877
878   if (Subtarget.useCRBits()) {
879     setTargetDAGCombine(ISD::TRUNCATE);
880     setTargetDAGCombine(ISD::SETCC);
881     setTargetDAGCombine(ISD::SELECT_CC);
882   }
883
884   // Use reciprocal estimates.
885   if (TM.Options.UnsafeFPMath) {
886     setTargetDAGCombine(ISD::FDIV);
887     setTargetDAGCombine(ISD::FSQRT);
888   }
889
890   // Darwin long double math library functions have $LDBL128 appended.
891   if (Subtarget.isDarwin()) {
892     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
893     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
894     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
895     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
896     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
897     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
898     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
899     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
900     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
901     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
902   }
903
904   // With 32 condition bits, we don't need to sink (and duplicate) compares
905   // aggressively in CodeGenPrep.
906   if (Subtarget.useCRBits()) {
907     setHasMultipleConditionRegisters();
908     setJumpIsExpensive();
909   }
910
911   setMinFunctionAlignment(2);
912   if (Subtarget.isDarwin())
913     setPrefFunctionAlignment(4);
914
915   switch (Subtarget.getDarwinDirective()) {
916   default: break;
917   case PPC::DIR_970:
918   case PPC::DIR_A2:
919   case PPC::DIR_E500mc:
920   case PPC::DIR_E5500:
921   case PPC::DIR_PWR4:
922   case PPC::DIR_PWR5:
923   case PPC::DIR_PWR5X:
924   case PPC::DIR_PWR6:
925   case PPC::DIR_PWR6X:
926   case PPC::DIR_PWR7:
927   case PPC::DIR_PWR8:
928   case PPC::DIR_PWR9:
929     setPrefFunctionAlignment(4);
930     setPrefLoopAlignment(4);
931     break;
932   }
933
934   if (Subtarget.enableMachineScheduler())
935     setSchedulingPreference(Sched::Source);
936   else
937     setSchedulingPreference(Sched::Hybrid);
938
939   computeRegisterProperties(STI.getRegisterInfo());
940
941   // The Freescale cores do better with aggressive inlining of memcpy and
942   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
943   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
944       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
945     MaxStoresPerMemset = 32;
946     MaxStoresPerMemsetOptSize = 16;
947     MaxStoresPerMemcpy = 32;
948     MaxStoresPerMemcpyOptSize = 8;
949     MaxStoresPerMemmove = 32;
950     MaxStoresPerMemmoveOptSize = 8;
951   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
952     // The A2 also benefits from (very) aggressive inlining of memcpy and
953     // friends. The overhead of a the function call, even when warm, can be
954     // over one hundred cycles.
955     MaxStoresPerMemset = 128;
956     MaxStoresPerMemcpy = 128;
957     MaxStoresPerMemmove = 128;
958   }
959 }
960
961 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
962 /// the desired ByVal argument alignment.
963 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
964                              unsigned MaxMaxAlign) {
965   if (MaxAlign == MaxMaxAlign)
966     return;
967   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
968     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
969       MaxAlign = 32;
970     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
971       MaxAlign = 16;
972   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
973     unsigned EltAlign = 0;
974     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
975     if (EltAlign > MaxAlign)
976       MaxAlign = EltAlign;
977   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
978     for (auto *EltTy : STy->elements()) {
979       unsigned EltAlign = 0;
980       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
981       if (EltAlign > MaxAlign)
982         MaxAlign = EltAlign;
983       if (MaxAlign == MaxMaxAlign)
984         break;
985     }
986   }
987 }
988
989 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
990 /// function arguments in the caller parameter area.
991 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
992                                                   const DataLayout &DL) const {
993   // Darwin passes everything on 4 byte boundary.
994   if (Subtarget.isDarwin())
995     return 4;
996
997   // 16byte and wider vectors are passed on 16byte boundary.
998   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
999   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1000   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1001     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1002   return Align;
1003 }
1004
1005 bool PPCTargetLowering::useSoftFloat() const {
1006   return Subtarget.useSoftFloat();
1007 }
1008
1009 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1010   switch ((PPCISD::NodeType)Opcode) {
1011   case PPCISD::FIRST_NUMBER:    break;
1012   case PPCISD::FSEL:            return "PPCISD::FSEL";
1013   case PPCISD::FCFID:           return "PPCISD::FCFID";
1014   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1015   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1016   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1017   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1018   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1019   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1020   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1021   case PPCISD::FRE:             return "PPCISD::FRE";
1022   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1023   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1024   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1025   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1026   case PPCISD::VPERM:           return "PPCISD::VPERM";
1027   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1028   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1029   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1030   case PPCISD::CMPB:            return "PPCISD::CMPB";
1031   case PPCISD::Hi:              return "PPCISD::Hi";
1032   case PPCISD::Lo:              return "PPCISD::Lo";
1033   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1034   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1035   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1036   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1037   case PPCISD::SRL:             return "PPCISD::SRL";
1038   case PPCISD::SRA:             return "PPCISD::SRA";
1039   case PPCISD::SHL:             return "PPCISD::SHL";
1040   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1041   case PPCISD::CALL:            return "PPCISD::CALL";
1042   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1043   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1044   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1045   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1046   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1047   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1048   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1049   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1050   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1051   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1052   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1053   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1054   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1055   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1056   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1057   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1058   case PPCISD::VCMP:            return "PPCISD::VCMP";
1059   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1060   case PPCISD::LBRX:            return "PPCISD::LBRX";
1061   case PPCISD::STBRX:           return "PPCISD::STBRX";
1062   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1063   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1064   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1065   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1066   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1067   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1068   case PPCISD::BDZ:             return "PPCISD::BDZ";
1069   case PPCISD::MFFS:            return "PPCISD::MFFS";
1070   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1071   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1072   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1073   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1074   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1075   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1076   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1077   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1078   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1079   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1080   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1081   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1082   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1083   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1084   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1085   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1086   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1087   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1088   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1089   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1090   case PPCISD::SC:              return "PPCISD::SC";
1091   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1092   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1093   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1094   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1095   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1096   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1097   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1098   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1099   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1100   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1101   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1102   }
1103   return nullptr;
1104 }
1105
1106 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1107                                           EVT VT) const {
1108   if (!VT.isVector())
1109     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1110
1111   if (Subtarget.hasQPX())
1112     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1113
1114   return VT.changeVectorElementTypeToInteger();
1115 }
1116
1117 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1118   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1119   return true;
1120 }
1121
1122 //===----------------------------------------------------------------------===//
1123 // Node matching predicates, for use by the tblgen matching code.
1124 //===----------------------------------------------------------------------===//
1125
1126 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1127 static bool isFloatingPointZero(SDValue Op) {
1128   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1129     return CFP->getValueAPF().isZero();
1130   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1131     // Maybe this has already been legalized into the constant pool?
1132     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1133       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1134         return CFP->getValueAPF().isZero();
1135   }
1136   return false;
1137 }
1138
1139 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1140 /// true if Op is undef or if it matches the specified value.
1141 static bool isConstantOrUndef(int Op, int Val) {
1142   return Op < 0 || Op == Val;
1143 }
1144
1145 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1146 /// VPKUHUM instruction.
1147 /// The ShuffleKind distinguishes between big-endian operations with
1148 /// two different inputs (0), either-endian operations with two identical
1149 /// inputs (1), and little-endian operations with two different inputs (2).
1150 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1151 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1152                                SelectionDAG &DAG) {
1153   bool IsLE = DAG.getDataLayout().isLittleEndian();
1154   if (ShuffleKind == 0) {
1155     if (IsLE)
1156       return false;
1157     for (unsigned i = 0; i != 16; ++i)
1158       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1159         return false;
1160   } else if (ShuffleKind == 2) {
1161     if (!IsLE)
1162       return false;
1163     for (unsigned i = 0; i != 16; ++i)
1164       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1165         return false;
1166   } else if (ShuffleKind == 1) {
1167     unsigned j = IsLE ? 0 : 1;
1168     for (unsigned i = 0; i != 8; ++i)
1169       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1170           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1171         return false;
1172   }
1173   return true;
1174 }
1175
1176 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1177 /// VPKUWUM instruction.
1178 /// The ShuffleKind distinguishes between big-endian operations with
1179 /// two different inputs (0), either-endian operations with two identical
1180 /// inputs (1), and little-endian operations with two different inputs (2).
1181 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1182 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1183                                SelectionDAG &DAG) {
1184   bool IsLE = DAG.getDataLayout().isLittleEndian();
1185   if (ShuffleKind == 0) {
1186     if (IsLE)
1187       return false;
1188     for (unsigned i = 0; i != 16; i += 2)
1189       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1190           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1191         return false;
1192   } else if (ShuffleKind == 2) {
1193     if (!IsLE)
1194       return false;
1195     for (unsigned i = 0; i != 16; i += 2)
1196       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1197           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1198         return false;
1199   } else if (ShuffleKind == 1) {
1200     unsigned j = IsLE ? 0 : 2;
1201     for (unsigned i = 0; i != 8; i += 2)
1202       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1203           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1204           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1205           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1206         return false;
1207   }
1208   return true;
1209 }
1210
1211 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1212 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1213 /// current subtarget.
1214 ///
1215 /// The ShuffleKind distinguishes between big-endian operations with
1216 /// two different inputs (0), either-endian operations with two identical
1217 /// inputs (1), and little-endian operations with two different inputs (2).
1218 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1220                                SelectionDAG &DAG) {
1221   const PPCSubtarget& Subtarget =
1222     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1223   if (!Subtarget.hasP8Vector())
1224     return false;
1225
1226   bool IsLE = DAG.getDataLayout().isLittleEndian();
1227   if (ShuffleKind == 0) {
1228     if (IsLE)
1229       return false;
1230     for (unsigned i = 0; i != 16; i += 4)
1231       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1232           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1233           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1234           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1235         return false;
1236   } else if (ShuffleKind == 2) {
1237     if (!IsLE)
1238       return false;
1239     for (unsigned i = 0; i != 16; i += 4)
1240       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1241           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1242           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1243           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1244         return false;
1245   } else if (ShuffleKind == 1) {
1246     unsigned j = IsLE ? 0 : 4;
1247     for (unsigned i = 0; i != 8; i += 4)
1248       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1249           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1250           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1251           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1252           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1253           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1254           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1255           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1256         return false;
1257   }
1258   return true;
1259 }
1260
1261 /// isVMerge - Common function, used to match vmrg* shuffles.
1262 ///
1263 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1264                      unsigned LHSStart, unsigned RHSStart) {
1265   if (N->getValueType(0) != MVT::v16i8)
1266     return false;
1267   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1268          "Unsupported merge size!");
1269
1270   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1271     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1272       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1273                              LHSStart+j+i*UnitSize) ||
1274           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1275                              RHSStart+j+i*UnitSize))
1276         return false;
1277     }
1278   return true;
1279 }
1280
1281 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1282 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1283 /// The ShuffleKind distinguishes between big-endian merges with two
1284 /// different inputs (0), either-endian merges with two identical inputs (1),
1285 /// and little-endian merges with two different inputs (2).  For the latter,
1286 /// the input operands are swapped (see PPCInstrAltivec.td).
1287 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1288                              unsigned ShuffleKind, SelectionDAG &DAG) {
1289   if (DAG.getDataLayout().isLittleEndian()) {
1290     if (ShuffleKind == 1) // unary
1291       return isVMerge(N, UnitSize, 0, 0);
1292     else if (ShuffleKind == 2) // swapped
1293       return isVMerge(N, UnitSize, 0, 16);
1294     else
1295       return false;
1296   } else {
1297     if (ShuffleKind == 1) // unary
1298       return isVMerge(N, UnitSize, 8, 8);
1299     else if (ShuffleKind == 0) // normal
1300       return isVMerge(N, UnitSize, 8, 24);
1301     else
1302       return false;
1303   }
1304 }
1305
1306 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1307 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1308 /// The ShuffleKind distinguishes between big-endian merges with two
1309 /// different inputs (0), either-endian merges with two identical inputs (1),
1310 /// and little-endian merges with two different inputs (2).  For the latter,
1311 /// the input operands are swapped (see PPCInstrAltivec.td).
1312 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1313                              unsigned ShuffleKind, SelectionDAG &DAG) {
1314   if (DAG.getDataLayout().isLittleEndian()) {
1315     if (ShuffleKind == 1) // unary
1316       return isVMerge(N, UnitSize, 8, 8);
1317     else if (ShuffleKind == 2) // swapped
1318       return isVMerge(N, UnitSize, 8, 24);
1319     else
1320       return false;
1321   } else {
1322     if (ShuffleKind == 1) // unary
1323       return isVMerge(N, UnitSize, 0, 0);
1324     else if (ShuffleKind == 0) // normal
1325       return isVMerge(N, UnitSize, 0, 16);
1326     else
1327       return false;
1328   }
1329 }
1330
1331 /**
1332  * \brief Common function used to match vmrgew and vmrgow shuffles
1333  *
1334  * The indexOffset determines whether to look for even or odd words in
1335  * the shuffle mask. This is based on the of the endianness of the target
1336  * machine.
1337  *   - Little Endian:
1338  *     - Use offset of 0 to check for odd elements
1339  *     - Use offset of 4 to check for even elements
1340  *   - Big Endian:
1341  *     - Use offset of 0 to check for even elements
1342  *     - Use offset of 4 to check for odd elements
1343  * A detailed description of the vector element ordering for little endian and
1344  * big endian can be found at
1345  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1346  * Targeting your applications - what little endian and big endian IBM XL C/C++
1347  * compiler differences mean to you
1348  *
1349  * The mask to the shuffle vector instruction specifies the indices of the
1350  * elements from the two input vectors to place in the result. The elements are
1351  * numbered in array-access order, starting with the first vector. These vectors
1352  * are always of type v16i8, thus each vector will contain 16 elements of size
1353  * 8. More info on the shuffle vector can be found in the
1354  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1355  * Language Reference.
1356  *
1357  * The RHSStartValue indicates whether the same input vectors are used (unary)
1358  * or two different input vectors are used, based on the following:
1359  *   - If the instruction uses the same vector for both inputs, the range of the
1360  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1361  *     be 0.
1362  *   - If the instruction has two different vectors then the range of the
1363  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1364  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1365  *     to 31 specify elements in the second vector).
1366  *
1367  * \param[in] N The shuffle vector SD Node to analyze
1368  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1369  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1370  * vector to the shuffle_vector instruction
1371  * \return true iff this shuffle vector represents an even or odd word merge
1372  */
1373 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1374                      unsigned RHSStartValue) {
1375   if (N->getValueType(0) != MVT::v16i8)
1376     return false;
1377
1378   for (unsigned i = 0; i < 2; ++i)
1379     for (unsigned j = 0; j < 4; ++j)
1380       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1381                              i*RHSStartValue+j+IndexOffset) ||
1382           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1383                              i*RHSStartValue+j+IndexOffset+8))
1384         return false;
1385   return true;
1386 }
1387
1388 /**
1389  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1390  * vmrgow instructions.
1391  *
1392  * \param[in] N The shuffle vector SD Node to analyze
1393  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1394  * \param[in] ShuffleKind Identify the type of merge:
1395  *   - 0 = big-endian merge with two different inputs;
1396  *   - 1 = either-endian merge with two identical inputs;
1397  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1398  *     little-endian merges).
1399  * \param[in] DAG The current SelectionDAG
1400  * \return true iff this shuffle mask
1401  */
1402 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1403                               unsigned ShuffleKind, SelectionDAG &DAG) {
1404   if (DAG.getDataLayout().isLittleEndian()) {
1405     unsigned indexOffset = CheckEven ? 4 : 0;
1406     if (ShuffleKind == 1) // Unary
1407       return isVMerge(N, indexOffset, 0);
1408     else if (ShuffleKind == 2) // swapped
1409       return isVMerge(N, indexOffset, 16);
1410     else
1411       return false;
1412   }
1413   else {
1414     unsigned indexOffset = CheckEven ? 0 : 4;
1415     if (ShuffleKind == 1) // Unary
1416       return isVMerge(N, indexOffset, 0);
1417     else if (ShuffleKind == 0) // Normal
1418       return isVMerge(N, indexOffset, 16);
1419     else
1420       return false;
1421   }
1422   return false;
1423 }
1424
1425 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1426 /// amount, otherwise return -1.
1427 /// The ShuffleKind distinguishes between big-endian operations with two
1428 /// different inputs (0), either-endian operations with two identical inputs
1429 /// (1), and little-endian operations with two different inputs (2).  For the
1430 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1431 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1432                              SelectionDAG &DAG) {
1433   if (N->getValueType(0) != MVT::v16i8)
1434     return -1;
1435
1436   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1437
1438   // Find the first non-undef value in the shuffle mask.
1439   unsigned i;
1440   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1441     /*search*/;
1442
1443   if (i == 16) return -1;  // all undef.
1444
1445   // Otherwise, check to see if the rest of the elements are consecutively
1446   // numbered from this value.
1447   unsigned ShiftAmt = SVOp->getMaskElt(i);
1448   if (ShiftAmt < i) return -1;
1449
1450   ShiftAmt -= i;
1451   bool isLE = DAG.getDataLayout().isLittleEndian();
1452
1453   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1454     // Check the rest of the elements to see if they are consecutive.
1455     for (++i; i != 16; ++i)
1456       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1457         return -1;
1458   } else if (ShuffleKind == 1) {
1459     // Check the rest of the elements to see if they are consecutive.
1460     for (++i; i != 16; ++i)
1461       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1462         return -1;
1463   } else
1464     return -1;
1465
1466   if (isLE)
1467     ShiftAmt = 16 - ShiftAmt;
1468
1469   return ShiftAmt;
1470 }
1471
1472 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1473 /// specifies a splat of a single element that is suitable for input to
1474 /// VSPLTB/VSPLTH/VSPLTW.
1475 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1476   assert(N->getValueType(0) == MVT::v16i8 &&
1477          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1478
1479   // The consecutive indices need to specify an element, not part of two
1480   // different elements.  So abandon ship early if this isn't the case.
1481   if (N->getMaskElt(0) % EltSize != 0)
1482     return false;
1483
1484   // This is a splat operation if each element of the permute is the same, and
1485   // if the value doesn't reference the second vector.
1486   unsigned ElementBase = N->getMaskElt(0);
1487
1488   // FIXME: Handle UNDEF elements too!
1489   if (ElementBase >= 16)
1490     return false;
1491
1492   // Check that the indices are consecutive, in the case of a multi-byte element
1493   // splatted with a v16i8 mask.
1494   for (unsigned i = 1; i != EltSize; ++i)
1495     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1496       return false;
1497
1498   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1499     if (N->getMaskElt(i) < 0) continue;
1500     for (unsigned j = 0; j != EltSize; ++j)
1501       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1502         return false;
1503   }
1504   return true;
1505 }
1506
1507 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1508                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1509
1510   // Check that the mask is shuffling words
1511   for (unsigned i = 0; i < 4; ++i) {
1512     unsigned B0 = N->getMaskElt(i*4);
1513     unsigned B1 = N->getMaskElt(i*4+1);
1514     unsigned B2 = N->getMaskElt(i*4+2);
1515     unsigned B3 = N->getMaskElt(i*4+3);
1516     if (B0 % 4)
1517       return false;
1518     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1519       return false;
1520   }
1521
1522   // Now we look at mask elements 0,4,8,12
1523   unsigned M0 = N->getMaskElt(0) / 4;
1524   unsigned M1 = N->getMaskElt(4) / 4;
1525   unsigned M2 = N->getMaskElt(8) / 4;
1526   unsigned M3 = N->getMaskElt(12) / 4;
1527   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1528   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1529
1530   // Below, let H and L be arbitrary elements of the shuffle mask
1531   // where H is in the range [4,7] and L is in the range [0,3].
1532   // H, 1, 2, 3 or L, 5, 6, 7
1533   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1534       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1535     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1536     InsertAtByte = IsLE ? 12 : 0;
1537     Swap = M0 < 4;
1538     return true;
1539   }
1540   // 0, H, 2, 3 or 4, L, 6, 7
1541   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1542       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1543     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1544     InsertAtByte = IsLE ? 8 : 4;
1545     Swap = M1 < 4;
1546     return true;
1547   }
1548   // 0, 1, H, 3 or 4, 5, L, 7
1549   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1550       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1551     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1552     InsertAtByte = IsLE ? 4 : 8;
1553     Swap = M2 < 4;
1554     return true;
1555   }
1556   // 0, 1, 2, H or 4, 5, 6, L
1557   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1558       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1559     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1560     InsertAtByte = IsLE ? 0 : 12;
1561     Swap = M3 < 4;
1562     return true;
1563   }
1564
1565   // If both vector operands for the shuffle are the same vector, the mask will
1566   // contain only elements from the first one and the second one will be undef.
1567   if (N->getOperand(1).isUndef()) {
1568     ShiftElts = 0;
1569     Swap = true;
1570     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1571     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1572       InsertAtByte = IsLE ? 12 : 0;
1573       return true;
1574     }
1575     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1576       InsertAtByte = IsLE ? 8 : 4;
1577       return true;
1578     }
1579     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1580       InsertAtByte = IsLE ? 4 : 8;
1581       return true;
1582     }
1583     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1584       InsertAtByte = IsLE ? 0 : 12;
1585       return true;
1586     }
1587   }
1588
1589   return false;
1590 }
1591
1592 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1593 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1594 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1595                                 SelectionDAG &DAG) {
1596   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1597   assert(isSplatShuffleMask(SVOp, EltSize));
1598   if (DAG.getDataLayout().isLittleEndian())
1599     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1600   else
1601     return SVOp->getMaskElt(0) / EltSize;
1602 }
1603
1604 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1605 /// by using a vspltis[bhw] instruction of the specified element size, return
1606 /// the constant being splatted.  The ByteSize field indicates the number of
1607 /// bytes of each element [124] -> [bhw].
1608 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1609   SDValue OpVal(nullptr, 0);
1610
1611   // If ByteSize of the splat is bigger than the element size of the
1612   // build_vector, then we have a case where we are checking for a splat where
1613   // multiple elements of the buildvector are folded together into a single
1614   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1615   unsigned EltSize = 16/N->getNumOperands();
1616   if (EltSize < ByteSize) {
1617     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1618     SDValue UniquedVals[4];
1619     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1620
1621     // See if all of the elements in the buildvector agree across.
1622     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1623       if (N->getOperand(i).isUndef()) continue;
1624       // If the element isn't a constant, bail fully out.
1625       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1626
1627
1628       if (!UniquedVals[i&(Multiple-1)].getNode())
1629         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1630       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1631         return SDValue();  // no match.
1632     }
1633
1634     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1635     // either constant or undef values that are identical for each chunk.  See
1636     // if these chunks can form into a larger vspltis*.
1637
1638     // Check to see if all of the leading entries are either 0 or -1.  If
1639     // neither, then this won't fit into the immediate field.
1640     bool LeadingZero = true;
1641     bool LeadingOnes = true;
1642     for (unsigned i = 0; i != Multiple-1; ++i) {
1643       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1644
1645       LeadingZero &= isNullConstant(UniquedVals[i]);
1646       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1647     }
1648     // Finally, check the least significant entry.
1649     if (LeadingZero) {
1650       if (!UniquedVals[Multiple-1].getNode())
1651         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1652       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1653       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1654         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1655     }
1656     if (LeadingOnes) {
1657       if (!UniquedVals[Multiple-1].getNode())
1658         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1659       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1660       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1661         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1662     }
1663
1664     return SDValue();
1665   }
1666
1667   // Check to see if this buildvec has a single non-undef value in its elements.
1668   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1669     if (N->getOperand(i).isUndef()) continue;
1670     if (!OpVal.getNode())
1671       OpVal = N->getOperand(i);
1672     else if (OpVal != N->getOperand(i))
1673       return SDValue();
1674   }
1675
1676   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1677
1678   unsigned ValSizeInBytes = EltSize;
1679   uint64_t Value = 0;
1680   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1681     Value = CN->getZExtValue();
1682   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1683     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1684     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1685   }
1686
1687   // If the splat value is larger than the element value, then we can never do
1688   // this splat.  The only case that we could fit the replicated bits into our
1689   // immediate field for would be zero, and we prefer to use vxor for it.
1690   if (ValSizeInBytes < ByteSize) return SDValue();
1691
1692   // If the element value is larger than the splat value, check if it consists
1693   // of a repeated bit pattern of size ByteSize.
1694   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1695     return SDValue();
1696
1697   // Properly sign extend the value.
1698   int MaskVal = SignExtend32(Value, ByteSize * 8);
1699
1700   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1701   if (MaskVal == 0) return SDValue();
1702
1703   // Finally, if this value fits in a 5 bit sext field, return it
1704   if (SignExtend32<5>(MaskVal) == MaskVal)
1705     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1706   return SDValue();
1707 }
1708
1709 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1710 /// amount, otherwise return -1.
1711 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1712   EVT VT = N->getValueType(0);
1713   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1714     return -1;
1715
1716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1717
1718   // Find the first non-undef value in the shuffle mask.
1719   unsigned i;
1720   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1721     /*search*/;
1722
1723   if (i == 4) return -1;  // all undef.
1724
1725   // Otherwise, check to see if the rest of the elements are consecutively
1726   // numbered from this value.
1727   unsigned ShiftAmt = SVOp->getMaskElt(i);
1728   if (ShiftAmt < i) return -1;
1729   ShiftAmt -= i;
1730
1731   // Check the rest of the elements to see if they are consecutive.
1732   for (++i; i != 4; ++i)
1733     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1734       return -1;
1735
1736   return ShiftAmt;
1737 }
1738
1739 //===----------------------------------------------------------------------===//
1740 //  Addressing Mode Selection
1741 //===----------------------------------------------------------------------===//
1742
1743 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1744 /// or 64-bit immediate, and if the value can be accurately represented as a
1745 /// sign extension from a 16-bit value.  If so, this returns true and the
1746 /// immediate.
1747 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1748   if (!isa<ConstantSDNode>(N))
1749     return false;
1750
1751   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1752   if (N->getValueType(0) == MVT::i32)
1753     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1754   else
1755     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1756 }
1757 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1758   return isIntS16Immediate(Op.getNode(), Imm);
1759 }
1760
1761 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1762 /// can be represented as an indexed [r+r] operation.  Returns false if it
1763 /// can be more efficiently represented with [r+imm].
1764 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1765                                             SDValue &Index,
1766                                             SelectionDAG &DAG) const {
1767   short imm = 0;
1768   if (N.getOpcode() == ISD::ADD) {
1769     if (isIntS16Immediate(N.getOperand(1), imm))
1770       return false;    // r+i
1771     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1772       return false;    // r+i
1773
1774     Base = N.getOperand(0);
1775     Index = N.getOperand(1);
1776     return true;
1777   } else if (N.getOpcode() == ISD::OR) {
1778     if (isIntS16Immediate(N.getOperand(1), imm))
1779       return false;    // r+i can fold it if we can.
1780
1781     // If this is an or of disjoint bitfields, we can codegen this as an add
1782     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1783     // disjoint.
1784     APInt LHSKnownZero, LHSKnownOne;
1785     APInt RHSKnownZero, RHSKnownOne;
1786     DAG.computeKnownBits(N.getOperand(0),
1787                          LHSKnownZero, LHSKnownOne);
1788
1789     if (LHSKnownZero.getBoolValue()) {
1790       DAG.computeKnownBits(N.getOperand(1),
1791                            RHSKnownZero, RHSKnownOne);
1792       // If all of the bits are known zero on the LHS or RHS, the add won't
1793       // carry.
1794       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1795         Base = N.getOperand(0);
1796         Index = N.getOperand(1);
1797         return true;
1798       }
1799     }
1800   }
1801
1802   return false;
1803 }
1804
1805 // If we happen to be doing an i64 load or store into a stack slot that has
1806 // less than a 4-byte alignment, then the frame-index elimination may need to
1807 // use an indexed load or store instruction (because the offset may not be a
1808 // multiple of 4). The extra register needed to hold the offset comes from the
1809 // register scavenger, and it is possible that the scavenger will need to use
1810 // an emergency spill slot. As a result, we need to make sure that a spill slot
1811 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1812 // stack slot.
1813 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1814   // FIXME: This does not handle the LWA case.
1815   if (VT != MVT::i64)
1816     return;
1817
1818   // NOTE: We'll exclude negative FIs here, which come from argument
1819   // lowering, because there are no known test cases triggering this problem
1820   // using packed structures (or similar). We can remove this exclusion if
1821   // we find such a test case. The reason why this is so test-case driven is
1822   // because this entire 'fixup' is only to prevent crashes (from the
1823   // register scavenger) on not-really-valid inputs. For example, if we have:
1824   //   %a = alloca i1
1825   //   %b = bitcast i1* %a to i64*
1826   //   store i64* a, i64 b
1827   // then the store should really be marked as 'align 1', but is not. If it
1828   // were marked as 'align 1' then the indexed form would have been
1829   // instruction-selected initially, and the problem this 'fixup' is preventing
1830   // won't happen regardless.
1831   if (FrameIdx < 0)
1832     return;
1833
1834   MachineFunction &MF = DAG.getMachineFunction();
1835   MachineFrameInfo *MFI = MF.getFrameInfo();
1836
1837   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1838   if (Align >= 4)
1839     return;
1840
1841   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1842   FuncInfo->setHasNonRISpills();
1843 }
1844
1845 /// Returns true if the address N can be represented by a base register plus
1846 /// a signed 16-bit displacement [r+imm], and if it is not better
1847 /// represented as reg+reg.  If Aligned is true, only accept displacements
1848 /// suitable for STD and friends, i.e. multiples of 4.
1849 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1850                                             SDValue &Base,
1851                                             SelectionDAG &DAG,
1852                                             bool Aligned) const {
1853   // FIXME dl should come from parent load or store, not from address
1854   SDLoc dl(N);
1855   // If this can be more profitably realized as r+r, fail.
1856   if (SelectAddressRegReg(N, Disp, Base, DAG))
1857     return false;
1858
1859   if (N.getOpcode() == ISD::ADD) {
1860     short imm = 0;
1861     if (isIntS16Immediate(N.getOperand(1), imm) &&
1862         (!Aligned || (imm & 3) == 0)) {
1863       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1864       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1865         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1866         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1867       } else {
1868         Base = N.getOperand(0);
1869       }
1870       return true; // [r+i]
1871     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1872       // Match LOAD (ADD (X, Lo(G))).
1873       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1874              && "Cannot handle constant offsets yet!");
1875       Disp = N.getOperand(1).getOperand(0);  // The global address.
1876       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1877              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1878              Disp.getOpcode() == ISD::TargetConstantPool ||
1879              Disp.getOpcode() == ISD::TargetJumpTable);
1880       Base = N.getOperand(0);
1881       return true;  // [&g+r]
1882     }
1883   } else if (N.getOpcode() == ISD::OR) {
1884     short imm = 0;
1885     if (isIntS16Immediate(N.getOperand(1), imm) &&
1886         (!Aligned || (imm & 3) == 0)) {
1887       // If this is an or of disjoint bitfields, we can codegen this as an add
1888       // (for better address arithmetic) if the LHS and RHS of the OR are
1889       // provably disjoint.
1890       APInt LHSKnownZero, LHSKnownOne;
1891       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1892
1893       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1894         // If all of the bits are known zero on the LHS or RHS, the add won't
1895         // carry.
1896         if (FrameIndexSDNode *FI =
1897               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1898           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1899           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1900         } else {
1901           Base = N.getOperand(0);
1902         }
1903         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1904         return true;
1905       }
1906     }
1907   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1908     // Loading from a constant address.
1909
1910     // If this address fits entirely in a 16-bit sext immediate field, codegen
1911     // this as "d, 0"
1912     short Imm;
1913     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1914       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1915       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1916                              CN->getValueType(0));
1917       return true;
1918     }
1919
1920     // Handle 32-bit sext immediates with LIS + addr mode.
1921     if ((CN->getValueType(0) == MVT::i32 ||
1922          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1923         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1924       int Addr = (int)CN->getZExtValue();
1925
1926       // Otherwise, break this down into an LIS + disp.
1927       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1928
1929       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1930                                    MVT::i32);
1931       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1932       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1933       return true;
1934     }
1935   }
1936
1937   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1938   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1939     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1940     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1941   } else
1942     Base = N;
1943   return true;      // [r+0]
1944 }
1945
1946 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1947 /// represented as an indexed [r+r] operation.
1948 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1949                                                 SDValue &Index,
1950                                                 SelectionDAG &DAG) const {
1951   // Check to see if we can easily represent this as an [r+r] address.  This
1952   // will fail if it thinks that the address is more profitably represented as
1953   // reg+imm, e.g. where imm = 0.
1954   if (SelectAddressRegReg(N, Base, Index, DAG))
1955     return true;
1956
1957   // If the operand is an addition, always emit this as [r+r], since this is
1958   // better (for code size, and execution, as the memop does the add for free)
1959   // than emitting an explicit add.
1960   if (N.getOpcode() == ISD::ADD) {
1961     Base = N.getOperand(0);
1962     Index = N.getOperand(1);
1963     return true;
1964   }
1965
1966   // Otherwise, do it the hard way, using R0 as the base register.
1967   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1968                          N.getValueType());
1969   Index = N;
1970   return true;
1971 }
1972
1973 /// getPreIndexedAddressParts - returns true by value, base pointer and
1974 /// offset pointer and addressing mode by reference if the node's address
1975 /// can be legally represented as pre-indexed load / store address.
1976 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1977                                                   SDValue &Offset,
1978                                                   ISD::MemIndexedMode &AM,
1979                                                   SelectionDAG &DAG) const {
1980   if (DisablePPCPreinc) return false;
1981
1982   bool isLoad = true;
1983   SDValue Ptr;
1984   EVT VT;
1985   unsigned Alignment;
1986   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1987     Ptr = LD->getBasePtr();
1988     VT = LD->getMemoryVT();
1989     Alignment = LD->getAlignment();
1990   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1991     Ptr = ST->getBasePtr();
1992     VT  = ST->getMemoryVT();
1993     Alignment = ST->getAlignment();
1994     isLoad = false;
1995   } else
1996     return false;
1997
1998   // PowerPC doesn't have preinc load/store instructions for vectors (except
1999   // for QPX, which does have preinc r+r forms).
2000   if (VT.isVector()) {
2001     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2002       return false;
2003     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2004       AM = ISD::PRE_INC;
2005       return true;
2006     }
2007   }
2008
2009   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2010
2011     // Common code will reject creating a pre-inc form if the base pointer
2012     // is a frame index, or if N is a store and the base pointer is either
2013     // the same as or a predecessor of the value being stored.  Check for
2014     // those situations here, and try with swapped Base/Offset instead.
2015     bool Swap = false;
2016
2017     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2018       Swap = true;
2019     else if (!isLoad) {
2020       SDValue Val = cast<StoreSDNode>(N)->getValue();
2021       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2022         Swap = true;
2023     }
2024
2025     if (Swap)
2026       std::swap(Base, Offset);
2027
2028     AM = ISD::PRE_INC;
2029     return true;
2030   }
2031
2032   // LDU/STU can only handle immediates that are a multiple of 4.
2033   if (VT != MVT::i64) {
2034     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2035       return false;
2036   } else {
2037     // LDU/STU need an address with at least 4-byte alignment.
2038     if (Alignment < 4)
2039       return false;
2040
2041     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2042       return false;
2043   }
2044
2045   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2046     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2047     // sext i32 to i64 when addr mode is r+i.
2048     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2049         LD->getExtensionType() == ISD::SEXTLOAD &&
2050         isa<ConstantSDNode>(Offset))
2051       return false;
2052   }
2053
2054   AM = ISD::PRE_INC;
2055   return true;
2056 }
2057
2058 //===----------------------------------------------------------------------===//
2059 //  LowerOperation implementation
2060 //===----------------------------------------------------------------------===//
2061
2062 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2063 /// and LoOpFlags to the target MO flags.
2064 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2065                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2066                                const GlobalValue *GV = nullptr) {
2067   HiOpFlags = PPCII::MO_HA;
2068   LoOpFlags = PPCII::MO_LO;
2069
2070   // Don't use the pic base if not in PIC relocation model.
2071   if (IsPIC) {
2072     HiOpFlags |= PPCII::MO_PIC_FLAG;
2073     LoOpFlags |= PPCII::MO_PIC_FLAG;
2074   }
2075
2076   // If this is a reference to a global value that requires a non-lazy-ptr, make
2077   // sure that instruction lowering adds it.
2078   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2079     HiOpFlags |= PPCII::MO_NLP_FLAG;
2080     LoOpFlags |= PPCII::MO_NLP_FLAG;
2081
2082     if (GV->hasHiddenVisibility()) {
2083       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2084       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2085     }
2086   }
2087 }
2088
2089 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2090                              SelectionDAG &DAG) {
2091   SDLoc DL(HiPart);
2092   EVT PtrVT = HiPart.getValueType();
2093   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2094
2095   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2096   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2097
2098   // With PIC, the first instruction is actually "GR+hi(&G)".
2099   if (isPIC)
2100     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2101                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2102
2103   // Generate non-pic code that has direct accesses to the constant pool.
2104   // The address of the global is just (hi(&g)+lo(&g)).
2105   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2106 }
2107
2108 static void setUsesTOCBasePtr(MachineFunction &MF) {
2109   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2110   FuncInfo->setUsesTOCBasePtr();
2111 }
2112
2113 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2114   setUsesTOCBasePtr(DAG.getMachineFunction());
2115 }
2116
2117 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2118                            SDValue GA) {
2119   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2120   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2121                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2122
2123   SDValue Ops[] = { GA, Reg };
2124   return DAG.getMemIntrinsicNode(
2125       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2126       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2127       false, 0);
2128 }
2129
2130 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2131                                              SelectionDAG &DAG) const {
2132   EVT PtrVT = Op.getValueType();
2133   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2134   const Constant *C = CP->getConstVal();
2135
2136   // 64-bit SVR4 ABI code is always position-independent.
2137   // The actual address of the GlobalValue is stored in the TOC.
2138   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2139     setUsesTOCBasePtr(DAG);
2140     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2141     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2142   }
2143
2144   unsigned MOHiFlag, MOLoFlag;
2145   bool IsPIC = isPositionIndependent();
2146   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2147
2148   if (IsPIC && Subtarget.isSVR4ABI()) {
2149     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2150                                            PPCII::MO_PIC_FLAG);
2151     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2152   }
2153
2154   SDValue CPIHi =
2155     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2156   SDValue CPILo =
2157     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2158   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2159 }
2160
2161 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2162   EVT PtrVT = Op.getValueType();
2163   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2164
2165   // 64-bit SVR4 ABI code is always position-independent.
2166   // The actual address of the GlobalValue is stored in the TOC.
2167   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2168     setUsesTOCBasePtr(DAG);
2169     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2170     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2171   }
2172
2173   unsigned MOHiFlag, MOLoFlag;
2174   bool IsPIC = isPositionIndependent();
2175   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2176
2177   if (IsPIC && Subtarget.isSVR4ABI()) {
2178     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2179                                         PPCII::MO_PIC_FLAG);
2180     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2181   }
2182
2183   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2184   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2185   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2186 }
2187
2188 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2189                                              SelectionDAG &DAG) const {
2190   EVT PtrVT = Op.getValueType();
2191   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2192   const BlockAddress *BA = BASDN->getBlockAddress();
2193
2194   // 64-bit SVR4 ABI code is always position-independent.
2195   // The actual BlockAddress is stored in the TOC.
2196   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2197     setUsesTOCBasePtr(DAG);
2198     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2199     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2200   }
2201
2202   unsigned MOHiFlag, MOLoFlag;
2203   bool IsPIC = isPositionIndependent();
2204   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2205   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2206   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2207   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2208 }
2209
2210 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2211                                               SelectionDAG &DAG) const {
2212
2213   // FIXME: TLS addresses currently use medium model code sequences,
2214   // which is the most useful form.  Eventually support for small and
2215   // large models could be added if users need it, at the cost of
2216   // additional complexity.
2217   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2218   if (DAG.getTarget().Options.EmulatedTLS)
2219     return LowerToTLSEmulatedModel(GA, DAG);
2220
2221   SDLoc dl(GA);
2222   const GlobalValue *GV = GA->getGlobal();
2223   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2224   bool is64bit = Subtarget.isPPC64();
2225   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2226   PICLevel::Level picLevel = M->getPICLevel();
2227
2228   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2229
2230   if (Model == TLSModel::LocalExec) {
2231     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2232                                                PPCII::MO_TPREL_HA);
2233     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2234                                                PPCII::MO_TPREL_LO);
2235     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2236                                      is64bit ? MVT::i64 : MVT::i32);
2237     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2238     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2239   }
2240
2241   if (Model == TLSModel::InitialExec) {
2242     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2243     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2244                                                 PPCII::MO_TLS);
2245     SDValue GOTPtr;
2246     if (is64bit) {
2247       setUsesTOCBasePtr(DAG);
2248       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2249       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2250                            PtrVT, GOTReg, TGA);
2251     } else
2252       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2253     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2254                                    PtrVT, TGA, GOTPtr);
2255     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2256   }
2257
2258   if (Model == TLSModel::GeneralDynamic) {
2259     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2260     SDValue GOTPtr;
2261     if (is64bit) {
2262       setUsesTOCBasePtr(DAG);
2263       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2264       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2265                                    GOTReg, TGA);
2266     } else {
2267       if (picLevel == PICLevel::SmallPIC)
2268         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2269       else
2270         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2271     }
2272     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2273                        GOTPtr, TGA, TGA);
2274   }
2275
2276   if (Model == TLSModel::LocalDynamic) {
2277     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2278     SDValue GOTPtr;
2279     if (is64bit) {
2280       setUsesTOCBasePtr(DAG);
2281       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2282       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2283                            GOTReg, TGA);
2284     } else {
2285       if (picLevel == PICLevel::SmallPIC)
2286         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2287       else
2288         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2289     }
2290     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2291                                   PtrVT, GOTPtr, TGA, TGA);
2292     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2293                                       PtrVT, TLSAddr, TGA);
2294     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2295   }
2296
2297   llvm_unreachable("Unknown TLS model!");
2298 }
2299
2300 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2301                                               SelectionDAG &DAG) const {
2302   EVT PtrVT = Op.getValueType();
2303   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2304   SDLoc DL(GSDN);
2305   const GlobalValue *GV = GSDN->getGlobal();
2306
2307   // 64-bit SVR4 ABI code is always position-independent.
2308   // The actual address of the GlobalValue is stored in the TOC.
2309   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2310     setUsesTOCBasePtr(DAG);
2311     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2312     return getTOCEntry(DAG, DL, true, GA);
2313   }
2314
2315   unsigned MOHiFlag, MOLoFlag;
2316   bool IsPIC = isPositionIndependent();
2317   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2318
2319   if (IsPIC && Subtarget.isSVR4ABI()) {
2320     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2321                                             GSDN->getOffset(),
2322                                             PPCII::MO_PIC_FLAG);
2323     return getTOCEntry(DAG, DL, false, GA);
2324   }
2325
2326   SDValue GAHi =
2327     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2328   SDValue GALo =
2329     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2330
2331   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2332
2333   // If the global reference is actually to a non-lazy-pointer, we have to do an
2334   // extra load to get the address of the global.
2335   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2336     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2337   return Ptr;
2338 }
2339
2340 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2341   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2342   SDLoc dl(Op);
2343
2344   if (Op.getValueType() == MVT::v2i64) {
2345     // When the operands themselves are v2i64 values, we need to do something
2346     // special because VSX has no underlying comparison operations for these.
2347     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2348       // Equality can be handled by casting to the legal type for Altivec
2349       // comparisons, everything else needs to be expanded.
2350       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2351         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2352                  DAG.getSetCC(dl, MVT::v4i32,
2353                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2354                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2355                    CC));
2356       }
2357
2358       return SDValue();
2359     }
2360
2361     // We handle most of these in the usual way.
2362     return Op;
2363   }
2364
2365   // If we're comparing for equality to zero, expose the fact that this is
2366   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2367   // fold the new nodes.
2368   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2369     if (C->isNullValue() && CC == ISD::SETEQ) {
2370       EVT VT = Op.getOperand(0).getValueType();
2371       SDValue Zext = Op.getOperand(0);
2372       if (VT.bitsLT(MVT::i32)) {
2373         VT = MVT::i32;
2374         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2375       }
2376       unsigned Log2b = Log2_32(VT.getSizeInBits());
2377       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2378       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2379                                 DAG.getConstant(Log2b, dl, MVT::i32));
2380       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2381     }
2382     // Leave comparisons against 0 and -1 alone for now, since they're usually
2383     // optimized.  FIXME: revisit this when we can custom lower all setcc
2384     // optimizations.
2385     if (C->isAllOnesValue() || C->isNullValue())
2386       return SDValue();
2387   }
2388
2389   // If we have an integer seteq/setne, turn it into a compare against zero
2390   // by xor'ing the rhs with the lhs, which is faster than setting a
2391   // condition register, reading it back out, and masking the correct bit.  The
2392   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2393   // the result to other bit-twiddling opportunities.
2394   EVT LHSVT = Op.getOperand(0).getValueType();
2395   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2396     EVT VT = Op.getValueType();
2397     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2398                                 Op.getOperand(1));
2399     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2400   }
2401   return SDValue();
2402 }
2403
2404 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2405   SDNode *Node = Op.getNode();
2406   EVT VT = Node->getValueType(0);
2407   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2408   SDValue InChain = Node->getOperand(0);
2409   SDValue VAListPtr = Node->getOperand(1);
2410   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2411   SDLoc dl(Node);
2412
2413   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2414
2415   // gpr_index
2416   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2417                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2418   InChain = GprIndex.getValue(1);
2419
2420   if (VT == MVT::i64) {
2421     // Check if GprIndex is even
2422     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2423                                  DAG.getConstant(1, dl, MVT::i32));
2424     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2425                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2426     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2427                                           DAG.getConstant(1, dl, MVT::i32));
2428     // Align GprIndex to be even if it isn't
2429     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2430                            GprIndex);
2431   }
2432
2433   // fpr index is 1 byte after gpr
2434   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2435                                DAG.getConstant(1, dl, MVT::i32));
2436
2437   // fpr
2438   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2439                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2440   InChain = FprIndex.getValue(1);
2441
2442   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2443                                        DAG.getConstant(8, dl, MVT::i32));
2444
2445   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2446                                         DAG.getConstant(4, dl, MVT::i32));
2447
2448   // areas
2449   SDValue OverflowArea =
2450       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2451   InChain = OverflowArea.getValue(1);
2452
2453   SDValue RegSaveArea =
2454       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2455   InChain = RegSaveArea.getValue(1);
2456
2457   // select overflow_area if index > 8
2458   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2459                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2460
2461   // adjustment constant gpr_index * 4/8
2462   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2463                                     VT.isInteger() ? GprIndex : FprIndex,
2464                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2465                                                     MVT::i32));
2466
2467   // OurReg = RegSaveArea + RegConstant
2468   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2469                                RegConstant);
2470
2471   // Floating types are 32 bytes into RegSaveArea
2472   if (VT.isFloatingPoint())
2473     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2474                          DAG.getConstant(32, dl, MVT::i32));
2475
2476   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2477   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2478                                    VT.isInteger() ? GprIndex : FprIndex,
2479                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2480                                                    MVT::i32));
2481
2482   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2483                               VT.isInteger() ? VAListPtr : FprPtr,
2484                               MachinePointerInfo(SV), MVT::i8);
2485
2486   // determine if we should load from reg_save_area or overflow_area
2487   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2488
2489   // increase overflow_area by 4/8 if gpr/fpr > 8
2490   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2491                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2492                                           dl, MVT::i32));
2493
2494   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2495                              OverflowAreaPlusN);
2496
2497   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2498                               MachinePointerInfo(), MVT::i32);
2499
2500   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2501 }
2502
2503 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2504   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2505
2506   // We have to copy the entire va_list struct:
2507   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2508   return DAG.getMemcpy(Op.getOperand(0), Op,
2509                        Op.getOperand(1), Op.getOperand(2),
2510                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2511                        false, MachinePointerInfo(), MachinePointerInfo());
2512 }
2513
2514 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2515                                                   SelectionDAG &DAG) const {
2516   return Op.getOperand(0);
2517 }
2518
2519 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2520                                                 SelectionDAG &DAG) const {
2521   SDValue Chain = Op.getOperand(0);
2522   SDValue Trmp = Op.getOperand(1); // trampoline
2523   SDValue FPtr = Op.getOperand(2); // nested function
2524   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2525   SDLoc dl(Op);
2526
2527   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2528   bool isPPC64 = (PtrVT == MVT::i64);
2529   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2530
2531   TargetLowering::ArgListTy Args;
2532   TargetLowering::ArgListEntry Entry;
2533
2534   Entry.Ty = IntPtrTy;
2535   Entry.Node = Trmp; Args.push_back(Entry);
2536
2537   // TrampSize == (isPPC64 ? 48 : 40);
2538   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2539                                isPPC64 ? MVT::i64 : MVT::i32);
2540   Args.push_back(Entry);
2541
2542   Entry.Node = FPtr; Args.push_back(Entry);
2543   Entry.Node = Nest; Args.push_back(Entry);
2544
2545   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2546   TargetLowering::CallLoweringInfo CLI(DAG);
2547   CLI.setDebugLoc(dl).setChain(Chain)
2548     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2549                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2550                std::move(Args));
2551
2552   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2553   return CallResult.second;
2554 }
2555
2556 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2557   MachineFunction &MF = DAG.getMachineFunction();
2558   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2559   EVT PtrVT = getPointerTy(MF.getDataLayout());
2560
2561   SDLoc dl(Op);
2562
2563   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2564     // vastart just stores the address of the VarArgsFrameIndex slot into the
2565     // memory location argument.
2566     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2567     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2568     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2569                         MachinePointerInfo(SV));
2570   }
2571
2572   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2573   // We suppose the given va_list is already allocated.
2574   //
2575   // typedef struct {
2576   //  char gpr;     /* index into the array of 8 GPRs
2577   //                 * stored in the register save area
2578   //                 * gpr=0 corresponds to r3,
2579   //                 * gpr=1 to r4, etc.
2580   //                 */
2581   //  char fpr;     /* index into the array of 8 FPRs
2582   //                 * stored in the register save area
2583   //                 * fpr=0 corresponds to f1,
2584   //                 * fpr=1 to f2, etc.
2585   //                 */
2586   //  char *overflow_arg_area;
2587   //                /* location on stack that holds
2588   //                 * the next overflow argument
2589   //                 */
2590   //  char *reg_save_area;
2591   //               /* where r3:r10 and f1:f8 (if saved)
2592   //                * are stored
2593   //                */
2594   // } va_list[1];
2595
2596   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2597   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2598   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2599                                             PtrVT);
2600   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2601                                  PtrVT);
2602
2603   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2604   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2605
2606   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2607   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2608
2609   uint64_t FPROffset = 1;
2610   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2611
2612   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2613
2614   // Store first byte : number of int regs
2615   SDValue firstStore =
2616       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2617                         MachinePointerInfo(SV), MVT::i8);
2618   uint64_t nextOffset = FPROffset;
2619   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2620                                   ConstFPROffset);
2621
2622   // Store second byte : number of float regs
2623   SDValue secondStore =
2624       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2625                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2626   nextOffset += StackOffset;
2627   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2628
2629   // Store second word : arguments given on stack
2630   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2631                                     MachinePointerInfo(SV, nextOffset));
2632   nextOffset += FrameOffset;
2633   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2634
2635   // Store third word : arguments given in registers
2636   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2637                       MachinePointerInfo(SV, nextOffset));
2638 }
2639
2640 #include "PPCGenCallingConv.inc"
2641
2642 // Function whose sole purpose is to kill compiler warnings
2643 // stemming from unused functions included from PPCGenCallingConv.inc.
2644 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2645   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2646 }
2647
2648 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2649                                       CCValAssign::LocInfo &LocInfo,
2650                                       ISD::ArgFlagsTy &ArgFlags,
2651                                       CCState &State) {
2652   return true;
2653 }
2654
2655 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2656                                              MVT &LocVT,
2657                                              CCValAssign::LocInfo &LocInfo,
2658                                              ISD::ArgFlagsTy &ArgFlags,
2659                                              CCState &State) {
2660   static const MCPhysReg ArgRegs[] = {
2661     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2662     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2663   };
2664   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2665
2666   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2667
2668   // Skip one register if the first unallocated register has an even register
2669   // number and there are still argument registers available which have not been
2670   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2671   // need to skip a register if RegNum is odd.
2672   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2673     State.AllocateReg(ArgRegs[RegNum]);
2674   }
2675
2676   // Always return false here, as this function only makes sure that the first
2677   // unallocated register has an odd register number and does not actually
2678   // allocate a register for the current argument.
2679   return false;
2680 }
2681
2682 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2683                                                MVT &LocVT,
2684                                                CCValAssign::LocInfo &LocInfo,
2685                                                ISD::ArgFlagsTy &ArgFlags,
2686                                                CCState &State) {
2687   static const MCPhysReg ArgRegs[] = {
2688     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2689     PPC::F8
2690   };
2691
2692   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2693
2694   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2695
2696   // If there is only one Floating-point register left we need to put both f64
2697   // values of a split ppc_fp128 value on the stack.
2698   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2699     State.AllocateReg(ArgRegs[RegNum]);
2700   }
2701
2702   // Always return false here, as this function only makes sure that the two f64
2703   // values a ppc_fp128 value is split into are both passed in registers or both
2704   // passed on the stack and does not actually allocate a register for the
2705   // current argument.
2706   return false;
2707 }
2708
2709 /// FPR - The set of FP registers that should be allocated for arguments,
2710 /// on Darwin.
2711 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2712                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2713                                 PPC::F11, PPC::F12, PPC::F13};
2714
2715 /// QFPR - The set of QPX registers that should be allocated for arguments.
2716 static const MCPhysReg QFPR[] = {
2717     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2718     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2719
2720 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2721 /// the stack.
2722 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2723                                        unsigned PtrByteSize) {
2724   unsigned ArgSize = ArgVT.getStoreSize();
2725   if (Flags.isByVal())
2726     ArgSize = Flags.getByValSize();
2727
2728   // Round up to multiples of the pointer size, except for array members,
2729   // which are always packed.
2730   if (!Flags.isInConsecutiveRegs())
2731     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2732
2733   return ArgSize;
2734 }
2735
2736 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2737 /// on the stack.
2738 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2739                                             ISD::ArgFlagsTy Flags,
2740                                             unsigned PtrByteSize) {
2741   unsigned Align = PtrByteSize;
2742
2743   // Altivec parameters are padded to a 16 byte boundary.
2744   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2745       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2746       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2747       ArgVT == MVT::v1i128)
2748     Align = 16;
2749   // QPX vector types stored in double-precision are padded to a 32 byte
2750   // boundary.
2751   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2752     Align = 32;
2753
2754   // ByVal parameters are aligned as requested.
2755   if (Flags.isByVal()) {
2756     unsigned BVAlign = Flags.getByValAlign();
2757     if (BVAlign > PtrByteSize) {
2758       if (BVAlign % PtrByteSize != 0)
2759           llvm_unreachable(
2760             "ByVal alignment is not a multiple of the pointer size");
2761
2762       Align = BVAlign;
2763     }
2764   }
2765
2766   // Array members are always packed to their original alignment.
2767   if (Flags.isInConsecutiveRegs()) {
2768     // If the array member was split into multiple registers, the first
2769     // needs to be aligned to the size of the full type.  (Except for
2770     // ppcf128, which is only aligned as its f64 components.)
2771     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2772       Align = OrigVT.getStoreSize();
2773     else
2774       Align = ArgVT.getStoreSize();
2775   }
2776
2777   return Align;
2778 }
2779
2780 /// CalculateStackSlotUsed - Return whether this argument will use its
2781 /// stack slot (instead of being passed in registers).  ArgOffset,
2782 /// AvailableFPRs, and AvailableVRs must hold the current argument
2783 /// position, and will be updated to account for this argument.
2784 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2785                                    ISD::ArgFlagsTy Flags,
2786                                    unsigned PtrByteSize,
2787                                    unsigned LinkageSize,
2788                                    unsigned ParamAreaSize,
2789                                    unsigned &ArgOffset,
2790                                    unsigned &AvailableFPRs,
2791                                    unsigned &AvailableVRs, bool HasQPX) {
2792   bool UseMemory = false;
2793
2794   // Respect alignment of argument on the stack.
2795   unsigned Align =
2796     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2797   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2798   // If there's no space left in the argument save area, we must
2799   // use memory (this check also catches zero-sized arguments).
2800   if (ArgOffset >= LinkageSize + ParamAreaSize)
2801     UseMemory = true;
2802
2803   // Allocate argument on the stack.
2804   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2805   if (Flags.isInConsecutiveRegsLast())
2806     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2807   // If we overran the argument save area, we must use memory
2808   // (this check catches arguments passed partially in memory)
2809   if (ArgOffset > LinkageSize + ParamAreaSize)
2810     UseMemory = true;
2811
2812   // However, if the argument is actually passed in an FPR or a VR,
2813   // we don't use memory after all.
2814   if (!Flags.isByVal()) {
2815     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2816         // QPX registers overlap with the scalar FP registers.
2817         (HasQPX && (ArgVT == MVT::v4f32 ||
2818                     ArgVT == MVT::v4f64 ||
2819                     ArgVT == MVT::v4i1)))
2820       if (AvailableFPRs > 0) {
2821         --AvailableFPRs;
2822         return false;
2823       }
2824     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2825         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2826         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2827         ArgVT == MVT::v1i128)
2828       if (AvailableVRs > 0) {
2829         --AvailableVRs;
2830         return false;
2831       }
2832   }
2833
2834   return UseMemory;
2835 }
2836
2837 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2838 /// ensure minimum alignment required for target.
2839 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2840                                      unsigned NumBytes) {
2841   unsigned TargetAlign = Lowering->getStackAlignment();
2842   unsigned AlignMask = TargetAlign - 1;
2843   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2844   return NumBytes;
2845 }
2846
2847 SDValue PPCTargetLowering::LowerFormalArguments(
2848     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2849     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2850     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2851   if (Subtarget.isSVR4ABI()) {
2852     if (Subtarget.isPPC64())
2853       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2854                                          dl, DAG, InVals);
2855     else
2856       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2857                                          dl, DAG, InVals);
2858   } else {
2859     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2860                                        dl, DAG, InVals);
2861   }
2862 }
2863
2864 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2865     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2866     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2867     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2868
2869   // 32-bit SVR4 ABI Stack Frame Layout:
2870   //              +-----------------------------------+
2871   //        +-->  |            Back chain             |
2872   //        |     +-----------------------------------+
2873   //        |     | Floating-point register save area |
2874   //        |     +-----------------------------------+
2875   //        |     |    General register save area     |
2876   //        |     +-----------------------------------+
2877   //        |     |          CR save word             |
2878   //        |     +-----------------------------------+
2879   //        |     |         VRSAVE save word          |
2880   //        |     +-----------------------------------+
2881   //        |     |         Alignment padding         |
2882   //        |     +-----------------------------------+
2883   //        |     |     Vector register save area     |
2884   //        |     +-----------------------------------+
2885   //        |     |       Local variable space        |
2886   //        |     +-----------------------------------+
2887   //        |     |        Parameter list area        |
2888   //        |     +-----------------------------------+
2889   //        |     |           LR save word            |
2890   //        |     +-----------------------------------+
2891   // SP-->  +---  |            Back chain             |
2892   //              +-----------------------------------+
2893   //
2894   // Specifications:
2895   //   System V Application Binary Interface PowerPC Processor Supplement
2896   //   AltiVec Technology Programming Interface Manual
2897
2898   MachineFunction &MF = DAG.getMachineFunction();
2899   MachineFrameInfo *MFI = MF.getFrameInfo();
2900   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2901
2902   EVT PtrVT = getPointerTy(MF.getDataLayout());
2903   // Potential tail calls could cause overwriting of argument stack slots.
2904   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2905                        (CallConv == CallingConv::Fast));
2906   unsigned PtrByteSize = 4;
2907
2908   // Assign locations to all of the incoming arguments.
2909   SmallVector<CCValAssign, 16> ArgLocs;
2910   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2911                  *DAG.getContext());
2912
2913   // Reserve space for the linkage area on the stack.
2914   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2915   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2916   if (useSoftFloat())
2917     CCInfo.PreAnalyzeFormalArguments(Ins);
2918
2919   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2920   CCInfo.clearWasPPCF128();
2921
2922   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2923     CCValAssign &VA = ArgLocs[i];
2924
2925     // Arguments stored in registers.
2926     if (VA.isRegLoc()) {
2927       const TargetRegisterClass *RC;
2928       EVT ValVT = VA.getValVT();
2929
2930       switch (ValVT.getSimpleVT().SimpleTy) {
2931         default:
2932           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2933         case MVT::i1:
2934         case MVT::i32:
2935           RC = &PPC::GPRCRegClass;
2936           break;
2937         case MVT::f32:
2938           if (Subtarget.hasP8Vector())
2939             RC = &PPC::VSSRCRegClass;
2940           else
2941             RC = &PPC::F4RCRegClass;
2942           break;
2943         case MVT::f64:
2944           if (Subtarget.hasVSX())
2945             RC = &PPC::VSFRCRegClass;
2946           else
2947             RC = &PPC::F8RCRegClass;
2948           break;
2949         case MVT::v16i8:
2950         case MVT::v8i16:
2951         case MVT::v4i32:
2952           RC = &PPC::VRRCRegClass;
2953           break;
2954         case MVT::v4f32:
2955           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2956           break;
2957         case MVT::v2f64:
2958         case MVT::v2i64:
2959           RC = &PPC::VSHRCRegClass;
2960           break;
2961         case MVT::v4f64:
2962           RC = &PPC::QFRCRegClass;
2963           break;
2964         case MVT::v4i1:
2965           RC = &PPC::QBRCRegClass;
2966           break;
2967       }
2968
2969       // Transform the arguments stored in physical registers into virtual ones.
2970       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2971       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2972                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2973
2974       if (ValVT == MVT::i1)
2975         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2976
2977       InVals.push_back(ArgValue);
2978     } else {
2979       // Argument stored in memory.
2980       assert(VA.isMemLoc());
2981
2982       unsigned ArgSize = VA.getLocVT().getStoreSize();
2983       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2984                                       isImmutable);
2985
2986       // Create load nodes to retrieve arguments from the stack.
2987       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2988       InVals.push_back(
2989           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
2990     }
2991   }
2992
2993   // Assign locations to all of the incoming aggregate by value arguments.
2994   // Aggregates passed by value are stored in the local variable space of the
2995   // caller's stack frame, right above the parameter list area.
2996   SmallVector<CCValAssign, 16> ByValArgLocs;
2997   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2998                       ByValArgLocs, *DAG.getContext());
2999
3000   // Reserve stack space for the allocations in CCInfo.
3001   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3002
3003   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3004
3005   // Area that is at least reserved in the caller of this function.
3006   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3007   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3008
3009   // Set the size that is at least reserved in caller of this function.  Tail
3010   // call optimized function's reserved stack space needs to be aligned so that
3011   // taking the difference between two stack areas will result in an aligned
3012   // stack.
3013   MinReservedArea =
3014       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3015   FuncInfo->setMinReservedArea(MinReservedArea);
3016
3017   SmallVector<SDValue, 8> MemOps;
3018
3019   // If the function takes variable number of arguments, make a frame index for
3020   // the start of the first vararg value... for expansion of llvm.va_start.
3021   if (isVarArg) {
3022     static const MCPhysReg GPArgRegs[] = {
3023       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3024       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3025     };
3026     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3027
3028     static const MCPhysReg FPArgRegs[] = {
3029       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3030       PPC::F8
3031     };
3032     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3033
3034     if (useSoftFloat())
3035        NumFPArgRegs = 0;
3036
3037     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3038     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3039
3040     // Make room for NumGPArgRegs and NumFPArgRegs.
3041     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3042                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3043
3044     FuncInfo->setVarArgsStackOffset(
3045       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3046                              CCInfo.getNextStackOffset(), true));
3047
3048     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
3049     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3050
3051     // The fixed integer arguments of a variadic function are stored to the
3052     // VarArgsFrameIndex on the stack so that they may be loaded by
3053     // dereferencing the result of va_next.
3054     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3055       // Get an existing live-in vreg, or add a new one.
3056       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3057       if (!VReg)
3058         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3059
3060       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3061       SDValue Store =
3062           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3063       MemOps.push_back(Store);
3064       // Increment the address by four for the next argument to store
3065       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3066       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3067     }
3068
3069     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3070     // is set.
3071     // The double arguments are stored to the VarArgsFrameIndex
3072     // on the stack.
3073     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3074       // Get an existing live-in vreg, or add a new one.
3075       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3076       if (!VReg)
3077         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3078
3079       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3080       SDValue Store =
3081           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3082       MemOps.push_back(Store);
3083       // Increment the address by eight for the next argument to store
3084       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3085                                          PtrVT);
3086       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3087     }
3088   }
3089
3090   if (!MemOps.empty())
3091     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3092
3093   return Chain;
3094 }
3095
3096 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3097 // value to MVT::i64 and then truncate to the correct register size.
3098 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3099                                              EVT ObjectVT, SelectionDAG &DAG,
3100                                              SDValue ArgVal,
3101                                              const SDLoc &dl) const {
3102   if (Flags.isSExt())
3103     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3104                          DAG.getValueType(ObjectVT));
3105   else if (Flags.isZExt())
3106     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3107                          DAG.getValueType(ObjectVT));
3108
3109   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3110 }
3111
3112 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3113     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3114     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3115     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3116   // TODO: add description of PPC stack frame format, or at least some docs.
3117   //
3118   bool isELFv2ABI = Subtarget.isELFv2ABI();
3119   bool isLittleEndian = Subtarget.isLittleEndian();
3120   MachineFunction &MF = DAG.getMachineFunction();
3121   MachineFrameInfo *MFI = MF.getFrameInfo();
3122   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3123
3124   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3125          "fastcc not supported on varargs functions");
3126
3127   EVT PtrVT = getPointerTy(MF.getDataLayout());
3128   // Potential tail calls could cause overwriting of argument stack slots.
3129   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3130                        (CallConv == CallingConv::Fast));
3131   unsigned PtrByteSize = 8;
3132   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3133
3134   static const MCPhysReg GPR[] = {
3135     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3136     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3137   };
3138   static const MCPhysReg VR[] = {
3139     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3140     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3141   };
3142   static const MCPhysReg VSRH[] = {
3143     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3144     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3145   };
3146
3147   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3148   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3149   const unsigned Num_VR_Regs  = array_lengthof(VR);
3150   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3151
3152   // Do a first pass over the arguments to determine whether the ABI
3153   // guarantees that our caller has allocated the parameter save area
3154   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3155   // in the ELFv2 ABI, it is true if this is a vararg function or if
3156   // any parameter is located in a stack slot.
3157
3158   bool HasParameterArea = !isELFv2ABI || isVarArg;
3159   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3160   unsigned NumBytes = LinkageSize;
3161   unsigned AvailableFPRs = Num_FPR_Regs;
3162   unsigned AvailableVRs = Num_VR_Regs;
3163   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3164     if (Ins[i].Flags.isNest())
3165       continue;
3166
3167     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3168                                PtrByteSize, LinkageSize, ParamAreaSize,
3169                                NumBytes, AvailableFPRs, AvailableVRs,
3170                                Subtarget.hasQPX()))
3171       HasParameterArea = true;
3172   }
3173
3174   // Add DAG nodes to load the arguments or copy them out of registers.  On
3175   // entry to a function on PPC, the arguments start after the linkage area,
3176   // although the first ones are often in registers.
3177
3178   unsigned ArgOffset = LinkageSize;
3179   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3180   unsigned &QFPR_idx = FPR_idx;
3181   SmallVector<SDValue, 8> MemOps;
3182   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3183   unsigned CurArgIdx = 0;
3184   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3185     SDValue ArgVal;
3186     bool needsLoad = false;
3187     EVT ObjectVT = Ins[ArgNo].VT;
3188     EVT OrigVT = Ins[ArgNo].ArgVT;
3189     unsigned ObjSize = ObjectVT.getStoreSize();
3190     unsigned ArgSize = ObjSize;
3191     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3192     if (Ins[ArgNo].isOrigArg()) {
3193       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3194       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3195     }
3196     // We re-align the argument offset for each argument, except when using the
3197     // fast calling convention, when we need to make sure we do that only when
3198     // we'll actually use a stack slot.
3199     unsigned CurArgOffset, Align;
3200     auto ComputeArgOffset = [&]() {
3201       /* Respect alignment of argument on the stack.  */
3202       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3203       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3204       CurArgOffset = ArgOffset;
3205     };
3206
3207     if (CallConv != CallingConv::Fast) {
3208       ComputeArgOffset();
3209
3210       /* Compute GPR index associated with argument offset.  */
3211       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3212       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3213     }
3214
3215     // FIXME the codegen can be much improved in some cases.
3216     // We do not have to keep everything in memory.
3217     if (Flags.isByVal()) {
3218       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3219
3220       if (CallConv == CallingConv::Fast)
3221         ComputeArgOffset();
3222
3223       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3224       ObjSize = Flags.getByValSize();
3225       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3226       // Empty aggregate parameters do not take up registers.  Examples:
3227       //   struct { } a;
3228       //   union  { } b;
3229       //   int c[0];
3230       // etc.  However, we have to provide a place-holder in InVals, so
3231       // pretend we have an 8-byte item at the current address for that
3232       // purpose.
3233       if (!ObjSize) {
3234         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3235         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3236         InVals.push_back(FIN);
3237         continue;
3238       }
3239
3240       // Create a stack object covering all stack doublewords occupied
3241       // by the argument.  If the argument is (fully or partially) on
3242       // the stack, or if the argument is fully in registers but the
3243       // caller has allocated the parameter save anyway, we can refer
3244       // directly to the caller's stack frame.  Otherwise, create a
3245       // local copy in our own frame.
3246       int FI;
3247       if (HasParameterArea ||
3248           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3249         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3250       else
3251         FI = MFI->CreateStackObject(ArgSize, Align, false);
3252       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3253
3254       // Handle aggregates smaller than 8 bytes.
3255       if (ObjSize < PtrByteSize) {
3256         // The value of the object is its address, which differs from the
3257         // address of the enclosing doubleword on big-endian systems.
3258         SDValue Arg = FIN;
3259         if (!isLittleEndian) {
3260           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3261           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3262         }
3263         InVals.push_back(Arg);
3264
3265         if (GPR_idx != Num_GPR_Regs) {
3266           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3267           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3268           SDValue Store;
3269
3270           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3271             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3272                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3273             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3274                                       MachinePointerInfo(&*FuncArg), ObjType);
3275           } else {
3276             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3277             // store the whole register as-is to the parameter save area
3278             // slot.
3279             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3280                                  MachinePointerInfo(&*FuncArg));
3281           }
3282
3283           MemOps.push_back(Store);
3284         }
3285         // Whether we copied from a register or not, advance the offset
3286         // into the parameter save area by a full doubleword.
3287         ArgOffset += PtrByteSize;
3288         continue;
3289       }
3290
3291       // The value of the object is its address, which is the address of
3292       // its first stack doubleword.
3293       InVals.push_back(FIN);
3294
3295       // Store whatever pieces of the object are in registers to memory.
3296       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3297         if (GPR_idx == Num_GPR_Regs)
3298           break;
3299
3300         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3301         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3302         SDValue Addr = FIN;
3303         if (j) {
3304           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3305           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3306         }
3307         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3308                                      MachinePointerInfo(&*FuncArg, j));
3309         MemOps.push_back(Store);
3310         ++GPR_idx;
3311       }
3312       ArgOffset += ArgSize;
3313       continue;
3314     }
3315
3316     switch (ObjectVT.getSimpleVT().SimpleTy) {
3317     default: llvm_unreachable("Unhandled argument type!");
3318     case MVT::i1:
3319     case MVT::i32:
3320     case MVT::i64:
3321       if (Flags.isNest()) {
3322         // The 'nest' parameter, if any, is passed in R11.
3323         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3324         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3325
3326         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3327           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3328
3329         break;
3330       }
3331
3332       // These can be scalar arguments or elements of an integer array type
3333       // passed directly.  Clang may use those instead of "byval" aggregate
3334       // types to avoid forcing arguments to memory unnecessarily.
3335       if (GPR_idx != Num_GPR_Regs) {
3336         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3337         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3338
3339         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3340           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3341           // value to MVT::i64 and then truncate to the correct register size.
3342           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3343       } else {
3344         if (CallConv == CallingConv::Fast)
3345           ComputeArgOffset();
3346
3347         needsLoad = true;
3348         ArgSize = PtrByteSize;
3349       }
3350       if (CallConv != CallingConv::Fast || needsLoad)
3351         ArgOffset += 8;
3352       break;
3353
3354     case MVT::f32:
3355     case MVT::f64:
3356       // These can be scalar arguments or elements of a float array type
3357       // passed directly.  The latter are used to implement ELFv2 homogenous
3358       // float aggregates.
3359       if (FPR_idx != Num_FPR_Regs) {
3360         unsigned VReg;
3361
3362         if (ObjectVT == MVT::f32)
3363           VReg = MF.addLiveIn(FPR[FPR_idx],
3364                               Subtarget.hasP8Vector()
3365                                   ? &PPC::VSSRCRegClass
3366                                   : &PPC::F4RCRegClass);
3367         else
3368           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3369                                                 ? &PPC::VSFRCRegClass
3370                                                 : &PPC::F8RCRegClass);
3371
3372         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3373         ++FPR_idx;
3374       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3375         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3376         // once we support fp <-> gpr moves.
3377
3378         // This can only ever happen in the presence of f32 array types,
3379         // since otherwise we never run out of FPRs before running out
3380         // of GPRs.
3381         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3382         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3383
3384         if (ObjectVT == MVT::f32) {
3385           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3386             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3387                                  DAG.getConstant(32, dl, MVT::i32));
3388           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3389         }
3390
3391         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3392       } else {
3393         if (CallConv == CallingConv::Fast)
3394           ComputeArgOffset();
3395
3396         needsLoad = true;
3397       }
3398
3399       // When passing an array of floats, the array occupies consecutive
3400       // space in the argument area; only round up to the next doubleword
3401       // at the end of the array.  Otherwise, each float takes 8 bytes.
3402       if (CallConv != CallingConv::Fast || needsLoad) {
3403         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3404         ArgOffset += ArgSize;
3405         if (Flags.isInConsecutiveRegsLast())
3406           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3407       }
3408       break;
3409     case MVT::v4f32:
3410     case MVT::v4i32:
3411     case MVT::v8i16:
3412     case MVT::v16i8:
3413     case MVT::v2f64:
3414     case MVT::v2i64:
3415     case MVT::v1i128:
3416       if (!Subtarget.hasQPX()) {
3417       // These can be scalar arguments or elements of a vector array type
3418       // passed directly.  The latter are used to implement ELFv2 homogenous
3419       // vector aggregates.
3420       if (VR_idx != Num_VR_Regs) {
3421         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3422                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3423                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3424         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3425         ++VR_idx;
3426       } else {
3427         if (CallConv == CallingConv::Fast)
3428           ComputeArgOffset();
3429
3430         needsLoad = true;
3431       }
3432       if (CallConv != CallingConv::Fast || needsLoad)
3433         ArgOffset += 16;
3434       break;
3435       } // not QPX
3436
3437       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3438              "Invalid QPX parameter type");
3439       /* fall through */
3440
3441     case MVT::v4f64:
3442     case MVT::v4i1:
3443       // QPX vectors are treated like their scalar floating-point subregisters
3444       // (except that they're larger).
3445       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3446       if (QFPR_idx != Num_QFPR_Regs) {
3447         const TargetRegisterClass *RC;
3448         switch (ObjectVT.getSimpleVT().SimpleTy) {
3449         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3450         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3451         default:         RC = &PPC::QBRCRegClass; break;
3452         }
3453
3454         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3455         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3456         ++QFPR_idx;
3457       } else {
3458         if (CallConv == CallingConv::Fast)
3459           ComputeArgOffset();
3460         needsLoad = true;
3461       }
3462       if (CallConv != CallingConv::Fast || needsLoad)
3463         ArgOffset += Sz;
3464       break;
3465     }
3466
3467     // We need to load the argument to a virtual register if we determined
3468     // above that we ran out of physical registers of the appropriate type.
3469     if (needsLoad) {
3470       if (ObjSize < ArgSize && !isLittleEndian)
3471         CurArgOffset += ArgSize - ObjSize;
3472       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3473       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3474       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3475     }
3476
3477     InVals.push_back(ArgVal);
3478   }
3479
3480   // Area that is at least reserved in the caller of this function.
3481   unsigned MinReservedArea;
3482   if (HasParameterArea)
3483     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3484   else
3485     MinReservedArea = LinkageSize;
3486
3487   // Set the size that is at least reserved in caller of this function.  Tail
3488   // call optimized functions' reserved stack space needs to be aligned so that
3489   // taking the difference between two stack areas will result in an aligned
3490   // stack.
3491   MinReservedArea =
3492       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3493   FuncInfo->setMinReservedArea(MinReservedArea);
3494
3495   // If the function takes variable number of arguments, make a frame index for
3496   // the start of the first vararg value... for expansion of llvm.va_start.
3497   if (isVarArg) {
3498     int Depth = ArgOffset;
3499
3500     FuncInfo->setVarArgsFrameIndex(
3501       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3502     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3503
3504     // If this function is vararg, store any remaining integer argument regs
3505     // to their spots on the stack so that they may be loaded by dereferencing
3506     // the result of va_next.
3507     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3508          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3509       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3510       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3511       SDValue Store =
3512           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3513       MemOps.push_back(Store);
3514       // Increment the address by four for the next argument to store
3515       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3516       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3517     }
3518   }
3519
3520   if (!MemOps.empty())
3521     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3522
3523   return Chain;
3524 }
3525
3526 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3527     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3528     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3529     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3530   // TODO: add description of PPC stack frame format, or at least some docs.
3531   //
3532   MachineFunction &MF = DAG.getMachineFunction();
3533   MachineFrameInfo *MFI = MF.getFrameInfo();
3534   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3535
3536   EVT PtrVT = getPointerTy(MF.getDataLayout());
3537   bool isPPC64 = PtrVT == MVT::i64;
3538   // Potential tail calls could cause overwriting of argument stack slots.
3539   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3540                        (CallConv == CallingConv::Fast));
3541   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3542   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3543   unsigned ArgOffset = LinkageSize;
3544   // Area that is at least reserved in caller of this function.
3545   unsigned MinReservedArea = ArgOffset;
3546
3547   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3548     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3549     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3550   };
3551   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3552     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3553     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3554   };
3555   static const MCPhysReg VR[] = {
3556     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3557     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3558   };
3559
3560   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3561   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3562   const unsigned Num_VR_Regs  = array_lengthof( VR);
3563
3564   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3565
3566   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3567
3568   // In 32-bit non-varargs functions, the stack space for vectors is after the
3569   // stack space for non-vectors.  We do not use this space unless we have
3570   // too many vectors to fit in registers, something that only occurs in
3571   // constructed examples:), but we have to walk the arglist to figure
3572   // that out...for the pathological case, compute VecArgOffset as the
3573   // start of the vector parameter area.  Computing VecArgOffset is the
3574   // entire point of the following loop.
3575   unsigned VecArgOffset = ArgOffset;
3576   if (!isVarArg && !isPPC64) {
3577     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3578          ++ArgNo) {
3579       EVT ObjectVT = Ins[ArgNo].VT;
3580       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3581
3582       if (Flags.isByVal()) {
3583         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3584         unsigned ObjSize = Flags.getByValSize();
3585         unsigned ArgSize =
3586                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3587         VecArgOffset += ArgSize;
3588         continue;
3589       }
3590
3591       switch(ObjectVT.getSimpleVT().SimpleTy) {
3592       default: llvm_unreachable("Unhandled argument type!");
3593       case MVT::i1:
3594       case MVT::i32:
3595       case MVT::f32:
3596         VecArgOffset += 4;
3597         break;
3598       case MVT::i64:  // PPC64
3599       case MVT::f64:
3600         // FIXME: We are guaranteed to be !isPPC64 at this point.
3601         // Does MVT::i64 apply?
3602         VecArgOffset += 8;
3603         break;
3604       case MVT::v4f32:
3605       case MVT::v4i32:
3606       case MVT::v8i16:
3607       case MVT::v16i8:
3608         // Nothing to do, we're only looking at Nonvector args here.
3609         break;
3610       }
3611     }
3612   }
3613   // We've found where the vector parameter area in memory is.  Skip the
3614   // first 12 parameters; these don't use that memory.
3615   VecArgOffset = ((VecArgOffset+15)/16)*16;
3616   VecArgOffset += 12*16;
3617
3618   // Add DAG nodes to load the arguments or copy them out of registers.  On
3619   // entry to a function on PPC, the arguments start after the linkage area,
3620   // although the first ones are often in registers.
3621
3622   SmallVector<SDValue, 8> MemOps;
3623   unsigned nAltivecParamsAtEnd = 0;
3624   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3625   unsigned CurArgIdx = 0;
3626   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3627     SDValue ArgVal;
3628     bool needsLoad = false;
3629     EVT ObjectVT = Ins[ArgNo].VT;
3630     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3631     unsigned ArgSize = ObjSize;
3632     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3633     if (Ins[ArgNo].isOrigArg()) {
3634       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3635       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3636     }
3637     unsigned CurArgOffset = ArgOffset;
3638
3639     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3640     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3641         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3642       if (isVarArg || isPPC64) {
3643         MinReservedArea = ((MinReservedArea+15)/16)*16;
3644         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3645                                                   Flags,
3646                                                   PtrByteSize);
3647       } else  nAltivecParamsAtEnd++;
3648     } else
3649       // Calculate min reserved area.
3650       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3651                                                 Flags,
3652                                                 PtrByteSize);
3653
3654     // FIXME the codegen can be much improved in some cases.
3655     // We do not have to keep everything in memory.
3656     if (Flags.isByVal()) {
3657       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3658
3659       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3660       ObjSize = Flags.getByValSize();
3661       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3662       // Objects of size 1 and 2 are right justified, everything else is
3663       // left justified.  This means the memory address is adjusted forwards.
3664       if (ObjSize==1 || ObjSize==2) {
3665         CurArgOffset = CurArgOffset + (4 - ObjSize);
3666       }
3667       // The value of the object is its address.
3668       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3669       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3670       InVals.push_back(FIN);
3671       if (ObjSize==1 || ObjSize==2) {
3672         if (GPR_idx != Num_GPR_Regs) {
3673           unsigned VReg;
3674           if (isPPC64)
3675             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3676           else
3677             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3678           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3679           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3680           SDValue Store =
3681               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3682                                 MachinePointerInfo(&*FuncArg), ObjType);
3683           MemOps.push_back(Store);
3684           ++GPR_idx;
3685         }
3686
3687         ArgOffset += PtrByteSize;
3688
3689         continue;
3690       }
3691       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3692         // Store whatever pieces of the object are in registers
3693         // to memory.  ArgOffset will be the address of the beginning
3694         // of the object.
3695         if (GPR_idx != Num_GPR_Regs) {
3696           unsigned VReg;
3697           if (isPPC64)
3698             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3699           else
3700             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3701           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3702           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3703           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3704           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3705                                        MachinePointerInfo(&*FuncArg, j));
3706           MemOps.push_back(Store);
3707           ++GPR_idx;
3708           ArgOffset += PtrByteSize;
3709         } else {
3710           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3711           break;
3712         }
3713       }
3714       continue;
3715     }
3716
3717     switch (ObjectVT.getSimpleVT().SimpleTy) {
3718     default: llvm_unreachable("Unhandled argument type!");
3719     case MVT::i1:
3720     case MVT::i32:
3721       if (!isPPC64) {
3722         if (GPR_idx != Num_GPR_Regs) {
3723           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3724           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3725
3726           if (ObjectVT == MVT::i1)
3727             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3728
3729           ++GPR_idx;
3730         } else {
3731           needsLoad = true;
3732           ArgSize = PtrByteSize;
3733         }
3734         // All int arguments reserve stack space in the Darwin ABI.
3735         ArgOffset += PtrByteSize;
3736         break;
3737       }
3738       // FALLTHROUGH
3739     case MVT::i64:  // PPC64
3740       if (GPR_idx != Num_GPR_Regs) {
3741         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3742         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3743
3744         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3745           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3746           // value to MVT::i64 and then truncate to the correct register size.
3747           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3748
3749         ++GPR_idx;
3750       } else {
3751         needsLoad = true;
3752         ArgSize = PtrByteSize;
3753       }
3754       // All int arguments reserve stack space in the Darwin ABI.
3755       ArgOffset += 8;
3756       break;
3757
3758     case MVT::f32:
3759     case MVT::f64:
3760       // Every 4 bytes of argument space consumes one of the GPRs available for
3761       // argument passing.
3762       if (GPR_idx != Num_GPR_Regs) {
3763         ++GPR_idx;
3764         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3765           ++GPR_idx;
3766       }
3767       if (FPR_idx != Num_FPR_Regs) {
3768         unsigned VReg;
3769
3770         if (ObjectVT == MVT::f32)
3771           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3772         else
3773           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3774
3775         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3776         ++FPR_idx;
3777       } else {
3778         needsLoad = true;
3779       }
3780
3781       // All FP arguments reserve stack space in the Darwin ABI.
3782       ArgOffset += isPPC64 ? 8 : ObjSize;
3783       break;
3784     case MVT::v4f32:
3785     case MVT::v4i32:
3786     case MVT::v8i16:
3787     case MVT::v16i8:
3788       // Note that vector arguments in registers don't reserve stack space,
3789       // except in varargs functions.
3790       if (VR_idx != Num_VR_Regs) {
3791         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3792         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3793         if (isVarArg) {
3794           while ((ArgOffset % 16) != 0) {
3795             ArgOffset += PtrByteSize;
3796             if (GPR_idx != Num_GPR_Regs)
3797               GPR_idx++;
3798           }
3799           ArgOffset += 16;
3800           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3801         }
3802         ++VR_idx;
3803       } else {
3804         if (!isVarArg && !isPPC64) {
3805           // Vectors go after all the nonvectors.
3806           CurArgOffset = VecArgOffset;
3807           VecArgOffset += 16;
3808         } else {
3809           // Vectors are aligned.
3810           ArgOffset = ((ArgOffset+15)/16)*16;
3811           CurArgOffset = ArgOffset;
3812           ArgOffset += 16;
3813         }
3814         needsLoad = true;
3815       }
3816       break;
3817     }
3818
3819     // We need to load the argument to a virtual register if we determined above
3820     // that we ran out of physical registers of the appropriate type.
3821     if (needsLoad) {
3822       int FI = MFI->CreateFixedObject(ObjSize,
3823                                       CurArgOffset + (ArgSize - ObjSize),
3824                                       isImmutable);
3825       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3826       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3827     }
3828
3829     InVals.push_back(ArgVal);
3830   }
3831
3832   // Allow for Altivec parameters at the end, if needed.
3833   if (nAltivecParamsAtEnd) {
3834     MinReservedArea = ((MinReservedArea+15)/16)*16;
3835     MinReservedArea += 16*nAltivecParamsAtEnd;
3836   }
3837
3838   // Area that is at least reserved in the caller of this function.
3839   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3840
3841   // Set the size that is at least reserved in caller of this function.  Tail
3842   // call optimized functions' reserved stack space needs to be aligned so that
3843   // taking the difference between two stack areas will result in an aligned
3844   // stack.
3845   MinReservedArea =
3846       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3847   FuncInfo->setMinReservedArea(MinReservedArea);
3848
3849   // If the function takes variable number of arguments, make a frame index for
3850   // the start of the first vararg value... for expansion of llvm.va_start.
3851   if (isVarArg) {
3852     int Depth = ArgOffset;
3853
3854     FuncInfo->setVarArgsFrameIndex(
3855       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3856                              Depth, true));
3857     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3858
3859     // If this function is vararg, store any remaining integer argument regs
3860     // to their spots on the stack so that they may be loaded by dereferencing
3861     // the result of va_next.
3862     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3863       unsigned VReg;
3864
3865       if (isPPC64)
3866         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3867       else
3868         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3869
3870       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3871       SDValue Store =
3872           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3873       MemOps.push_back(Store);
3874       // Increment the address by four for the next argument to store
3875       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3876       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3877     }
3878   }
3879
3880   if (!MemOps.empty())
3881     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3882
3883   return Chain;
3884 }
3885
3886 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3887 /// adjusted to accommodate the arguments for the tailcall.
3888 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3889                                    unsigned ParamSize) {
3890
3891   if (!isTailCall) return 0;
3892
3893   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3894   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3895   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3896   // Remember only if the new adjustement is bigger.
3897   if (SPDiff < FI->getTailCallSPDelta())
3898     FI->setTailCallSPDelta(SPDiff);
3899
3900   return SPDiff;
3901 }
3902
3903 static bool isFunctionGlobalAddress(SDValue Callee);
3904
3905 static bool
3906 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3907   // If !G, Callee can be an external symbol.
3908   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3909   if (!G) return false;
3910
3911   const GlobalValue *GV = G->getGlobal();
3912
3913   if (GV->isDeclaration()) return false;
3914
3915   switch(GV->getLinkage()) {
3916   default: llvm_unreachable("unknow linkage type");
3917   case GlobalValue::AvailableExternallyLinkage:
3918   case GlobalValue::ExternalWeakLinkage:
3919     return false;
3920
3921   // Callee with weak linkage is allowed if it has hidden or protected
3922   // visibility
3923   case GlobalValue::LinkOnceAnyLinkage:
3924   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3925   case GlobalValue::WeakAnyLinkage:
3926   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3927     if (GV->hasDefaultVisibility())
3928       return false;
3929
3930   case GlobalValue::ExternalLinkage:
3931   case GlobalValue::InternalLinkage:
3932   case GlobalValue::PrivateLinkage:
3933     break;
3934   }
3935
3936   // With '-fPIC', calling default visiblity function need insert 'nop' after
3937   // function call, no matter that function resides in same module or not, so
3938   // we treat it as in different module.
3939   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3940     return false;
3941
3942   return true;
3943 }
3944
3945 static bool
3946 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3947                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3948   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3949
3950   const unsigned PtrByteSize = 8;
3951   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3952
3953   static const MCPhysReg GPR[] = {
3954     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3955     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3956   };
3957   static const MCPhysReg VR[] = {
3958     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3959     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3960   };
3961
3962   const unsigned NumGPRs = array_lengthof(GPR);
3963   const unsigned NumFPRs = 13;
3964   const unsigned NumVRs = array_lengthof(VR);
3965   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3966
3967   unsigned NumBytes = LinkageSize;
3968   unsigned AvailableFPRs = NumFPRs;
3969   unsigned AvailableVRs = NumVRs;
3970
3971   for (const ISD::OutputArg& Param : Outs) {
3972     if (Param.Flags.isNest()) continue;
3973
3974     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3975                                PtrByteSize, LinkageSize, ParamAreaSize,
3976                                NumBytes, AvailableFPRs, AvailableVRs,
3977                                Subtarget.hasQPX()))
3978       return true;
3979   }
3980   return false;
3981 }
3982
3983 static bool
3984 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
3985   if (CS->arg_size() != CallerFn->getArgumentList().size())
3986     return false;
3987
3988   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
3989   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
3990   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
3991
3992   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
3993     const Value* CalleeArg = *CalleeArgIter;
3994     const Value* CallerArg = &(*CallerArgIter);
3995     if (CalleeArg == CallerArg)
3996       continue;
3997
3998     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
3999     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4000     //      }
4001     // 1st argument of callee is undef and has the same type as caller.
4002     if (CalleeArg->getType() == CallerArg->getType() &&
4003         isa<UndefValue>(CalleeArg))
4004       continue;
4005
4006     return false;
4007   }
4008
4009   return true;
4010 }
4011
4012 bool
4013 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4014                                     SDValue Callee,
4015                                     CallingConv::ID CalleeCC,
4016                                     ImmutableCallSite *CS,
4017                                     bool isVarArg,
4018                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4019                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4020                                     SelectionDAG& DAG) const {
4021   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4022
4023   if (DisableSCO && !TailCallOpt) return false;
4024
4025   // Variadic argument functions are not supported.
4026   if (isVarArg) return false;
4027
4028   MachineFunction &MF = DAG.getMachineFunction();
4029   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4030
4031   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4032   // the same calling convention
4033   if (CallerCC != CalleeCC) return false;
4034
4035   // SCO support C calling convention
4036   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4037     return false;
4038
4039   // Caller contains any byval parameter is not supported.
4040   if (std::any_of(Ins.begin(), Ins.end(),
4041                   [](const ISD::InputArg& IA) { return IA.Flags.isByVal(); }))
4042     return false;
4043
4044   // Callee contains any byval parameter is not supported, too.
4045   // Note: This is a quick work around, because in some cases, e.g.
4046   // caller's stack size > callee's stack size, we are still able to apply
4047   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4048   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4049     return false;
4050
4051   // No TCO/SCO on indirect call because Caller have to restore its TOC
4052   if (!isFunctionGlobalAddress(Callee) &&
4053       !isa<ExternalSymbolSDNode>(Callee))
4054     return false;
4055
4056   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4057   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4058   // module.
4059   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4060   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4061     return false;
4062
4063   // TCO allows altering callee ABI, so we don't have to check further.
4064   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4065     return true;
4066
4067   if (DisableSCO) return false;
4068
4069   // If callee use the same argument list that caller is using, then we can
4070   // apply SCO on this case. If it is not, then we need to check if callee needs
4071   // stack for passing arguments.
4072   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4073       needStackSlotPassParameters(Subtarget, Outs)) {
4074     return false;
4075   }
4076
4077   return true;
4078 }
4079
4080 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4081 /// for tail call optimization. Targets which want to do tail call
4082 /// optimization should implement this function.
4083 bool
4084 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4085                                                      CallingConv::ID CalleeCC,
4086                                                      bool isVarArg,
4087                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4088                                                      SelectionDAG& DAG) const {
4089   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4090     return false;
4091
4092   // Variable argument functions are not supported.
4093   if (isVarArg)
4094     return false;
4095
4096   MachineFunction &MF = DAG.getMachineFunction();
4097   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4098   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4099     // Functions containing by val parameters are not supported.
4100     for (unsigned i = 0; i != Ins.size(); i++) {
4101        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4102        if (Flags.isByVal()) return false;
4103     }
4104
4105     // Non-PIC/GOT tail calls are supported.
4106     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4107       return true;
4108
4109     // At the moment we can only do local tail calls (in same module, hidden
4110     // or protected) if we are generating PIC.
4111     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4112       return G->getGlobal()->hasHiddenVisibility()
4113           || G->getGlobal()->hasProtectedVisibility();
4114   }
4115
4116   return false;
4117 }
4118
4119 /// isCallCompatibleAddress - Return the immediate to use if the specified
4120 /// 32-bit value is representable in the immediate field of a BxA instruction.
4121 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4122   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4123   if (!C) return nullptr;
4124
4125   int Addr = C->getZExtValue();
4126   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4127       SignExtend32<26>(Addr) != Addr)
4128     return nullptr;  // Top 6 bits have to be sext of immediate.
4129
4130   return DAG
4131       .getConstant(
4132           (int)C->getZExtValue() >> 2, SDLoc(Op),
4133           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4134       .getNode();
4135 }
4136
4137 namespace {
4138
4139 struct TailCallArgumentInfo {
4140   SDValue Arg;
4141   SDValue FrameIdxOp;
4142   int       FrameIdx;
4143
4144   TailCallArgumentInfo() : FrameIdx(0) {}
4145 };
4146 }
4147
4148 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4149 static void StoreTailCallArgumentsToStackSlot(
4150     SelectionDAG &DAG, SDValue Chain,
4151     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4152     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4153   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4154     SDValue Arg = TailCallArgs[i].Arg;
4155     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4156     int FI = TailCallArgs[i].FrameIdx;
4157     // Store relative to framepointer.
4158     MemOpChains.push_back(DAG.getStore(
4159         Chain, dl, Arg, FIN,
4160         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4161   }
4162 }
4163
4164 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4165 /// the appropriate stack slot for the tail call optimized function call.
4166 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4167                                              SDValue OldRetAddr, SDValue OldFP,
4168                                              int SPDiff, const SDLoc &dl) {
4169   if (SPDiff) {
4170     // Calculate the new stack slot for the return address.
4171     MachineFunction &MF = DAG.getMachineFunction();
4172     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4173     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4174     bool isPPC64 = Subtarget.isPPC64();
4175     int SlotSize = isPPC64 ? 8 : 4;
4176     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4177     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
4178                                                           NewRetAddrLoc, true);
4179     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4180     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4181     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4182                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4183
4184     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4185     // slot as the FP is never overwritten.
4186     if (Subtarget.isDarwinABI()) {
4187       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4188       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
4189                                                           true);
4190       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4191       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4192                            MachinePointerInfo::getFixedStack(
4193                                DAG.getMachineFunction(), NewFPIdx));
4194     }
4195   }
4196   return Chain;
4197 }
4198
4199 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4200 /// the position of the argument.
4201 static void
4202 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4203                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4204                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4205   int Offset = ArgOffset + SPDiff;
4206   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4207   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
4208   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4209   SDValue FIN = DAG.getFrameIndex(FI, VT);
4210   TailCallArgumentInfo Info;
4211   Info.Arg = Arg;
4212   Info.FrameIdxOp = FIN;
4213   Info.FrameIdx = FI;
4214   TailCallArguments.push_back(Info);
4215 }
4216
4217 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4218 /// stack slot. Returns the chain as result and the loaded frame pointers in
4219 /// LROpOut/FPOpout. Used when tail calling.
4220 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4221     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4222     SDValue &FPOpOut, const SDLoc &dl) const {
4223   if (SPDiff) {
4224     // Load the LR and FP stack slot for later adjusting.
4225     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4226     LROpOut = getReturnAddrFrameIndex(DAG);
4227     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4228     Chain = SDValue(LROpOut.getNode(), 1);
4229
4230     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4231     // slot as the FP is never overwritten.
4232     if (Subtarget.isDarwinABI()) {
4233       FPOpOut = getFramePointerFrameIndex(DAG);
4234       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4235       Chain = SDValue(FPOpOut.getNode(), 1);
4236     }
4237   }
4238   return Chain;
4239 }
4240
4241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4242 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4243 /// specified by the specific parameter attribute. The copy will be passed as
4244 /// a byval function parameter.
4245 /// Sometimes what we are copying is the end of a larger object, the part that
4246 /// does not fit in registers.
4247 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4248                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4249                                          SelectionDAG &DAG, const SDLoc &dl) {
4250   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4251   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4252                        false, false, false, MachinePointerInfo(),
4253                        MachinePointerInfo());
4254 }
4255
4256 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4257 /// tail calls.
4258 static void LowerMemOpCallTo(
4259     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4260     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4261     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4262     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4263   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4264   if (!isTailCall) {
4265     if (isVector) {
4266       SDValue StackPtr;
4267       if (isPPC64)
4268         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4269       else
4270         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4271       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4272                            DAG.getConstant(ArgOffset, dl, PtrVT));
4273     }
4274     MemOpChains.push_back(
4275         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4276     // Calculate and remember argument location.
4277   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4278                                   TailCallArguments);
4279 }
4280
4281 static void
4282 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4283                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4284                 SDValue FPOp,
4285                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4286   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4287   // might overwrite each other in case of tail call optimization.
4288   SmallVector<SDValue, 8> MemOpChains2;
4289   // Do not flag preceding copytoreg stuff together with the following stuff.
4290   InFlag = SDValue();
4291   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4292                                     MemOpChains2, dl);
4293   if (!MemOpChains2.empty())
4294     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4295
4296   // Store the return address to the appropriate stack slot.
4297   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4298
4299   // Emit callseq_end just before tailcall node.
4300   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4301                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4302   InFlag = Chain.getValue(1);
4303 }
4304
4305 // Is this global address that of a function that can be called by name? (as
4306 // opposed to something that must hold a descriptor for an indirect call).
4307 static bool isFunctionGlobalAddress(SDValue Callee) {
4308   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4309     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4310         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4311       return false;
4312
4313     return G->getGlobal()->getValueType()->isFunctionTy();
4314   }
4315
4316   return false;
4317 }
4318
4319 static unsigned
4320 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4321             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4322             bool isPatchPoint, bool hasNest,
4323             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4324             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4325             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4326
4327   bool isPPC64 = Subtarget.isPPC64();
4328   bool isSVR4ABI = Subtarget.isSVR4ABI();
4329   bool isELFv2ABI = Subtarget.isELFv2ABI();
4330
4331   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4332   NodeTys.push_back(MVT::Other);   // Returns a chain
4333   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4334
4335   unsigned CallOpc = PPCISD::CALL;
4336
4337   bool needIndirectCall = true;
4338   if (!isSVR4ABI || !isPPC64)
4339     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4340       // If this is an absolute destination address, use the munged value.
4341       Callee = SDValue(Dest, 0);
4342       needIndirectCall = false;
4343     }
4344
4345   // PC-relative references to external symbols should go through $stub, unless
4346   // we're building with the leopard linker or later, which automatically
4347   // synthesizes these stubs.
4348   const TargetMachine &TM = DAG.getTarget();
4349   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4350   const GlobalValue *GV = nullptr;
4351   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4352     GV = G->getGlobal();
4353   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4354   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4355
4356   if (isFunctionGlobalAddress(Callee)) {
4357     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4358     // A call to a TLS address is actually an indirect call to a
4359     // thread-specific pointer.
4360     unsigned OpFlags = 0;
4361     if (UsePlt)
4362       OpFlags = PPCII::MO_PLT;
4363
4364     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4365     // every direct call is) turn it into a TargetGlobalAddress /
4366     // TargetExternalSymbol node so that legalize doesn't hack it.
4367     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4368                                         Callee.getValueType(), 0, OpFlags);
4369     needIndirectCall = false;
4370   }
4371
4372   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4373     unsigned char OpFlags = 0;
4374
4375     if (UsePlt)
4376       OpFlags = PPCII::MO_PLT;
4377
4378     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4379                                          OpFlags);
4380     needIndirectCall = false;
4381   }
4382
4383   if (isPatchPoint) {
4384     // We'll form an invalid direct call when lowering a patchpoint; the full
4385     // sequence for an indirect call is complicated, and many of the
4386     // instructions introduced might have side effects (and, thus, can't be
4387     // removed later). The call itself will be removed as soon as the
4388     // argument/return lowering is complete, so the fact that it has the wrong
4389     // kind of operands should not really matter.
4390     needIndirectCall = false;
4391   }
4392
4393   if (needIndirectCall) {
4394     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4395     // to do the call, we can't use PPCISD::CALL.
4396     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4397
4398     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4399       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4400       // entry point, but to the function descriptor (the function entry point
4401       // address is part of the function descriptor though).
4402       // The function descriptor is a three doubleword structure with the
4403       // following fields: function entry point, TOC base address and
4404       // environment pointer.
4405       // Thus for a call through a function pointer, the following actions need
4406       // to be performed:
4407       //   1. Save the TOC of the caller in the TOC save area of its stack
4408       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4409       //   2. Load the address of the function entry point from the function
4410       //      descriptor.
4411       //   3. Load the TOC of the callee from the function descriptor into r2.
4412       //   4. Load the environment pointer from the function descriptor into
4413       //      r11.
4414       //   5. Branch to the function entry point address.
4415       //   6. On return of the callee, the TOC of the caller needs to be
4416       //      restored (this is done in FinishCall()).
4417       //
4418       // The loads are scheduled at the beginning of the call sequence, and the
4419       // register copies are flagged together to ensure that no other
4420       // operations can be scheduled in between. E.g. without flagging the
4421       // copies together, a TOC access in the caller could be scheduled between
4422       // the assignment of the callee TOC and the branch to the callee, which
4423       // results in the TOC access going through the TOC of the callee instead
4424       // of going through the TOC of the caller, which leads to incorrect code.
4425
4426       // Load the address of the function entry point from the function
4427       // descriptor.
4428       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4429       if (LDChain.getValueType() == MVT::Glue)
4430         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4431
4432       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4433                           ? MachineMemOperand::MOInvariant
4434                           : MachineMemOperand::MONone;
4435
4436       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4437       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4438                                         /* Alignment = */ 8, MMOFlags);
4439
4440       // Load environment pointer into r11.
4441       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4442       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4443       SDValue LoadEnvPtr =
4444           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4445                       /* Alignment = */ 8, MMOFlags);
4446
4447       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4448       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4449       SDValue TOCPtr =
4450           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4451                       /* Alignment = */ 8, MMOFlags);
4452
4453       setUsesTOCBasePtr(DAG);
4454       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4455                                         InFlag);
4456       Chain = TOCVal.getValue(0);
4457       InFlag = TOCVal.getValue(1);
4458
4459       // If the function call has an explicit 'nest' parameter, it takes the
4460       // place of the environment pointer.
4461       if (!hasNest) {
4462         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4463                                           InFlag);
4464
4465         Chain = EnvVal.getValue(0);
4466         InFlag = EnvVal.getValue(1);
4467       }
4468
4469       MTCTROps[0] = Chain;
4470       MTCTROps[1] = LoadFuncPtr;
4471       MTCTROps[2] = InFlag;
4472     }
4473
4474     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4475                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4476     InFlag = Chain.getValue(1);
4477
4478     NodeTys.clear();
4479     NodeTys.push_back(MVT::Other);
4480     NodeTys.push_back(MVT::Glue);
4481     Ops.push_back(Chain);
4482     CallOpc = PPCISD::BCTRL;
4483     Callee.setNode(nullptr);
4484     // Add use of X11 (holding environment pointer)
4485     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4486       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4487     // Add CTR register as callee so a bctr can be emitted later.
4488     if (isTailCall)
4489       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4490   }
4491
4492   // If this is a direct call, pass the chain and the callee.
4493   if (Callee.getNode()) {
4494     Ops.push_back(Chain);
4495     Ops.push_back(Callee);
4496   }
4497   // If this is a tail call add stack pointer delta.
4498   if (isTailCall)
4499     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4500
4501   // Add argument registers to the end of the list so that they are known live
4502   // into the call.
4503   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4504     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4505                                   RegsToPass[i].second.getValueType()));
4506
4507   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4508   // into the call.
4509   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4510     setUsesTOCBasePtr(DAG);
4511     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4512   }
4513
4514   return CallOpc;
4515 }
4516
4517 static
4518 bool isLocalCall(const SDValue &Callee)
4519 {
4520   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4521     return G->getGlobal()->isStrongDefinitionForLinker();
4522   return false;
4523 }
4524
4525 SDValue PPCTargetLowering::LowerCallResult(
4526     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4527     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4528     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4529
4530   SmallVector<CCValAssign, 16> RVLocs;
4531   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4532                     *DAG.getContext());
4533   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4534
4535   // Copy all of the result registers out of their specified physreg.
4536   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4537     CCValAssign &VA = RVLocs[i];
4538     assert(VA.isRegLoc() && "Can only return in registers!");
4539
4540     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4541                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4542     Chain = Val.getValue(1);
4543     InFlag = Val.getValue(2);
4544
4545     switch (VA.getLocInfo()) {
4546     default: llvm_unreachable("Unknown loc info!");
4547     case CCValAssign::Full: break;
4548     case CCValAssign::AExt:
4549       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4550       break;
4551     case CCValAssign::ZExt:
4552       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4553                         DAG.getValueType(VA.getValVT()));
4554       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4555       break;
4556     case CCValAssign::SExt:
4557       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4558                         DAG.getValueType(VA.getValVT()));
4559       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4560       break;
4561     }
4562
4563     InVals.push_back(Val);
4564   }
4565
4566   return Chain;
4567 }
4568
4569 SDValue PPCTargetLowering::FinishCall(
4570     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4571     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4572     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4573     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4574     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4575     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4576
4577   std::vector<EVT> NodeTys;
4578   SmallVector<SDValue, 8> Ops;
4579   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4580                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4581                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4582
4583   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4584   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4585     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4586
4587   // When performing tail call optimization the callee pops its arguments off
4588   // the stack. Account for this here so these bytes can be pushed back on in
4589   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4590   int BytesCalleePops =
4591     (CallConv == CallingConv::Fast &&
4592      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4593
4594   // Add a register mask operand representing the call-preserved registers.
4595   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4596   const uint32_t *Mask =
4597       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4598   assert(Mask && "Missing call preserved mask for calling convention");
4599   Ops.push_back(DAG.getRegisterMask(Mask));
4600
4601   if (InFlag.getNode())
4602     Ops.push_back(InFlag);
4603
4604   // Emit tail call.
4605   if (isTailCall) {
4606     assert(((Callee.getOpcode() == ISD::Register &&
4607              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4608             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4609             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4610             isa<ConstantSDNode>(Callee)) &&
4611     "Expecting an global address, external symbol, absolute value or register");
4612
4613     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4614     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4615   }
4616
4617   // Add a NOP immediately after the branch instruction when using the 64-bit
4618   // SVR4 ABI. At link time, if caller and callee are in a different module and
4619   // thus have a different TOC, the call will be replaced with a call to a stub
4620   // function which saves the current TOC, loads the TOC of the callee and
4621   // branches to the callee. The NOP will be replaced with a load instruction
4622   // which restores the TOC of the caller from the TOC save slot of the current
4623   // stack frame. If caller and callee belong to the same module (and have the
4624   // same TOC), the NOP will remain unchanged.
4625
4626   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4627       !isPatchPoint) {
4628     if (CallOpc == PPCISD::BCTRL) {
4629       // This is a call through a function pointer.
4630       // Restore the caller TOC from the save area into R2.
4631       // See PrepareCall() for more information about calls through function
4632       // pointers in the 64-bit SVR4 ABI.
4633       // We are using a target-specific load with r2 hard coded, because the
4634       // result of a target-independent load would never go directly into r2,
4635       // since r2 is a reserved register (which prevents the register allocator
4636       // from allocating it), resulting in an additional register being
4637       // allocated and an unnecessary move instruction being generated.
4638       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4639
4640       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4641       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4642       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4643       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4644       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4645
4646       // The address needs to go after the chain input but before the flag (or
4647       // any other variadic arguments).
4648       Ops.insert(std::next(Ops.begin()), AddTOC);
4649     } else if ((CallOpc == PPCISD::CALL) &&
4650                (!isLocalCall(Callee) ||
4651                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4652       // Otherwise insert NOP for non-local calls.
4653       CallOpc = PPCISD::CALL_NOP;
4654   }
4655
4656   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4657   InFlag = Chain.getValue(1);
4658
4659   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4660                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4661                              InFlag, dl);
4662   if (!Ins.empty())
4663     InFlag = Chain.getValue(1);
4664
4665   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4666                          Ins, dl, DAG, InVals);
4667 }
4668
4669 SDValue
4670 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4671                              SmallVectorImpl<SDValue> &InVals) const {
4672   SelectionDAG &DAG                     = CLI.DAG;
4673   SDLoc &dl                             = CLI.DL;
4674   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4675   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4676   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4677   SDValue Chain                         = CLI.Chain;
4678   SDValue Callee                        = CLI.Callee;
4679   bool &isTailCall                      = CLI.IsTailCall;
4680   CallingConv::ID CallConv              = CLI.CallConv;
4681   bool isVarArg                         = CLI.IsVarArg;
4682   bool isPatchPoint                     = CLI.IsPatchPoint;
4683   ImmutableCallSite *CS                 = CLI.CS;
4684
4685   if (isTailCall) {
4686     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4687       isTailCall = false;
4688     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4689       isTailCall =
4690         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4691                                                  isVarArg, Outs, Ins, DAG);
4692     else
4693       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4694                                                      Ins, DAG);
4695     if (isTailCall) {
4696       ++NumTailCalls;
4697       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4698         ++NumSiblingCalls;
4699
4700       assert(isa<GlobalAddressSDNode>(Callee) &&
4701              "Callee should be an llvm::Function object.");
4702       DEBUG(
4703         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4704         const unsigned Width = 80 - strlen("TCO caller: ")
4705                                   - strlen(", callee linkage: 0, 0");
4706         dbgs() << "TCO caller: "
4707                << left_justify(DAG.getMachineFunction().getName(), Width)
4708                << ", callee linkage: "
4709                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4710       );
4711     }
4712   }
4713
4714   if (!isTailCall && CS && CS->isMustTailCall())
4715     report_fatal_error("failed to perform tail call elimination on a call "
4716                        "site marked musttail");
4717
4718   // When long calls (i.e. indirect calls) are always used, calls are always
4719   // made via function pointer. If we have a function name, first translate it
4720   // into a pointer.
4721   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4722       !isTailCall)
4723     Callee = LowerGlobalAddress(Callee, DAG);
4724
4725   if (Subtarget.isSVR4ABI()) {
4726     if (Subtarget.isPPC64())
4727       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4728                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4729                               dl, DAG, InVals, CS);
4730     else
4731       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4732                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4733                               dl, DAG, InVals, CS);
4734   }
4735
4736   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4737                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4738                           dl, DAG, InVals, CS);
4739 }
4740
4741 SDValue PPCTargetLowering::LowerCall_32SVR4(
4742     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4743     bool isTailCall, bool isPatchPoint,
4744     const SmallVectorImpl<ISD::OutputArg> &Outs,
4745     const SmallVectorImpl<SDValue> &OutVals,
4746     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4747     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4748     ImmutableCallSite *CS) const {
4749   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4750   // of the 32-bit SVR4 ABI stack frame layout.
4751
4752   assert((CallConv == CallingConv::C ||
4753           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4754
4755   unsigned PtrByteSize = 4;
4756
4757   MachineFunction &MF = DAG.getMachineFunction();
4758
4759   // Mark this function as potentially containing a function that contains a
4760   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4761   // and restoring the callers stack pointer in this functions epilog. This is
4762   // done because by tail calling the called function might overwrite the value
4763   // in this function's (MF) stack pointer stack slot 0(SP).
4764   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4765       CallConv == CallingConv::Fast)
4766     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4767
4768   // Count how many bytes are to be pushed on the stack, including the linkage
4769   // area, parameter list area and the part of the local variable space which
4770   // contains copies of aggregates which are passed by value.
4771
4772   // Assign locations to all of the outgoing arguments.
4773   SmallVector<CCValAssign, 16> ArgLocs;
4774   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4775
4776   // Reserve space for the linkage area on the stack.
4777   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4778                        PtrByteSize);
4779   if (useSoftFloat())
4780     CCInfo.PreAnalyzeCallOperands(Outs);
4781
4782   if (isVarArg) {
4783     // Handle fixed and variable vector arguments differently.
4784     // Fixed vector arguments go into registers as long as registers are
4785     // available. Variable vector arguments always go into memory.
4786     unsigned NumArgs = Outs.size();
4787
4788     for (unsigned i = 0; i != NumArgs; ++i) {
4789       MVT ArgVT = Outs[i].VT;
4790       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4791       bool Result;
4792
4793       if (Outs[i].IsFixed) {
4794         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4795                                CCInfo);
4796       } else {
4797         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4798                                       ArgFlags, CCInfo);
4799       }
4800
4801       if (Result) {
4802 #ifndef NDEBUG
4803         errs() << "Call operand #" << i << " has unhandled type "
4804              << EVT(ArgVT).getEVTString() << "\n";
4805 #endif
4806         llvm_unreachable(nullptr);
4807       }
4808     }
4809   } else {
4810     // All arguments are treated the same.
4811     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4812   }
4813   CCInfo.clearWasPPCF128();
4814
4815   // Assign locations to all of the outgoing aggregate by value arguments.
4816   SmallVector<CCValAssign, 16> ByValArgLocs;
4817   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4818
4819   // Reserve stack space for the allocations in CCInfo.
4820   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4821
4822   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4823
4824   // Size of the linkage area, parameter list area and the part of the local
4825   // space variable where copies of aggregates which are passed by value are
4826   // stored.
4827   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4828
4829   // Calculate by how many bytes the stack has to be adjusted in case of tail
4830   // call optimization.
4831   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4832
4833   // Adjust the stack pointer for the new arguments...
4834   // These operations are automatically eliminated by the prolog/epilog pass
4835   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4836                                dl);
4837   SDValue CallSeqStart = Chain;
4838
4839   // Load the return address and frame pointer so it can be moved somewhere else
4840   // later.
4841   SDValue LROp, FPOp;
4842   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4843
4844   // Set up a copy of the stack pointer for use loading and storing any
4845   // arguments that may not fit in the registers available for argument
4846   // passing.
4847   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4848
4849   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4850   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4851   SmallVector<SDValue, 8> MemOpChains;
4852
4853   bool seenFloatArg = false;
4854   // Walk the register/memloc assignments, inserting copies/loads.
4855   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4856        i != e;
4857        ++i) {
4858     CCValAssign &VA = ArgLocs[i];
4859     SDValue Arg = OutVals[i];
4860     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4861
4862     if (Flags.isByVal()) {
4863       // Argument is an aggregate which is passed by value, thus we need to
4864       // create a copy of it in the local variable space of the current stack
4865       // frame (which is the stack frame of the caller) and pass the address of
4866       // this copy to the callee.
4867       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4868       CCValAssign &ByValVA = ByValArgLocs[j++];
4869       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4870
4871       // Memory reserved in the local variable space of the callers stack frame.
4872       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4873
4874       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4875       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4876                            StackPtr, PtrOff);
4877
4878       // Create a copy of the argument in the local area of the current
4879       // stack frame.
4880       SDValue MemcpyCall =
4881         CreateCopyOfByValArgument(Arg, PtrOff,
4882                                   CallSeqStart.getNode()->getOperand(0),
4883                                   Flags, DAG, dl);
4884
4885       // This must go outside the CALLSEQ_START..END.
4886       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4887                            CallSeqStart.getNode()->getOperand(1),
4888                            SDLoc(MemcpyCall));
4889       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4890                              NewCallSeqStart.getNode());
4891       Chain = CallSeqStart = NewCallSeqStart;
4892
4893       // Pass the address of the aggregate copy on the stack either in a
4894       // physical register or in the parameter list area of the current stack
4895       // frame to the callee.
4896       Arg = PtrOff;
4897     }
4898
4899     if (VA.isRegLoc()) {
4900       if (Arg.getValueType() == MVT::i1)
4901         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4902
4903       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4904       // Put argument in a physical register.
4905       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4906     } else {
4907       // Put argument in the parameter list area of the current stack frame.
4908       assert(VA.isMemLoc());
4909       unsigned LocMemOffset = VA.getLocMemOffset();
4910
4911       if (!isTailCall) {
4912         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4913         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4914                              StackPtr, PtrOff);
4915
4916         MemOpChains.push_back(
4917             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4918       } else {
4919         // Calculate and remember argument location.
4920         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4921                                  TailCallArguments);
4922       }
4923     }
4924   }
4925
4926   if (!MemOpChains.empty())
4927     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4928
4929   // Build a sequence of copy-to-reg nodes chained together with token chain
4930   // and flag operands which copy the outgoing args into the appropriate regs.
4931   SDValue InFlag;
4932   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4933     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4934                              RegsToPass[i].second, InFlag);
4935     InFlag = Chain.getValue(1);
4936   }
4937
4938   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4939   // registers.
4940   if (isVarArg) {
4941     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4942     SDValue Ops[] = { Chain, InFlag };
4943
4944     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4945                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4946
4947     InFlag = Chain.getValue(1);
4948   }
4949
4950   if (isTailCall)
4951     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
4952                     TailCallArguments);
4953
4954   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
4955                     /* unused except on PPC64 ELFv1 */ false, DAG,
4956                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4957                     NumBytes, Ins, InVals, CS);
4958 }
4959
4960 // Copy an argument into memory, being careful to do this outside the
4961 // call sequence for the call to which the argument belongs.
4962 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4963     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4964     SelectionDAG &DAG, const SDLoc &dl) const {
4965   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4966                         CallSeqStart.getNode()->getOperand(0),
4967                         Flags, DAG, dl);
4968   // The MEMCPY must go outside the CALLSEQ_START..END.
4969   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4970                              CallSeqStart.getNode()->getOperand(1),
4971                              SDLoc(MemcpyCall));
4972   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4973                          NewCallSeqStart.getNode());
4974   return NewCallSeqStart;
4975 }
4976
4977 SDValue PPCTargetLowering::LowerCall_64SVR4(
4978     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4979     bool isTailCall, bool isPatchPoint,
4980     const SmallVectorImpl<ISD::OutputArg> &Outs,
4981     const SmallVectorImpl<SDValue> &OutVals,
4982     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4983     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4984     ImmutableCallSite *CS) const {
4985
4986   bool isELFv2ABI = Subtarget.isELFv2ABI();
4987   bool isLittleEndian = Subtarget.isLittleEndian();
4988   unsigned NumOps = Outs.size();
4989   bool hasNest = false;
4990   bool IsSibCall = false;
4991
4992   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4993   unsigned PtrByteSize = 8;
4994
4995   MachineFunction &MF = DAG.getMachineFunction();
4996
4997   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
4998     IsSibCall = true;
4999
5000   // Mark this function as potentially containing a function that contains a
5001   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5002   // and restoring the callers stack pointer in this functions epilog. This is
5003   // done because by tail calling the called function might overwrite the value
5004   // in this function's (MF) stack pointer stack slot 0(SP).
5005   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5006       CallConv == CallingConv::Fast)
5007     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5008
5009   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5010          "fastcc not supported on varargs functions");
5011
5012   // Count how many bytes are to be pushed on the stack, including the linkage
5013   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5014   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5015   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5016   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5017   unsigned NumBytes = LinkageSize;
5018   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5019   unsigned &QFPR_idx = FPR_idx;
5020
5021   static const MCPhysReg GPR[] = {
5022     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5023     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5024   };
5025   static const MCPhysReg VR[] = {
5026     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5027     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5028   };
5029   static const MCPhysReg VSRH[] = {
5030     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
5031     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
5032   };
5033
5034   const unsigned NumGPRs = array_lengthof(GPR);
5035   const unsigned NumFPRs = 13;
5036   const unsigned NumVRs  = array_lengthof(VR);
5037   const unsigned NumQFPRs = NumFPRs;
5038
5039   // When using the fast calling convention, we don't provide backing for
5040   // arguments that will be in registers.
5041   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5042
5043   // Add up all the space actually used.
5044   for (unsigned i = 0; i != NumOps; ++i) {
5045     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5046     EVT ArgVT = Outs[i].VT;
5047     EVT OrigVT = Outs[i].ArgVT;
5048
5049     if (Flags.isNest())
5050       continue;
5051
5052     if (CallConv == CallingConv::Fast) {
5053       if (Flags.isByVal())
5054         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5055       else
5056         switch (ArgVT.getSimpleVT().SimpleTy) {
5057         default: llvm_unreachable("Unexpected ValueType for argument!");
5058         case MVT::i1:
5059         case MVT::i32:
5060         case MVT::i64:
5061           if (++NumGPRsUsed <= NumGPRs)
5062             continue;
5063           break;
5064         case MVT::v4i32:
5065         case MVT::v8i16:
5066         case MVT::v16i8:
5067         case MVT::v2f64:
5068         case MVT::v2i64:
5069         case MVT::v1i128:
5070           if (++NumVRsUsed <= NumVRs)
5071             continue;
5072           break;
5073         case MVT::v4f32:
5074           // When using QPX, this is handled like a FP register, otherwise, it
5075           // is an Altivec register.
5076           if (Subtarget.hasQPX()) {
5077             if (++NumFPRsUsed <= NumFPRs)
5078               continue;
5079           } else {
5080             if (++NumVRsUsed <= NumVRs)
5081               continue;
5082           }
5083           break;
5084         case MVT::f32:
5085         case MVT::f64:
5086         case MVT::v4f64: // QPX
5087         case MVT::v4i1:  // QPX
5088           if (++NumFPRsUsed <= NumFPRs)
5089             continue;
5090           break;
5091         }
5092     }
5093
5094     /* Respect alignment of argument on the stack.  */
5095     unsigned Align =
5096       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5097     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5098
5099     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5100     if (Flags.isInConsecutiveRegsLast())
5101       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5102   }
5103
5104   unsigned NumBytesActuallyUsed = NumBytes;
5105
5106   // The prolog code of the callee may store up to 8 GPR argument registers to
5107   // the stack, allowing va_start to index over them in memory if its varargs.
5108   // Because we cannot tell if this is needed on the caller side, we have to
5109   // conservatively assume that it is needed.  As such, make sure we have at
5110   // least enough stack space for the caller to store the 8 GPRs.
5111   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5112   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5113
5114   // Tail call needs the stack to be aligned.
5115   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5116       CallConv == CallingConv::Fast)
5117     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5118
5119   int SPDiff = 0;
5120
5121   // Calculate by how many bytes the stack has to be adjusted in case of tail
5122   // call optimization.
5123   if (!IsSibCall)
5124     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5125
5126   // To protect arguments on the stack from being clobbered in a tail call,
5127   // force all the loads to happen before doing any other lowering.
5128   if (isTailCall)
5129     Chain = DAG.getStackArgumentTokenFactor(Chain);
5130
5131   // Adjust the stack pointer for the new arguments...
5132   // These operations are automatically eliminated by the prolog/epilog pass
5133   if (!IsSibCall)
5134     Chain = DAG.getCALLSEQ_START(Chain,
5135                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5136   SDValue CallSeqStart = Chain;
5137
5138   // Load the return address and frame pointer so it can be move somewhere else
5139   // later.
5140   SDValue LROp, FPOp;
5141   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5142
5143   // Set up a copy of the stack pointer for use loading and storing any
5144   // arguments that may not fit in the registers available for argument
5145   // passing.
5146   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5147
5148   // Figure out which arguments are going to go in registers, and which in
5149   // memory.  Also, if this is a vararg function, floating point operations
5150   // must be stored to our stack, and loaded into integer regs as well, if
5151   // any integer regs are available for argument passing.
5152   unsigned ArgOffset = LinkageSize;
5153
5154   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5155   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5156
5157   SmallVector<SDValue, 8> MemOpChains;
5158   for (unsigned i = 0; i != NumOps; ++i) {
5159     SDValue Arg = OutVals[i];
5160     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5161     EVT ArgVT = Outs[i].VT;
5162     EVT OrigVT = Outs[i].ArgVT;
5163
5164     // PtrOff will be used to store the current argument to the stack if a
5165     // register cannot be found for it.
5166     SDValue PtrOff;
5167
5168     // We re-align the argument offset for each argument, except when using the
5169     // fast calling convention, when we need to make sure we do that only when
5170     // we'll actually use a stack slot.
5171     auto ComputePtrOff = [&]() {
5172       /* Respect alignment of argument on the stack.  */
5173       unsigned Align =
5174         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5175       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5176
5177       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5178
5179       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5180     };
5181
5182     if (CallConv != CallingConv::Fast) {
5183       ComputePtrOff();
5184
5185       /* Compute GPR index associated with argument offset.  */
5186       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5187       GPR_idx = std::min(GPR_idx, NumGPRs);
5188     }
5189
5190     // Promote integers to 64-bit values.
5191     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5192       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5193       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5194       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5195     }
5196
5197     // FIXME memcpy is used way more than necessary.  Correctness first.
5198     // Note: "by value" is code for passing a structure by value, not
5199     // basic types.
5200     if (Flags.isByVal()) {
5201       // Note: Size includes alignment padding, so
5202       //   struct x { short a; char b; }
5203       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5204       // These are the proper values we need for right-justifying the
5205       // aggregate in a parameter register.
5206       unsigned Size = Flags.getByValSize();
5207
5208       // An empty aggregate parameter takes up no storage and no
5209       // registers.
5210       if (Size == 0)
5211         continue;
5212
5213       if (CallConv == CallingConv::Fast)
5214         ComputePtrOff();
5215
5216       // All aggregates smaller than 8 bytes must be passed right-justified.
5217       if (Size==1 || Size==2 || Size==4) {
5218         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5219         if (GPR_idx != NumGPRs) {
5220           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5221                                         MachinePointerInfo(), VT);
5222           MemOpChains.push_back(Load.getValue(1));
5223           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5224
5225           ArgOffset += PtrByteSize;
5226           continue;
5227         }
5228       }
5229
5230       if (GPR_idx == NumGPRs && Size < 8) {
5231         SDValue AddPtr = PtrOff;
5232         if (!isLittleEndian) {
5233           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5234                                           PtrOff.getValueType());
5235           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5236         }
5237         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5238                                                           CallSeqStart,
5239                                                           Flags, DAG, dl);
5240         ArgOffset += PtrByteSize;
5241         continue;
5242       }
5243       // Copy entire object into memory.  There are cases where gcc-generated
5244       // code assumes it is there, even if it could be put entirely into
5245       // registers.  (This is not what the doc says.)
5246
5247       // FIXME: The above statement is likely due to a misunderstanding of the
5248       // documents.  All arguments must be copied into the parameter area BY
5249       // THE CALLEE in the event that the callee takes the address of any
5250       // formal argument.  That has not yet been implemented.  However, it is
5251       // reasonable to use the stack area as a staging area for the register
5252       // load.
5253
5254       // Skip this for small aggregates, as we will use the same slot for a
5255       // right-justified copy, below.
5256       if (Size >= 8)
5257         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5258                                                           CallSeqStart,
5259                                                           Flags, DAG, dl);
5260
5261       // When a register is available, pass a small aggregate right-justified.
5262       if (Size < 8 && GPR_idx != NumGPRs) {
5263         // The easiest way to get this right-justified in a register
5264         // is to copy the structure into the rightmost portion of a
5265         // local variable slot, then load the whole slot into the
5266         // register.
5267         // FIXME: The memcpy seems to produce pretty awful code for
5268         // small aggregates, particularly for packed ones.
5269         // FIXME: It would be preferable to use the slot in the
5270         // parameter save area instead of a new local variable.
5271         SDValue AddPtr = PtrOff;
5272         if (!isLittleEndian) {
5273           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5274           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5275         }
5276         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5277                                                           CallSeqStart,
5278                                                           Flags, DAG, dl);
5279
5280         // Load the slot into the register.
5281         SDValue Load =
5282             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5283         MemOpChains.push_back(Load.getValue(1));
5284         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5285
5286         // Done with this argument.
5287         ArgOffset += PtrByteSize;
5288         continue;
5289       }
5290
5291       // For aggregates larger than PtrByteSize, copy the pieces of the
5292       // object that fit into registers from the parameter save area.
5293       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5294         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5295         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5296         if (GPR_idx != NumGPRs) {
5297           SDValue Load =
5298               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5299           MemOpChains.push_back(Load.getValue(1));
5300           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5301           ArgOffset += PtrByteSize;
5302         } else {
5303           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5304           break;
5305         }
5306       }
5307       continue;
5308     }
5309
5310     switch (Arg.getSimpleValueType().SimpleTy) {
5311     default: llvm_unreachable("Unexpected ValueType for argument!");
5312     case MVT::i1:
5313     case MVT::i32:
5314     case MVT::i64:
5315       if (Flags.isNest()) {
5316         // The 'nest' parameter, if any, is passed in R11.
5317         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5318         hasNest = true;
5319         break;
5320       }
5321
5322       // These can be scalar arguments or elements of an integer array type
5323       // passed directly.  Clang may use those instead of "byval" aggregate
5324       // types to avoid forcing arguments to memory unnecessarily.
5325       if (GPR_idx != NumGPRs) {
5326         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5327       } else {
5328         if (CallConv == CallingConv::Fast)
5329           ComputePtrOff();
5330
5331         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5332                          true, isTailCall, false, MemOpChains,
5333                          TailCallArguments, dl);
5334         if (CallConv == CallingConv::Fast)
5335           ArgOffset += PtrByteSize;
5336       }
5337       if (CallConv != CallingConv::Fast)
5338         ArgOffset += PtrByteSize;
5339       break;
5340     case MVT::f32:
5341     case MVT::f64: {
5342       // These can be scalar arguments or elements of a float array type
5343       // passed directly.  The latter are used to implement ELFv2 homogenous
5344       // float aggregates.
5345
5346       // Named arguments go into FPRs first, and once they overflow, the
5347       // remaining arguments go into GPRs and then the parameter save area.
5348       // Unnamed arguments for vararg functions always go to GPRs and
5349       // then the parameter save area.  For now, put all arguments to vararg
5350       // routines always in both locations (FPR *and* GPR or stack slot).
5351       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5352       bool NeededLoad = false;
5353
5354       // First load the argument into the next available FPR.
5355       if (FPR_idx != NumFPRs)
5356         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5357
5358       // Next, load the argument into GPR or stack slot if needed.
5359       if (!NeedGPROrStack)
5360         ;
5361       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5362         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5363         // once we support fp <-> gpr moves.
5364
5365         // In the non-vararg case, this can only ever happen in the
5366         // presence of f32 array types, since otherwise we never run
5367         // out of FPRs before running out of GPRs.
5368         SDValue ArgVal;
5369
5370         // Double values are always passed in a single GPR.
5371         if (Arg.getValueType() != MVT::f32) {
5372           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5373
5374         // Non-array float values are extended and passed in a GPR.
5375         } else if (!Flags.isInConsecutiveRegs()) {
5376           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5377           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5378
5379         // If we have an array of floats, we collect every odd element
5380         // together with its predecessor into one GPR.
5381         } else if (ArgOffset % PtrByteSize != 0) {
5382           SDValue Lo, Hi;
5383           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5384           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5385           if (!isLittleEndian)
5386             std::swap(Lo, Hi);
5387           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5388
5389         // The final element, if even, goes into the first half of a GPR.
5390         } else if (Flags.isInConsecutiveRegsLast()) {
5391           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5392           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5393           if (!isLittleEndian)
5394             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5395                                  DAG.getConstant(32, dl, MVT::i32));
5396
5397         // Non-final even elements are skipped; they will be handled
5398         // together the with subsequent argument on the next go-around.
5399         } else
5400           ArgVal = SDValue();
5401
5402         if (ArgVal.getNode())
5403           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5404       } else {
5405         if (CallConv == CallingConv::Fast)
5406           ComputePtrOff();
5407
5408         // Single-precision floating-point values are mapped to the
5409         // second (rightmost) word of the stack doubleword.
5410         if (Arg.getValueType() == MVT::f32 &&
5411             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5412           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5413           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5414         }
5415
5416         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5417                          true, isTailCall, false, MemOpChains,
5418                          TailCallArguments, dl);
5419
5420         NeededLoad = true;
5421       }
5422       // When passing an array of floats, the array occupies consecutive
5423       // space in the argument area; only round up to the next doubleword
5424       // at the end of the array.  Otherwise, each float takes 8 bytes.
5425       if (CallConv != CallingConv::Fast || NeededLoad) {
5426         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5427                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5428         if (Flags.isInConsecutiveRegsLast())
5429           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5430       }
5431       break;
5432     }
5433     case MVT::v4f32:
5434     case MVT::v4i32:
5435     case MVT::v8i16:
5436     case MVT::v16i8:
5437     case MVT::v2f64:
5438     case MVT::v2i64:
5439     case MVT::v1i128:
5440       if (!Subtarget.hasQPX()) {
5441       // These can be scalar arguments or elements of a vector array type
5442       // passed directly.  The latter are used to implement ELFv2 homogenous
5443       // vector aggregates.
5444
5445       // For a varargs call, named arguments go into VRs or on the stack as
5446       // usual; unnamed arguments always go to the stack or the corresponding
5447       // GPRs when within range.  For now, we always put the value in both
5448       // locations (or even all three).
5449       if (isVarArg) {
5450         // We could elide this store in the case where the object fits
5451         // entirely in R registers.  Maybe later.
5452         SDValue Store =
5453             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5454         MemOpChains.push_back(Store);
5455         if (VR_idx != NumVRs) {
5456           SDValue Load =
5457               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5458           MemOpChains.push_back(Load.getValue(1));
5459
5460           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5461                            Arg.getSimpleValueType() == MVT::v2i64) ?
5462                           VSRH[VR_idx] : VR[VR_idx];
5463           ++VR_idx;
5464
5465           RegsToPass.push_back(std::make_pair(VReg, Load));
5466         }
5467         ArgOffset += 16;
5468         for (unsigned i=0; i<16; i+=PtrByteSize) {
5469           if (GPR_idx == NumGPRs)
5470             break;
5471           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5472                                    DAG.getConstant(i, dl, PtrVT));
5473           SDValue Load =
5474               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5475           MemOpChains.push_back(Load.getValue(1));
5476           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5477         }
5478         break;
5479       }
5480
5481       // Non-varargs Altivec params go into VRs or on the stack.
5482       if (VR_idx != NumVRs) {
5483         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5484                          Arg.getSimpleValueType() == MVT::v2i64) ?
5485                         VSRH[VR_idx] : VR[VR_idx];
5486         ++VR_idx;
5487
5488         RegsToPass.push_back(std::make_pair(VReg, Arg));
5489       } else {
5490         if (CallConv == CallingConv::Fast)
5491           ComputePtrOff();
5492
5493         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5494                          true, isTailCall, true, MemOpChains,
5495                          TailCallArguments, dl);
5496         if (CallConv == CallingConv::Fast)
5497           ArgOffset += 16;
5498       }
5499
5500       if (CallConv != CallingConv::Fast)
5501         ArgOffset += 16;
5502       break;
5503       } // not QPX
5504
5505       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5506              "Invalid QPX parameter type");
5507
5508       /* fall through */
5509     case MVT::v4f64:
5510     case MVT::v4i1: {
5511       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5512       if (isVarArg) {
5513         // We could elide this store in the case where the object fits
5514         // entirely in R registers.  Maybe later.
5515         SDValue Store =
5516             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5517         MemOpChains.push_back(Store);
5518         if (QFPR_idx != NumQFPRs) {
5519           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5520                                      PtrOff, MachinePointerInfo());
5521           MemOpChains.push_back(Load.getValue(1));
5522           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5523         }
5524         ArgOffset += (IsF32 ? 16 : 32);
5525         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5526           if (GPR_idx == NumGPRs)
5527             break;
5528           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5529                                    DAG.getConstant(i, dl, PtrVT));
5530           SDValue Load =
5531               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5532           MemOpChains.push_back(Load.getValue(1));
5533           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5534         }
5535         break;
5536       }
5537
5538       // Non-varargs QPX params go into registers or on the stack.
5539       if (QFPR_idx != NumQFPRs) {
5540         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5541       } else {
5542         if (CallConv == CallingConv::Fast)
5543           ComputePtrOff();
5544
5545         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5546                          true, isTailCall, true, MemOpChains,
5547                          TailCallArguments, dl);
5548         if (CallConv == CallingConv::Fast)
5549           ArgOffset += (IsF32 ? 16 : 32);
5550       }
5551
5552       if (CallConv != CallingConv::Fast)
5553         ArgOffset += (IsF32 ? 16 : 32);
5554       break;
5555       }
5556     }
5557   }
5558
5559   assert(NumBytesActuallyUsed == ArgOffset);
5560   (void)NumBytesActuallyUsed;
5561
5562   if (!MemOpChains.empty())
5563     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5564
5565   // Check if this is an indirect call (MTCTR/BCTRL).
5566   // See PrepareCall() for more information about calls through function
5567   // pointers in the 64-bit SVR4 ABI.
5568   if (!isTailCall && !isPatchPoint &&
5569       !isFunctionGlobalAddress(Callee) &&
5570       !isa<ExternalSymbolSDNode>(Callee)) {
5571     // Load r2 into a virtual register and store it to the TOC save area.
5572     setUsesTOCBasePtr(DAG);
5573     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5574     // TOC save area offset.
5575     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5576     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5577     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5578     Chain = DAG.getStore(
5579         Val.getValue(1), dl, Val, AddPtr,
5580         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5581     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5582     // This does not mean the MTCTR instruction must use R12; it's easier
5583     // to model this as an extra parameter, so do that.
5584     if (isELFv2ABI && !isPatchPoint)
5585       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5586   }
5587
5588   // Build a sequence of copy-to-reg nodes chained together with token chain
5589   // and flag operands which copy the outgoing args into the appropriate regs.
5590   SDValue InFlag;
5591   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5592     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5593                              RegsToPass[i].second, InFlag);
5594     InFlag = Chain.getValue(1);
5595   }
5596
5597   if (isTailCall && !IsSibCall)
5598     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5599                     TailCallArguments);
5600
5601   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5602                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5603                     SPDiff, NumBytes, Ins, InVals, CS);
5604 }
5605
5606 SDValue PPCTargetLowering::LowerCall_Darwin(
5607     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5608     bool isTailCall, bool isPatchPoint,
5609     const SmallVectorImpl<ISD::OutputArg> &Outs,
5610     const SmallVectorImpl<SDValue> &OutVals,
5611     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5612     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5613     ImmutableCallSite *CS) const {
5614
5615   unsigned NumOps = Outs.size();
5616
5617   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5618   bool isPPC64 = PtrVT == MVT::i64;
5619   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5620
5621   MachineFunction &MF = DAG.getMachineFunction();
5622
5623   // Mark this function as potentially containing a function that contains a
5624   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5625   // and restoring the callers stack pointer in this functions epilog. This is
5626   // done because by tail calling the called function might overwrite the value
5627   // in this function's (MF) stack pointer stack slot 0(SP).
5628   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5629       CallConv == CallingConv::Fast)
5630     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5631
5632   // Count how many bytes are to be pushed on the stack, including the linkage
5633   // area, and parameter passing area.  We start with 24/48 bytes, which is
5634   // prereserved space for [SP][CR][LR][3 x unused].
5635   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5636   unsigned NumBytes = LinkageSize;
5637
5638   // Add up all the space actually used.
5639   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5640   // they all go in registers, but we must reserve stack space for them for
5641   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5642   // assigned stack space in order, with padding so Altivec parameters are
5643   // 16-byte aligned.
5644   unsigned nAltivecParamsAtEnd = 0;
5645   for (unsigned i = 0; i != NumOps; ++i) {
5646     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5647     EVT ArgVT = Outs[i].VT;
5648     // Varargs Altivec parameters are padded to a 16 byte boundary.
5649     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5650         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5651         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5652       if (!isVarArg && !isPPC64) {
5653         // Non-varargs Altivec parameters go after all the non-Altivec
5654         // parameters; handle those later so we know how much padding we need.
5655         nAltivecParamsAtEnd++;
5656         continue;
5657       }
5658       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5659       NumBytes = ((NumBytes+15)/16)*16;
5660     }
5661     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5662   }
5663
5664   // Allow for Altivec parameters at the end, if needed.
5665   if (nAltivecParamsAtEnd) {
5666     NumBytes = ((NumBytes+15)/16)*16;
5667     NumBytes += 16*nAltivecParamsAtEnd;
5668   }
5669
5670   // The prolog code of the callee may store up to 8 GPR argument registers to
5671   // the stack, allowing va_start to index over them in memory if its varargs.
5672   // Because we cannot tell if this is needed on the caller side, we have to
5673   // conservatively assume that it is needed.  As such, make sure we have at
5674   // least enough stack space for the caller to store the 8 GPRs.
5675   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5676
5677   // Tail call needs the stack to be aligned.
5678   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5679       CallConv == CallingConv::Fast)
5680     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5681
5682   // Calculate by how many bytes the stack has to be adjusted in case of tail
5683   // call optimization.
5684   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5685
5686   // To protect arguments on the stack from being clobbered in a tail call,
5687   // force all the loads to happen before doing any other lowering.
5688   if (isTailCall)
5689     Chain = DAG.getStackArgumentTokenFactor(Chain);
5690
5691   // Adjust the stack pointer for the new arguments...
5692   // These operations are automatically eliminated by the prolog/epilog pass
5693   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5694                                dl);
5695   SDValue CallSeqStart = Chain;
5696
5697   // Load the return address and frame pointer so it can be move somewhere else
5698   // later.
5699   SDValue LROp, FPOp;
5700   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5701
5702   // Set up a copy of the stack pointer for use loading and storing any
5703   // arguments that may not fit in the registers available for argument
5704   // passing.
5705   SDValue StackPtr;
5706   if (isPPC64)
5707     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5708   else
5709     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5710
5711   // Figure out which arguments are going to go in registers, and which in
5712   // memory.  Also, if this is a vararg function, floating point operations
5713   // must be stored to our stack, and loaded into integer regs as well, if
5714   // any integer regs are available for argument passing.
5715   unsigned ArgOffset = LinkageSize;
5716   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5717
5718   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5719     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5720     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5721   };
5722   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5723     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5724     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5725   };
5726   static const MCPhysReg VR[] = {
5727     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5728     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5729   };
5730   const unsigned NumGPRs = array_lengthof(GPR_32);
5731   const unsigned NumFPRs = 13;
5732   const unsigned NumVRs  = array_lengthof(VR);
5733
5734   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5735
5736   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5737   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5738
5739   SmallVector<SDValue, 8> MemOpChains;
5740   for (unsigned i = 0; i != NumOps; ++i) {
5741     SDValue Arg = OutVals[i];
5742     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5743
5744     // PtrOff will be used to store the current argument to the stack if a
5745     // register cannot be found for it.
5746     SDValue PtrOff;
5747
5748     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5749
5750     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5751
5752     // On PPC64, promote integers to 64-bit values.
5753     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5754       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5755       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5756       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5757     }
5758
5759     // FIXME memcpy is used way more than necessary.  Correctness first.
5760     // Note: "by value" is code for passing a structure by value, not
5761     // basic types.
5762     if (Flags.isByVal()) {
5763       unsigned Size = Flags.getByValSize();
5764       // Very small objects are passed right-justified.  Everything else is
5765       // passed left-justified.
5766       if (Size==1 || Size==2) {
5767         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5768         if (GPR_idx != NumGPRs) {
5769           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5770                                         MachinePointerInfo(), VT);
5771           MemOpChains.push_back(Load.getValue(1));
5772           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5773
5774           ArgOffset += PtrByteSize;
5775         } else {
5776           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5777                                           PtrOff.getValueType());
5778           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5779           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5780                                                             CallSeqStart,
5781                                                             Flags, DAG, dl);
5782           ArgOffset += PtrByteSize;
5783         }
5784         continue;
5785       }
5786       // Copy entire object into memory.  There are cases where gcc-generated
5787       // code assumes it is there, even if it could be put entirely into
5788       // registers.  (This is not what the doc says.)
5789       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5790                                                         CallSeqStart,
5791                                                         Flags, DAG, dl);
5792
5793       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5794       // copy the pieces of the object that fit into registers from the
5795       // parameter save area.
5796       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5797         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5798         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5799         if (GPR_idx != NumGPRs) {
5800           SDValue Load =
5801               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5802           MemOpChains.push_back(Load.getValue(1));
5803           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5804           ArgOffset += PtrByteSize;
5805         } else {
5806           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5807           break;
5808         }
5809       }
5810       continue;
5811     }
5812
5813     switch (Arg.getSimpleValueType().SimpleTy) {
5814     default: llvm_unreachable("Unexpected ValueType for argument!");
5815     case MVT::i1:
5816     case MVT::i32:
5817     case MVT::i64:
5818       if (GPR_idx != NumGPRs) {
5819         if (Arg.getValueType() == MVT::i1)
5820           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5821
5822         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5823       } else {
5824         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5825                          isPPC64, isTailCall, false, MemOpChains,
5826                          TailCallArguments, dl);
5827       }
5828       ArgOffset += PtrByteSize;
5829       break;
5830     case MVT::f32:
5831     case MVT::f64:
5832       if (FPR_idx != NumFPRs) {
5833         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5834
5835         if (isVarArg) {
5836           SDValue Store =
5837               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5838           MemOpChains.push_back(Store);
5839
5840           // Float varargs are always shadowed in available integer registers
5841           if (GPR_idx != NumGPRs) {
5842             SDValue Load =
5843                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5844             MemOpChains.push_back(Load.getValue(1));
5845             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5846           }
5847           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5848             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5849             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5850             SDValue Load =
5851                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5852             MemOpChains.push_back(Load.getValue(1));
5853             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5854           }
5855         } else {
5856           // If we have any FPRs remaining, we may also have GPRs remaining.
5857           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5858           // GPRs.
5859           if (GPR_idx != NumGPRs)
5860             ++GPR_idx;
5861           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5862               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5863             ++GPR_idx;
5864         }
5865       } else
5866         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5867                          isPPC64, isTailCall, false, MemOpChains,
5868                          TailCallArguments, dl);
5869       if (isPPC64)
5870         ArgOffset += 8;
5871       else
5872         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5873       break;
5874     case MVT::v4f32:
5875     case MVT::v4i32:
5876     case MVT::v8i16:
5877     case MVT::v16i8:
5878       if (isVarArg) {
5879         // These go aligned on the stack, or in the corresponding R registers
5880         // when within range.  The Darwin PPC ABI doc claims they also go in
5881         // V registers; in fact gcc does this only for arguments that are
5882         // prototyped, not for those that match the ...  We do it for all
5883         // arguments, seems to work.
5884         while (ArgOffset % 16 !=0) {
5885           ArgOffset += PtrByteSize;
5886           if (GPR_idx != NumGPRs)
5887             GPR_idx++;
5888         }
5889         // We could elide this store in the case where the object fits
5890         // entirely in R registers.  Maybe later.
5891         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5892                              DAG.getConstant(ArgOffset, dl, PtrVT));
5893         SDValue Store =
5894             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5895         MemOpChains.push_back(Store);
5896         if (VR_idx != NumVRs) {
5897           SDValue Load =
5898               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5899           MemOpChains.push_back(Load.getValue(1));
5900           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5901         }
5902         ArgOffset += 16;
5903         for (unsigned i=0; i<16; i+=PtrByteSize) {
5904           if (GPR_idx == NumGPRs)
5905             break;
5906           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5907                                    DAG.getConstant(i, dl, PtrVT));
5908           SDValue Load =
5909               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5910           MemOpChains.push_back(Load.getValue(1));
5911           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5912         }
5913         break;
5914       }
5915
5916       // Non-varargs Altivec params generally go in registers, but have
5917       // stack space allocated at the end.
5918       if (VR_idx != NumVRs) {
5919         // Doesn't have GPR space allocated.
5920         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5921       } else if (nAltivecParamsAtEnd==0) {
5922         // We are emitting Altivec params in order.
5923         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5924                          isPPC64, isTailCall, true, MemOpChains,
5925                          TailCallArguments, dl);
5926         ArgOffset += 16;
5927       }
5928       break;
5929     }
5930   }
5931   // If all Altivec parameters fit in registers, as they usually do,
5932   // they get stack space following the non-Altivec parameters.  We
5933   // don't track this here because nobody below needs it.
5934   // If there are more Altivec parameters than fit in registers emit
5935   // the stores here.
5936   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5937     unsigned j = 0;
5938     // Offset is aligned; skip 1st 12 params which go in V registers.
5939     ArgOffset = ((ArgOffset+15)/16)*16;
5940     ArgOffset += 12*16;
5941     for (unsigned i = 0; i != NumOps; ++i) {
5942       SDValue Arg = OutVals[i];
5943       EVT ArgType = Outs[i].VT;
5944       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5945           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5946         if (++j > NumVRs) {
5947           SDValue PtrOff;
5948           // We are emitting Altivec params in order.
5949           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5950                            isPPC64, isTailCall, true, MemOpChains,
5951                            TailCallArguments, dl);
5952           ArgOffset += 16;
5953         }
5954       }
5955     }
5956   }
5957
5958   if (!MemOpChains.empty())
5959     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5960
5961   // On Darwin, R12 must contain the address of an indirect callee.  This does
5962   // not mean the MTCTR instruction must use R12; it's easier to model this as
5963   // an extra parameter, so do that.
5964   if (!isTailCall &&
5965       !isFunctionGlobalAddress(Callee) &&
5966       !isa<ExternalSymbolSDNode>(Callee) &&
5967       !isBLACompatibleAddress(Callee, DAG))
5968     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5969                                                    PPC::R12), Callee));
5970
5971   // Build a sequence of copy-to-reg nodes chained together with token chain
5972   // and flag operands which copy the outgoing args into the appropriate regs.
5973   SDValue InFlag;
5974   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5975     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5976                              RegsToPass[i].second, InFlag);
5977     InFlag = Chain.getValue(1);
5978   }
5979
5980   if (isTailCall)
5981     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5982                     TailCallArguments);
5983
5984   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5985                     /* unused except on PPC64 ELFv1 */ false, DAG,
5986                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5987                     NumBytes, Ins, InVals, CS);
5988 }
5989
5990 bool
5991 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5992                                   MachineFunction &MF, bool isVarArg,
5993                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5994                                   LLVMContext &Context) const {
5995   SmallVector<CCValAssign, 16> RVLocs;
5996   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5997   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5998 }
5999
6000 SDValue
6001 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6002                                bool isVarArg,
6003                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6004                                const SmallVectorImpl<SDValue> &OutVals,
6005                                const SDLoc &dl, SelectionDAG &DAG) const {
6006
6007   SmallVector<CCValAssign, 16> RVLocs;
6008   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6009                  *DAG.getContext());
6010   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6011
6012   SDValue Flag;
6013   SmallVector<SDValue, 4> RetOps(1, Chain);
6014
6015   // Copy the result values into the output registers.
6016   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6017     CCValAssign &VA = RVLocs[i];
6018     assert(VA.isRegLoc() && "Can only return in registers!");
6019
6020     SDValue Arg = OutVals[i];
6021
6022     switch (VA.getLocInfo()) {
6023     default: llvm_unreachable("Unknown loc info!");
6024     case CCValAssign::Full: break;
6025     case CCValAssign::AExt:
6026       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6027       break;
6028     case CCValAssign::ZExt:
6029       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6030       break;
6031     case CCValAssign::SExt:
6032       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6033       break;
6034     }
6035
6036     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6037     Flag = Chain.getValue(1);
6038     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6039   }
6040
6041   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6042   const MCPhysReg *I =
6043     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6044   if (I) {
6045     for (; *I; ++I) {
6046
6047       if (PPC::G8RCRegClass.contains(*I))
6048         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6049       else if (PPC::F8RCRegClass.contains(*I))
6050         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6051       else if (PPC::CRRCRegClass.contains(*I))
6052         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6053       else if (PPC::VRRCRegClass.contains(*I))
6054         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6055       else
6056         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6057     }
6058   }
6059
6060   RetOps[0] = Chain;  // Update chain.
6061
6062   // Add the flag if we have it.
6063   if (Flag.getNode())
6064     RetOps.push_back(Flag);
6065
6066   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6067 }
6068
6069 SDValue
6070 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6071                                                 SelectionDAG &DAG) const {
6072   SDLoc dl(Op);
6073
6074   // Get the corect type for integers.
6075   EVT IntVT = Op.getValueType();
6076
6077   // Get the inputs.
6078   SDValue Chain = Op.getOperand(0);
6079   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6080   // Build a DYNAREAOFFSET node.
6081   SDValue Ops[2] = {Chain, FPSIdx};
6082   SDVTList VTs = DAG.getVTList(IntVT);
6083   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6084 }
6085
6086 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6087                                              SelectionDAG &DAG) const {
6088   // When we pop the dynamic allocation we need to restore the SP link.
6089   SDLoc dl(Op);
6090
6091   // Get the corect type for pointers.
6092   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6093
6094   // Construct the stack pointer operand.
6095   bool isPPC64 = Subtarget.isPPC64();
6096   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6097   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6098
6099   // Get the operands for the STACKRESTORE.
6100   SDValue Chain = Op.getOperand(0);
6101   SDValue SaveSP = Op.getOperand(1);
6102
6103   // Load the old link SP.
6104   SDValue LoadLinkSP =
6105       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6106
6107   // Restore the stack pointer.
6108   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6109
6110   // Store the old link SP.
6111   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6112 }
6113
6114 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6115   MachineFunction &MF = DAG.getMachineFunction();
6116   bool isPPC64 = Subtarget.isPPC64();
6117   EVT PtrVT = getPointerTy(MF.getDataLayout());
6118
6119   // Get current frame pointer save index.  The users of this index will be
6120   // primarily DYNALLOC instructions.
6121   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6122   int RASI = FI->getReturnAddrSaveIndex();
6123
6124   // If the frame pointer save index hasn't been defined yet.
6125   if (!RASI) {
6126     // Find out what the fix offset of the frame pointer save area.
6127     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6128     // Allocate the frame index for frame pointer save area.
6129     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6130     // Save the result.
6131     FI->setReturnAddrSaveIndex(RASI);
6132   }
6133   return DAG.getFrameIndex(RASI, PtrVT);
6134 }
6135
6136 SDValue
6137 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6138   MachineFunction &MF = DAG.getMachineFunction();
6139   bool isPPC64 = Subtarget.isPPC64();
6140   EVT PtrVT = getPointerTy(MF.getDataLayout());
6141
6142   // Get current frame pointer save index.  The users of this index will be
6143   // primarily DYNALLOC instructions.
6144   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6145   int FPSI = FI->getFramePointerSaveIndex();
6146
6147   // If the frame pointer save index hasn't been defined yet.
6148   if (!FPSI) {
6149     // Find out what the fix offset of the frame pointer save area.
6150     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6151     // Allocate the frame index for frame pointer save area.
6152     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6153     // Save the result.
6154     FI->setFramePointerSaveIndex(FPSI);
6155   }
6156   return DAG.getFrameIndex(FPSI, PtrVT);
6157 }
6158
6159 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6160                                                    SelectionDAG &DAG) const {
6161   // Get the inputs.
6162   SDValue Chain = Op.getOperand(0);
6163   SDValue Size  = Op.getOperand(1);
6164   SDLoc dl(Op);
6165
6166   // Get the corect type for pointers.
6167   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6168   // Negate the size.
6169   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6170                                 DAG.getConstant(0, dl, PtrVT), Size);
6171   // Construct a node for the frame pointer save index.
6172   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6173   // Build a DYNALLOC node.
6174   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6175   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6176   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6177 }
6178
6179 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6180                                                      SelectionDAG &DAG) const {
6181   MachineFunction &MF = DAG.getMachineFunction();
6182
6183   bool isPPC64 = Subtarget.isPPC64();
6184   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6185
6186   int FI = MF.getFrameInfo()->CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6187   return DAG.getFrameIndex(FI, PtrVT);
6188 }
6189
6190 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6191                                                SelectionDAG &DAG) const {
6192   SDLoc DL(Op);
6193   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6194                      DAG.getVTList(MVT::i32, MVT::Other),
6195                      Op.getOperand(0), Op.getOperand(1));
6196 }
6197
6198 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6199                                                 SelectionDAG &DAG) const {
6200   SDLoc DL(Op);
6201   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6202                      Op.getOperand(0), Op.getOperand(1));
6203 }
6204
6205 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6206   if (Op.getValueType().isVector())
6207     return LowerVectorLoad(Op, DAG);
6208
6209   assert(Op.getValueType() == MVT::i1 &&
6210          "Custom lowering only for i1 loads");
6211
6212   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6213
6214   SDLoc dl(Op);
6215   LoadSDNode *LD = cast<LoadSDNode>(Op);
6216
6217   SDValue Chain = LD->getChain();
6218   SDValue BasePtr = LD->getBasePtr();
6219   MachineMemOperand *MMO = LD->getMemOperand();
6220
6221   SDValue NewLD =
6222       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6223                      BasePtr, MVT::i8, MMO);
6224   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6225
6226   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6227   return DAG.getMergeValues(Ops, dl);
6228 }
6229
6230 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6231   if (Op.getOperand(1).getValueType().isVector())
6232     return LowerVectorStore(Op, DAG);
6233
6234   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6235          "Custom lowering only for i1 stores");
6236
6237   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6238
6239   SDLoc dl(Op);
6240   StoreSDNode *ST = cast<StoreSDNode>(Op);
6241
6242   SDValue Chain = ST->getChain();
6243   SDValue BasePtr = ST->getBasePtr();
6244   SDValue Value = ST->getValue();
6245   MachineMemOperand *MMO = ST->getMemOperand();
6246
6247   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6248                       Value);
6249   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6250 }
6251
6252 // FIXME: Remove this once the ANDI glue bug is fixed:
6253 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6254   assert(Op.getValueType() == MVT::i1 &&
6255          "Custom lowering only for i1 results");
6256
6257   SDLoc DL(Op);
6258   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6259                      Op.getOperand(0));
6260 }
6261
6262 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6263 /// possible.
6264 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6265   // Not FP? Not a fsel.
6266   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6267       !Op.getOperand(2).getValueType().isFloatingPoint())
6268     return Op;
6269
6270   // We might be able to do better than this under some circumstances, but in
6271   // general, fsel-based lowering of select is a finite-math-only optimization.
6272   // For more information, see section F.3 of the 2.06 ISA specification.
6273   if (!DAG.getTarget().Options.NoInfsFPMath ||
6274       !DAG.getTarget().Options.NoNaNsFPMath)
6275     return Op;
6276   // TODO: Propagate flags from the select rather than global settings.
6277   SDNodeFlags Flags;
6278   Flags.setNoInfs(true);
6279   Flags.setNoNaNs(true);
6280
6281   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6282
6283   EVT ResVT = Op.getValueType();
6284   EVT CmpVT = Op.getOperand(0).getValueType();
6285   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6286   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6287   SDLoc dl(Op);
6288
6289   // If the RHS of the comparison is a 0.0, we don't need to do the
6290   // subtraction at all.
6291   SDValue Sel1;
6292   if (isFloatingPointZero(RHS))
6293     switch (CC) {
6294     default: break;       // SETUO etc aren't handled by fsel.
6295     case ISD::SETNE:
6296       std::swap(TV, FV);
6297     case ISD::SETEQ:
6298       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6299         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6300       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6301       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6302         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6303       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6304                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6305     case ISD::SETULT:
6306     case ISD::SETLT:
6307       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6308     case ISD::SETOGE:
6309     case ISD::SETGE:
6310       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6311         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6312       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6313     case ISD::SETUGT:
6314     case ISD::SETGT:
6315       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6316     case ISD::SETOLE:
6317     case ISD::SETLE:
6318       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6319         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6320       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6321                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6322     }
6323
6324   SDValue Cmp;
6325   switch (CC) {
6326   default: break;       // SETUO etc aren't handled by fsel.
6327   case ISD::SETNE:
6328     std::swap(TV, FV);
6329   case ISD::SETEQ:
6330     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6331     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6332       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6333     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6334     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6335       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6336     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6337                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6338   case ISD::SETULT:
6339   case ISD::SETLT:
6340     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6341     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6342       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6343     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6344   case ISD::SETOGE:
6345   case ISD::SETGE:
6346     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6347     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6348       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6349     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6350   case ISD::SETUGT:
6351   case ISD::SETGT:
6352     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6353     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6354       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6355     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6356   case ISD::SETOLE:
6357   case ISD::SETLE:
6358     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6359     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6360       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6361     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6362   }
6363   return Op;
6364 }
6365
6366 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6367                                                SelectionDAG &DAG,
6368                                                const SDLoc &dl) const {
6369   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6370   SDValue Src = Op.getOperand(0);
6371   if (Src.getValueType() == MVT::f32)
6372     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6373
6374   SDValue Tmp;
6375   switch (Op.getSimpleValueType().SimpleTy) {
6376   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6377   case MVT::i32:
6378     Tmp = DAG.getNode(
6379         Op.getOpcode() == ISD::FP_TO_SINT
6380             ? PPCISD::FCTIWZ
6381             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6382         dl, MVT::f64, Src);
6383     break;
6384   case MVT::i64:
6385     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6386            "i64 FP_TO_UINT is supported only with FPCVT");
6387     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6388                                                         PPCISD::FCTIDUZ,
6389                       dl, MVT::f64, Src);
6390     break;
6391   }
6392
6393   // Convert the FP value to an int value through memory.
6394   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6395     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6396   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6397   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6398   MachinePointerInfo MPI =
6399       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6400
6401   // Emit a store to the stack slot.
6402   SDValue Chain;
6403   if (i32Stack) {
6404     MachineFunction &MF = DAG.getMachineFunction();
6405     MachineMemOperand *MMO =
6406       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6407     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6408     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6409               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6410   } else
6411     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6412
6413   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6414   // add in a bias on big endian.
6415   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6416     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6417                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6418     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6419   }
6420
6421   RLI.Chain = Chain;
6422   RLI.Ptr = FIPtr;
6423   RLI.MPI = MPI;
6424 }
6425
6426 /// \brief Custom lowers floating point to integer conversions to use
6427 /// the direct move instructions available in ISA 2.07 to avoid the
6428 /// need for load/store combinations.
6429 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6430                                                     SelectionDAG &DAG,
6431                                                     const SDLoc &dl) const {
6432   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6433   SDValue Src = Op.getOperand(0);
6434
6435   if (Src.getValueType() == MVT::f32)
6436     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6437
6438   SDValue Tmp;
6439   switch (Op.getSimpleValueType().SimpleTy) {
6440   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6441   case MVT::i32:
6442     Tmp = DAG.getNode(
6443         Op.getOpcode() == ISD::FP_TO_SINT
6444             ? PPCISD::FCTIWZ
6445             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6446         dl, MVT::f64, Src);
6447     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6448     break;
6449   case MVT::i64:
6450     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6451            "i64 FP_TO_UINT is supported only with FPCVT");
6452     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6453                                                         PPCISD::FCTIDUZ,
6454                       dl, MVT::f64, Src);
6455     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6456     break;
6457   }
6458   return Tmp;
6459 }
6460
6461 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6462                                           const SDLoc &dl) const {
6463   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6464     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6465
6466   ReuseLoadInfo RLI;
6467   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6468
6469   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6470                      RLI.Alignment,
6471                      RLI.IsInvariant ? MachineMemOperand::MOInvariant
6472                                      : MachineMemOperand::MONone,
6473                      RLI.AAInfo, RLI.Ranges);
6474 }
6475
6476 // We're trying to insert a regular store, S, and then a load, L. If the
6477 // incoming value, O, is a load, we might just be able to have our load use the
6478 // address used by O. However, we don't know if anything else will store to
6479 // that address before we can load from it. To prevent this situation, we need
6480 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6481 // the same chain operand as O, we create a token factor from the chain results
6482 // of O and L, and we replace all uses of O's chain result with that token
6483 // factor (see spliceIntoChain below for this last part).
6484 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6485                                             ReuseLoadInfo &RLI,
6486                                             SelectionDAG &DAG,
6487                                             ISD::LoadExtType ET) const {
6488   SDLoc dl(Op);
6489   if (ET == ISD::NON_EXTLOAD &&
6490       (Op.getOpcode() == ISD::FP_TO_UINT ||
6491        Op.getOpcode() == ISD::FP_TO_SINT) &&
6492       isOperationLegalOrCustom(Op.getOpcode(),
6493                                Op.getOperand(0).getValueType())) {
6494
6495     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6496     return true;
6497   }
6498
6499   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6500   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6501       LD->isNonTemporal())
6502     return false;
6503   if (LD->getMemoryVT() != MemVT)
6504     return false;
6505
6506   RLI.Ptr = LD->getBasePtr();
6507   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6508     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6509            "Non-pre-inc AM on PPC?");
6510     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6511                           LD->getOffset());
6512   }
6513
6514   RLI.Chain = LD->getChain();
6515   RLI.MPI = LD->getPointerInfo();
6516   RLI.IsInvariant = LD->isInvariant();
6517   RLI.Alignment = LD->getAlignment();
6518   RLI.AAInfo = LD->getAAInfo();
6519   RLI.Ranges = LD->getRanges();
6520
6521   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6522   return true;
6523 }
6524
6525 // Given the head of the old chain, ResChain, insert a token factor containing
6526 // it and NewResChain, and make users of ResChain now be users of that token
6527 // factor.
6528 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6529                                         SDValue NewResChain,
6530                                         SelectionDAG &DAG) const {
6531   if (!ResChain)
6532     return;
6533
6534   SDLoc dl(NewResChain);
6535
6536   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6537                            NewResChain, DAG.getUNDEF(MVT::Other));
6538   assert(TF.getNode() != NewResChain.getNode() &&
6539          "A new TF really is required here");
6540
6541   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6542   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6543 }
6544
6545 /// \brief Analyze profitability of direct move
6546 /// prefer float load to int load plus direct move
6547 /// when there is no integer use of int load
6548 static bool directMoveIsProfitable(const SDValue &Op) {
6549   SDNode *Origin = Op.getOperand(0).getNode();
6550   if (Origin->getOpcode() != ISD::LOAD)
6551     return true;
6552
6553   for (SDNode::use_iterator UI = Origin->use_begin(),
6554                             UE = Origin->use_end();
6555        UI != UE; ++UI) {
6556
6557     // Only look at the users of the loaded value.
6558     if (UI.getUse().get().getResNo() != 0)
6559       continue;
6560
6561     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6562         UI->getOpcode() != ISD::UINT_TO_FP)
6563       return true;
6564   }
6565
6566   return false;
6567 }
6568
6569 /// \brief Custom lowers integer to floating point conversions to use
6570 /// the direct move instructions available in ISA 2.07 to avoid the
6571 /// need for load/store combinations.
6572 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6573                                                     SelectionDAG &DAG,
6574                                                     const SDLoc &dl) const {
6575   assert((Op.getValueType() == MVT::f32 ||
6576           Op.getValueType() == MVT::f64) &&
6577          "Invalid floating point type as target of conversion");
6578   assert(Subtarget.hasFPCVT() &&
6579          "Int to FP conversions with direct moves require FPCVT");
6580   SDValue FP;
6581   SDValue Src = Op.getOperand(0);
6582   bool SinglePrec = Op.getValueType() == MVT::f32;
6583   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6584   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6585   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6586                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6587
6588   if (WordInt) {
6589     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6590                      dl, MVT::f64, Src);
6591     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6592   }
6593   else {
6594     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6595     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6596   }
6597
6598   return FP;
6599 }
6600
6601 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6602                                           SelectionDAG &DAG) const {
6603   SDLoc dl(Op);
6604
6605   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6606     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6607       return SDValue();
6608
6609     SDValue Value = Op.getOperand(0);
6610     // The values are now known to be -1 (false) or 1 (true). To convert this
6611     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6612     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6613     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6614
6615     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6616
6617     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6618
6619     if (Op.getValueType() != MVT::v4f64)
6620       Value = DAG.getNode(ISD::FP_ROUND, dl,
6621                           Op.getValueType(), Value,
6622                           DAG.getIntPtrConstant(1, dl));
6623     return Value;
6624   }
6625
6626   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6627   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6628     return SDValue();
6629
6630   if (Op.getOperand(0).getValueType() == MVT::i1)
6631     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6632                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6633                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6634
6635   // If we have direct moves, we can do all the conversion, skip the store/load
6636   // however, without FPCVT we can't do most conversions.
6637   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6638       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6639     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6640
6641   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6642          "UINT_TO_FP is supported only with FPCVT");
6643
6644   // If we have FCFIDS, then use it when converting to single-precision.
6645   // Otherwise, convert to double-precision and then round.
6646   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6647                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6648                                                             : PPCISD::FCFIDS)
6649                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6650                                                             : PPCISD::FCFID);
6651   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6652                   ? MVT::f32
6653                   : MVT::f64;
6654
6655   if (Op.getOperand(0).getValueType() == MVT::i64) {
6656     SDValue SINT = Op.getOperand(0);
6657     // When converting to single-precision, we actually need to convert
6658     // to double-precision first and then round to single-precision.
6659     // To avoid double-rounding effects during that operation, we have
6660     // to prepare the input operand.  Bits that might be truncated when
6661     // converting to double-precision are replaced by a bit that won't
6662     // be lost at this stage, but is below the single-precision rounding
6663     // position.
6664     //
6665     // However, if -enable-unsafe-fp-math is in effect, accept double
6666     // rounding to avoid the extra overhead.
6667     if (Op.getValueType() == MVT::f32 &&
6668         !Subtarget.hasFPCVT() &&
6669         !DAG.getTarget().Options.UnsafeFPMath) {
6670
6671       // Twiddle input to make sure the low 11 bits are zero.  (If this
6672       // is the case, we are guaranteed the value will fit into the 53 bit
6673       // mantissa of an IEEE double-precision value without rounding.)
6674       // If any of those low 11 bits were not zero originally, make sure
6675       // bit 12 (value 2048) is set instead, so that the final rounding
6676       // to single-precision gets the correct result.
6677       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6678                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6679       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6680                           Round, DAG.getConstant(2047, dl, MVT::i64));
6681       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6682       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6683                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6684
6685       // However, we cannot use that value unconditionally: if the magnitude
6686       // of the input value is small, the bit-twiddling we did above might
6687       // end up visibly changing the output.  Fortunately, in that case, we
6688       // don't need to twiddle bits since the original input will convert
6689       // exactly to double-precision floating-point already.  Therefore,
6690       // construct a conditional to use the original value if the top 11
6691       // bits are all sign-bit copies, and use the rounded value computed
6692       // above otherwise.
6693       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6694                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6695       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6696                          Cond, DAG.getConstant(1, dl, MVT::i64));
6697       Cond = DAG.getSetCC(dl, MVT::i32,
6698                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6699
6700       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6701     }
6702
6703     ReuseLoadInfo RLI;
6704     SDValue Bits;
6705
6706     MachineFunction &MF = DAG.getMachineFunction();
6707     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6708       Bits =
6709           DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, RLI.Alignment,
6710                       RLI.IsInvariant ? MachineMemOperand::MOInvariant
6711                                       : MachineMemOperand::MONone,
6712                       RLI.AAInfo, RLI.Ranges);
6713       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6714     } else if (Subtarget.hasLFIWAX() &&
6715                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6716       MachineMemOperand *MMO =
6717         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6718                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6719       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6720       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6721                                      DAG.getVTList(MVT::f64, MVT::Other),
6722                                      Ops, MVT::i32, MMO);
6723       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6724     } else if (Subtarget.hasFPCVT() &&
6725                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6726       MachineMemOperand *MMO =
6727         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6728                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6729       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6730       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6731                                      DAG.getVTList(MVT::f64, MVT::Other),
6732                                      Ops, MVT::i32, MMO);
6733       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6734     } else if (((Subtarget.hasLFIWAX() &&
6735                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6736                 (Subtarget.hasFPCVT() &&
6737                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6738                SINT.getOperand(0).getValueType() == MVT::i32) {
6739       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6740       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6741
6742       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6743       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6744
6745       SDValue Store =
6746           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6747                        MachinePointerInfo::getFixedStack(
6748                            DAG.getMachineFunction(), FrameIdx));
6749
6750       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6751              "Expected an i32 store");
6752
6753       RLI.Ptr = FIdx;
6754       RLI.Chain = Store;
6755       RLI.MPI =
6756           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6757       RLI.Alignment = 4;
6758
6759       MachineMemOperand *MMO =
6760         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6761                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6762       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6763       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6764                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6765                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6766                                      Ops, MVT::i32, MMO);
6767     } else
6768       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6769
6770     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6771
6772     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6773       FP = DAG.getNode(ISD::FP_ROUND, dl,
6774                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6775     return FP;
6776   }
6777
6778   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6779          "Unhandled INT_TO_FP type in custom expander!");
6780   // Since we only generate this in 64-bit mode, we can take advantage of
6781   // 64-bit registers.  In particular, sign extend the input value into the
6782   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6783   // then lfd it and fcfid it.
6784   MachineFunction &MF = DAG.getMachineFunction();
6785   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6786   EVT PtrVT = getPointerTy(MF.getDataLayout());
6787
6788   SDValue Ld;
6789   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6790     ReuseLoadInfo RLI;
6791     bool ReusingLoad;
6792     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6793                                             DAG))) {
6794       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6795       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6796
6797       SDValue Store =
6798           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6799                        MachinePointerInfo::getFixedStack(
6800                            DAG.getMachineFunction(), FrameIdx));
6801
6802       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6803              "Expected an i32 store");
6804
6805       RLI.Ptr = FIdx;
6806       RLI.Chain = Store;
6807       RLI.MPI =
6808           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6809       RLI.Alignment = 4;
6810     }
6811
6812     MachineMemOperand *MMO =
6813       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6814                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6815     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6816     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6817                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6818                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6819                                  Ops, MVT::i32, MMO);
6820     if (ReusingLoad)
6821       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6822   } else {
6823     assert(Subtarget.isPPC64() &&
6824            "i32->FP without LFIWAX supported only on PPC64");
6825
6826     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6827     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6828
6829     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6830                                 Op.getOperand(0));
6831
6832     // STD the extended value into the stack slot.
6833     SDValue Store = DAG.getStore(
6834         DAG.getEntryNode(), dl, Ext64, FIdx,
6835         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6836
6837     // Load the value as a double.
6838     Ld = DAG.getLoad(
6839         MVT::f64, dl, Store, FIdx,
6840         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6841   }
6842
6843   // FCFID it and return it.
6844   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6845   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6846     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6847                      DAG.getIntPtrConstant(0, dl));
6848   return FP;
6849 }
6850
6851 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6852                                             SelectionDAG &DAG) const {
6853   SDLoc dl(Op);
6854   /*
6855    The rounding mode is in bits 30:31 of FPSR, and has the following
6856    settings:
6857      00 Round to nearest
6858      01 Round to 0
6859      10 Round to +inf
6860      11 Round to -inf
6861
6862   FLT_ROUNDS, on the other hand, expects the following:
6863     -1 Undefined
6864      0 Round to 0
6865      1 Round to nearest
6866      2 Round to +inf
6867      3 Round to -inf
6868
6869   To perform the conversion, we do:
6870     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6871   */
6872
6873   MachineFunction &MF = DAG.getMachineFunction();
6874   EVT VT = Op.getValueType();
6875   EVT PtrVT = getPointerTy(MF.getDataLayout());
6876
6877   // Save FP Control Word to register
6878   EVT NodeTys[] = {
6879     MVT::f64,    // return register
6880     MVT::Glue    // unused in this context
6881   };
6882   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6883
6884   // Save FP register to stack slot
6885   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6886   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6887   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
6888                                MachinePointerInfo());
6889
6890   // Load FP Control Word from low 32 bits of stack slot.
6891   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6892   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6893   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
6894
6895   // Transform as necessary
6896   SDValue CWD1 =
6897     DAG.getNode(ISD::AND, dl, MVT::i32,
6898                 CWD, DAG.getConstant(3, dl, MVT::i32));
6899   SDValue CWD2 =
6900     DAG.getNode(ISD::SRL, dl, MVT::i32,
6901                 DAG.getNode(ISD::AND, dl, MVT::i32,
6902                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6903                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6904                             DAG.getConstant(3, dl, MVT::i32)),
6905                 DAG.getConstant(1, dl, MVT::i32));
6906
6907   SDValue RetVal =
6908     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6909
6910   return DAG.getNode((VT.getSizeInBits() < 16 ?
6911                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6912 }
6913
6914 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6915   EVT VT = Op.getValueType();
6916   unsigned BitWidth = VT.getSizeInBits();
6917   SDLoc dl(Op);
6918   assert(Op.getNumOperands() == 3 &&
6919          VT == Op.getOperand(1).getValueType() &&
6920          "Unexpected SHL!");
6921
6922   // Expand into a bunch of logical ops.  Note that these ops
6923   // depend on the PPC behavior for oversized shift amounts.
6924   SDValue Lo = Op.getOperand(0);
6925   SDValue Hi = Op.getOperand(1);
6926   SDValue Amt = Op.getOperand(2);
6927   EVT AmtVT = Amt.getValueType();
6928
6929   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6930                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6931   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6932   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6933   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6934   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6935                              DAG.getConstant(-BitWidth, dl, AmtVT));
6936   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6937   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6938   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6939   SDValue OutOps[] = { OutLo, OutHi };
6940   return DAG.getMergeValues(OutOps, dl);
6941 }
6942
6943 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6944   EVT VT = Op.getValueType();
6945   SDLoc dl(Op);
6946   unsigned BitWidth = VT.getSizeInBits();
6947   assert(Op.getNumOperands() == 3 &&
6948          VT == Op.getOperand(1).getValueType() &&
6949          "Unexpected SRL!");
6950
6951   // Expand into a bunch of logical ops.  Note that these ops
6952   // depend on the PPC behavior for oversized shift amounts.
6953   SDValue Lo = Op.getOperand(0);
6954   SDValue Hi = Op.getOperand(1);
6955   SDValue Amt = Op.getOperand(2);
6956   EVT AmtVT = Amt.getValueType();
6957
6958   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6959                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6960   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6961   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6962   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6963   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6964                              DAG.getConstant(-BitWidth, dl, AmtVT));
6965   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6966   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6967   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6968   SDValue OutOps[] = { OutLo, OutHi };
6969   return DAG.getMergeValues(OutOps, dl);
6970 }
6971
6972 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6973   SDLoc dl(Op);
6974   EVT VT = Op.getValueType();
6975   unsigned BitWidth = VT.getSizeInBits();
6976   assert(Op.getNumOperands() == 3 &&
6977          VT == Op.getOperand(1).getValueType() &&
6978          "Unexpected SRA!");
6979
6980   // Expand into a bunch of logical ops, followed by a select_cc.
6981   SDValue Lo = Op.getOperand(0);
6982   SDValue Hi = Op.getOperand(1);
6983   SDValue Amt = Op.getOperand(2);
6984   EVT AmtVT = Amt.getValueType();
6985
6986   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6987                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6988   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6989   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6990   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6991   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6992                              DAG.getConstant(-BitWidth, dl, AmtVT));
6993   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6994   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6995   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6996                                   Tmp4, Tmp6, ISD::SETLE);
6997   SDValue OutOps[] = { OutLo, OutHi };
6998   return DAG.getMergeValues(OutOps, dl);
6999 }
7000
7001 //===----------------------------------------------------------------------===//
7002 // Vector related lowering.
7003 //
7004
7005 /// BuildSplatI - Build a canonical splati of Val with an element size of
7006 /// SplatSize.  Cast the result to VT.
7007 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7008                            SelectionDAG &DAG, const SDLoc &dl) {
7009   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7010
7011   static const MVT VTys[] = { // canonical VT to use for each size.
7012     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7013   };
7014
7015   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7016
7017   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7018   if (Val == -1)
7019     SplatSize = 1;
7020
7021   EVT CanonicalVT = VTys[SplatSize-1];
7022
7023   // Build a canonical splat for this value.
7024   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7025 }
7026
7027 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7028 /// specified intrinsic ID.
7029 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7030                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7031   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7032   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7033                      DAG.getConstant(IID, dl, MVT::i32), Op);
7034 }
7035
7036 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7037 /// specified intrinsic ID.
7038 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7039                                 SelectionDAG &DAG, const SDLoc &dl,
7040                                 EVT DestVT = MVT::Other) {
7041   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7042   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7043                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7044 }
7045
7046 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7047 /// specified intrinsic ID.
7048 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7049                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7050                                 EVT DestVT = MVT::Other) {
7051   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7052   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7053                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7054 }
7055
7056 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7057 /// amount.  The result has the specified value type.
7058 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7059                            SelectionDAG &DAG, const SDLoc &dl) {
7060   // Force LHS/RHS to be the right type.
7061   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7062   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7063
7064   int Ops[16];
7065   for (unsigned i = 0; i != 16; ++i)
7066     Ops[i] = i + Amt;
7067   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7068   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7069 }
7070
7071 // If this is a case we can't handle, return null and let the default
7072 // expansion code take care of it.  If we CAN select this case, and if it
7073 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7074 // this case more efficiently than a constant pool load, lower it to the
7075 // sequence of ops that should be used.
7076 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7077                                              SelectionDAG &DAG) const {
7078   SDLoc dl(Op);
7079   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7080   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7081
7082   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7083     // We first build an i32 vector, load it into a QPX register,
7084     // then convert it to a floating-point vector and compare it
7085     // to a zero vector to get the boolean result.
7086     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7087     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7088     MachinePointerInfo PtrInfo =
7089         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7090     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7091     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7092
7093     assert(BVN->getNumOperands() == 4 &&
7094       "BUILD_VECTOR for v4i1 does not have 4 operands");
7095
7096     bool IsConst = true;
7097     for (unsigned i = 0; i < 4; ++i) {
7098       if (BVN->getOperand(i).isUndef()) continue;
7099       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7100         IsConst = false;
7101         break;
7102       }
7103     }
7104
7105     if (IsConst) {
7106       Constant *One =
7107         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7108       Constant *NegOne =
7109         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7110
7111       Constant *CV[4];
7112       for (unsigned i = 0; i < 4; ++i) {
7113         if (BVN->getOperand(i).isUndef())
7114           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7115         else if (isNullConstant(BVN->getOperand(i)))
7116           CV[i] = NegOne;
7117         else
7118           CV[i] = One;
7119       }
7120
7121       Constant *CP = ConstantVector::get(CV);
7122       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7123                                           16 /* alignment */);
7124
7125       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7126       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7127       return DAG.getMemIntrinsicNode(
7128           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7129           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7130     }
7131
7132     SmallVector<SDValue, 4> Stores;
7133     for (unsigned i = 0; i < 4; ++i) {
7134       if (BVN->getOperand(i).isUndef()) continue;
7135
7136       unsigned Offset = 4*i;
7137       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7138       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7139
7140       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7141       if (StoreSize > 4) {
7142         Stores.push_back(
7143             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7144                               PtrInfo.getWithOffset(Offset), MVT::i32));
7145       } else {
7146         SDValue StoreValue = BVN->getOperand(i);
7147         if (StoreSize < 4)
7148           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7149
7150         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7151                                       PtrInfo.getWithOffset(Offset)));
7152       }
7153     }
7154
7155     SDValue StoreChain;
7156     if (!Stores.empty())
7157       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7158     else
7159       StoreChain = DAG.getEntryNode();
7160
7161     // Now load from v4i32 into the QPX register; this will extend it to
7162     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7163     // is typed as v4f64 because the QPX register integer states are not
7164     // explicitly represented.
7165
7166     SDValue Ops[] = {StoreChain,
7167                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7168                      FIdx};
7169     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7170
7171     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7172       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7173     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7174       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7175       LoadedVect);
7176
7177     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7178
7179     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7180   }
7181
7182   // All other QPX vectors are handled by generic code.
7183   if (Subtarget.hasQPX())
7184     return SDValue();
7185
7186   // Check if this is a splat of a constant value.
7187   APInt APSplatBits, APSplatUndef;
7188   unsigned SplatBitSize;
7189   bool HasAnyUndefs;
7190   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7191                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7192       SplatBitSize > 32)
7193     return SDValue();
7194
7195   unsigned SplatBits = APSplatBits.getZExtValue();
7196   unsigned SplatUndef = APSplatUndef.getZExtValue();
7197   unsigned SplatSize = SplatBitSize / 8;
7198
7199   // First, handle single instruction cases.
7200
7201   // All zeros?
7202   if (SplatBits == 0) {
7203     // Canonicalize all zero vectors to be v4i32.
7204     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7205       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7206       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7207     }
7208     return Op;
7209   }
7210
7211   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7212   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7213                     (32-SplatBitSize));
7214   if (SextVal >= -16 && SextVal <= 15)
7215     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7216
7217   // Two instruction sequences.
7218
7219   // If this value is in the range [-32,30] and is even, use:
7220   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7221   // If this value is in the range [17,31] and is odd, use:
7222   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7223   // If this value is in the range [-31,-17] and is odd, use:
7224   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7225   // Note the last two are three-instruction sequences.
7226   if (SextVal >= -32 && SextVal <= 31) {
7227     // To avoid having these optimizations undone by constant folding,
7228     // we convert to a pseudo that will be expanded later into one of
7229     // the above forms.
7230     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7231     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7232               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7233     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7234     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7235     if (VT == Op.getValueType())
7236       return RetVal;
7237     else
7238       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7239   }
7240
7241   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7242   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7243   // for fneg/fabs.
7244   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7245     // Make -1 and vspltisw -1:
7246     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7247
7248     // Make the VSLW intrinsic, computing 0x8000_0000.
7249     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7250                                    OnesV, DAG, dl);
7251
7252     // xor by OnesV to invert it.
7253     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7254     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7255   }
7256
7257   // Check to see if this is a wide variety of vsplti*, binop self cases.
7258   static const signed char SplatCsts[] = {
7259     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7260     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7261   };
7262
7263   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7264     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7265     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7266     int i = SplatCsts[idx];
7267
7268     // Figure out what shift amount will be used by altivec if shifted by i in
7269     // this splat size.
7270     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7271
7272     // vsplti + shl self.
7273     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7274       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7275       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7276         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7277         Intrinsic::ppc_altivec_vslw
7278       };
7279       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7280       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7281     }
7282
7283     // vsplti + srl self.
7284     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7285       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7286       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7287         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7288         Intrinsic::ppc_altivec_vsrw
7289       };
7290       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7291       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7292     }
7293
7294     // vsplti + sra self.
7295     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7296       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7297       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7298         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7299         Intrinsic::ppc_altivec_vsraw
7300       };
7301       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7302       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7303     }
7304
7305     // vsplti + rol self.
7306     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7307                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7308       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7309       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7310         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7311         Intrinsic::ppc_altivec_vrlw
7312       };
7313       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7314       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7315     }
7316
7317     // t = vsplti c, result = vsldoi t, t, 1
7318     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7319       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7320       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7321       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7322     }
7323     // t = vsplti c, result = vsldoi t, t, 2
7324     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7325       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7326       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7327       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7328     }
7329     // t = vsplti c, result = vsldoi t, t, 3
7330     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7331       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7332       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7333       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7334     }
7335   }
7336
7337   return SDValue();
7338 }
7339
7340 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7341 /// the specified operations to build the shuffle.
7342 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7343                                       SDValue RHS, SelectionDAG &DAG,
7344                                       const SDLoc &dl) {
7345   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7346   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7347   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7348
7349   enum {
7350     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7351     OP_VMRGHW,
7352     OP_VMRGLW,
7353     OP_VSPLTISW0,
7354     OP_VSPLTISW1,
7355     OP_VSPLTISW2,
7356     OP_VSPLTISW3,
7357     OP_VSLDOI4,
7358     OP_VSLDOI8,
7359     OP_VSLDOI12
7360   };
7361
7362   if (OpNum == OP_COPY) {
7363     if (LHSID == (1*9+2)*9+3) return LHS;
7364     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7365     return RHS;
7366   }
7367
7368   SDValue OpLHS, OpRHS;
7369   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7370   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7371
7372   int ShufIdxs[16];
7373   switch (OpNum) {
7374   default: llvm_unreachable("Unknown i32 permute!");
7375   case OP_VMRGHW:
7376     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7377     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7378     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7379     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7380     break;
7381   case OP_VMRGLW:
7382     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7383     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7384     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7385     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7386     break;
7387   case OP_VSPLTISW0:
7388     for (unsigned i = 0; i != 16; ++i)
7389       ShufIdxs[i] = (i&3)+0;
7390     break;
7391   case OP_VSPLTISW1:
7392     for (unsigned i = 0; i != 16; ++i)
7393       ShufIdxs[i] = (i&3)+4;
7394     break;
7395   case OP_VSPLTISW2:
7396     for (unsigned i = 0; i != 16; ++i)
7397       ShufIdxs[i] = (i&3)+8;
7398     break;
7399   case OP_VSPLTISW3:
7400     for (unsigned i = 0; i != 16; ++i)
7401       ShufIdxs[i] = (i&3)+12;
7402     break;
7403   case OP_VSLDOI4:
7404     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7405   case OP_VSLDOI8:
7406     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7407   case OP_VSLDOI12:
7408     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7409   }
7410   EVT VT = OpLHS.getValueType();
7411   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7412   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7413   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7414   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7415 }
7416
7417 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7418 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7419 /// return the code it can be lowered into.  Worst case, it can always be
7420 /// lowered into a vperm.
7421 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7422                                                SelectionDAG &DAG) const {
7423   SDLoc dl(Op);
7424   SDValue V1 = Op.getOperand(0);
7425   SDValue V2 = Op.getOperand(1);
7426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7427   EVT VT = Op.getValueType();
7428   bool isLittleEndian = Subtarget.isLittleEndian();
7429
7430   unsigned ShiftElts, InsertAtByte;
7431   bool Swap;
7432   if (Subtarget.hasP9Vector() &&
7433       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7434                            isLittleEndian)) {
7435     if (Swap)
7436       std::swap(V1, V2);
7437     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7438     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7439     if (ShiftElts) {
7440       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7441                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7442       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7443                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7444       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7445     }
7446     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7447                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7448     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7449   }
7450
7451   if (Subtarget.hasVSX()) {
7452     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7453       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7454       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7455       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7456                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7457       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7458     }
7459
7460     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7461     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7462       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7463       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7464       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7465     }
7466
7467   }
7468
7469   if (Subtarget.hasQPX()) {
7470     if (VT.getVectorNumElements() != 4)
7471       return SDValue();
7472
7473     if (V2.isUndef()) V2 = V1;
7474
7475     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7476     if (AlignIdx != -1) {
7477       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7478                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7479     } else if (SVOp->isSplat()) {
7480       int SplatIdx = SVOp->getSplatIndex();
7481       if (SplatIdx >= 4) {
7482         std::swap(V1, V2);
7483         SplatIdx -= 4;
7484       }
7485
7486       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7487                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7488     }
7489
7490     // Lower this into a qvgpci/qvfperm pair.
7491
7492     // Compute the qvgpci literal
7493     unsigned idx = 0;
7494     for (unsigned i = 0; i < 4; ++i) {
7495       int m = SVOp->getMaskElt(i);
7496       unsigned mm = m >= 0 ? (unsigned) m : i;
7497       idx |= mm << (3-i)*3;
7498     }
7499
7500     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7501                              DAG.getConstant(idx, dl, MVT::i32));
7502     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7503   }
7504
7505   // Cases that are handled by instructions that take permute immediates
7506   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7507   // selected by the instruction selector.
7508   if (V2.isUndef()) {
7509     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7510         PPC::isSplatShuffleMask(SVOp, 2) ||
7511         PPC::isSplatShuffleMask(SVOp, 4) ||
7512         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7513         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7514         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7515         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7516         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7517         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7518         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7519         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7520         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7521         (Subtarget.hasP8Altivec() && (
7522          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7523          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7524          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7525       return Op;
7526     }
7527   }
7528
7529   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7530   // and produce a fixed permutation.  If any of these match, do not lower to
7531   // VPERM.
7532   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7533   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7534       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7535       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7536       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7537       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7538       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7539       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7540       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7541       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7542       (Subtarget.hasP8Altivec() && (
7543        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7544        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7545        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7546     return Op;
7547
7548   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7549   // perfect shuffle table to emit an optimal matching sequence.
7550   ArrayRef<int> PermMask = SVOp->getMask();
7551
7552   unsigned PFIndexes[4];
7553   bool isFourElementShuffle = true;
7554   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7555     unsigned EltNo = 8;   // Start out undef.
7556     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7557       if (PermMask[i*4+j] < 0)
7558         continue;   // Undef, ignore it.
7559
7560       unsigned ByteSource = PermMask[i*4+j];
7561       if ((ByteSource & 3) != j) {
7562         isFourElementShuffle = false;
7563         break;
7564       }
7565
7566       if (EltNo == 8) {
7567         EltNo = ByteSource/4;
7568       } else if (EltNo != ByteSource/4) {
7569         isFourElementShuffle = false;
7570         break;
7571       }
7572     }
7573     PFIndexes[i] = EltNo;
7574   }
7575
7576   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7577   // perfect shuffle vector to determine if it is cost effective to do this as
7578   // discrete instructions, or whether we should use a vperm.
7579   // For now, we skip this for little endian until such time as we have a
7580   // little-endian perfect shuffle table.
7581   if (isFourElementShuffle && !isLittleEndian) {
7582     // Compute the index in the perfect shuffle table.
7583     unsigned PFTableIndex =
7584       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7585
7586     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7587     unsigned Cost  = (PFEntry >> 30);
7588
7589     // Determining when to avoid vperm is tricky.  Many things affect the cost
7590     // of vperm, particularly how many times the perm mask needs to be computed.
7591     // For example, if the perm mask can be hoisted out of a loop or is already
7592     // used (perhaps because there are multiple permutes with the same shuffle
7593     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7594     // the loop requires an extra register.
7595     //
7596     // As a compromise, we only emit discrete instructions if the shuffle can be
7597     // generated in 3 or fewer operations.  When we have loop information
7598     // available, if this block is within a loop, we should avoid using vperm
7599     // for 3-operation perms and use a constant pool load instead.
7600     if (Cost < 3)
7601       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7602   }
7603
7604   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7605   // vector that will get spilled to the constant pool.
7606   if (V2.isUndef()) V2 = V1;
7607
7608   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7609   // that it is in input element units, not in bytes.  Convert now.
7610
7611   // For little endian, the order of the input vectors is reversed, and
7612   // the permutation mask is complemented with respect to 31.  This is
7613   // necessary to produce proper semantics with the big-endian-biased vperm
7614   // instruction.
7615   EVT EltVT = V1.getValueType().getVectorElementType();
7616   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7617
7618   SmallVector<SDValue, 16> ResultMask;
7619   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7620     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7621
7622     for (unsigned j = 0; j != BytesPerElement; ++j)
7623       if (isLittleEndian)
7624         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7625                                              dl, MVT::i32));
7626       else
7627         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7628                                              MVT::i32));
7629   }
7630
7631   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7632   if (isLittleEndian)
7633     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7634                        V2, V1, VPermMask);
7635   else
7636     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7637                        V1, V2, VPermMask);
7638 }
7639
7640 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7641 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7642 /// information about the intrinsic.
7643 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7644                                  bool &isDot, const PPCSubtarget &Subtarget) {
7645   unsigned IntrinsicID =
7646     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7647   CompareOpc = -1;
7648   isDot = false;
7649   switch (IntrinsicID) {
7650   default: return false;
7651     // Comparison predicates.
7652   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7653   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7654   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7655   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7656   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7657   case Intrinsic::ppc_altivec_vcmpequd_p:
7658     if (Subtarget.hasP8Altivec()) {
7659       CompareOpc = 199;
7660       isDot = 1;
7661     } else
7662       return false;
7663
7664     break;
7665   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7666   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7667   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7668   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7669   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7670   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7671     if (Subtarget.hasP8Altivec()) {
7672       CompareOpc = 967;
7673       isDot = 1;
7674     } else
7675       return false;
7676
7677     break;
7678   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7679   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7680   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7681   case Intrinsic::ppc_altivec_vcmpgtud_p:
7682     if (Subtarget.hasP8Altivec()) {
7683       CompareOpc = 711;
7684       isDot = 1;
7685     } else
7686       return false;
7687
7688     break;
7689     // VSX predicate comparisons use the same infrastructure
7690   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7691   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7692   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7693   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7694   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7695   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7696     if (Subtarget.hasVSX()) {
7697       switch (IntrinsicID) {
7698       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7699       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7700       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7701       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7702       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7703       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7704       }
7705       isDot = 1;
7706     }
7707     else
7708       return false;
7709
7710     break;
7711
7712     // Normal Comparisons.
7713   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7714   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7715   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7716   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7717   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7718   case Intrinsic::ppc_altivec_vcmpequd:
7719     if (Subtarget.hasP8Altivec()) {
7720       CompareOpc = 199;
7721       isDot = 0;
7722     } else
7723       return false;
7724
7725     break;
7726   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7727   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7728   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7729   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7730   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7731   case Intrinsic::ppc_altivec_vcmpgtsd:
7732     if (Subtarget.hasP8Altivec()) {
7733       CompareOpc = 967;
7734       isDot = 0;
7735     } else
7736       return false;
7737
7738     break;
7739   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7740   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7741   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7742   case Intrinsic::ppc_altivec_vcmpgtud:
7743     if (Subtarget.hasP8Altivec()) {
7744       CompareOpc = 711;
7745       isDot = 0;
7746     } else
7747       return false;
7748
7749     break;
7750   }
7751   return true;
7752 }
7753
7754 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7755 /// lower, do it, otherwise return null.
7756 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7757                                                    SelectionDAG &DAG) const {
7758   unsigned IntrinsicID =
7759     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7760
7761   if (IntrinsicID == Intrinsic::thread_pointer) {
7762     // Reads the thread pointer register, used for __builtin_thread_pointer.
7763     bool is64bit = Subtarget.isPPC64();
7764     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7765                            is64bit ? MVT::i64 : MVT::i32);
7766   }
7767
7768   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7769   // opcode number of the comparison.
7770   SDLoc dl(Op);
7771   int CompareOpc;
7772   bool isDot;
7773   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7774     return SDValue();    // Don't custom lower most intrinsics.
7775
7776   // If this is a non-dot comparison, make the VCMP node and we are done.
7777   if (!isDot) {
7778     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7779                               Op.getOperand(1), Op.getOperand(2),
7780                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7781     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7782   }
7783
7784   // Create the PPCISD altivec 'dot' comparison node.
7785   SDValue Ops[] = {
7786     Op.getOperand(2),  // LHS
7787     Op.getOperand(3),  // RHS
7788     DAG.getConstant(CompareOpc, dl, MVT::i32)
7789   };
7790   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7791   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7792
7793   // Now that we have the comparison, emit a copy from the CR to a GPR.
7794   // This is flagged to the above dot comparison.
7795   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7796                                 DAG.getRegister(PPC::CR6, MVT::i32),
7797                                 CompNode.getValue(1));
7798
7799   // Unpack the result based on how the target uses it.
7800   unsigned BitNo;   // Bit # of CR6.
7801   bool InvertBit;   // Invert result?
7802   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7803   default:  // Can't happen, don't crash on invalid number though.
7804   case 0:   // Return the value of the EQ bit of CR6.
7805     BitNo = 0; InvertBit = false;
7806     break;
7807   case 1:   // Return the inverted value of the EQ bit of CR6.
7808     BitNo = 0; InvertBit = true;
7809     break;
7810   case 2:   // Return the value of the LT bit of CR6.
7811     BitNo = 2; InvertBit = false;
7812     break;
7813   case 3:   // Return the inverted value of the LT bit of CR6.
7814     BitNo = 2; InvertBit = true;
7815     break;
7816   }
7817
7818   // Shift the bit into the low position.
7819   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7820                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7821   // Isolate the bit.
7822   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7823                       DAG.getConstant(1, dl, MVT::i32));
7824
7825   // If we are supposed to, toggle the bit.
7826   if (InvertBit)
7827     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7828                         DAG.getConstant(1, dl, MVT::i32));
7829   return Flags;
7830 }
7831
7832 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7833                                                   SelectionDAG &DAG) const {
7834   SDLoc dl(Op);
7835   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7836   // instructions), but for smaller types, we need to first extend up to v2i32
7837   // before doing going farther.
7838   if (Op.getValueType() == MVT::v2i64) {
7839     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7840     if (ExtVT != MVT::v2i32) {
7841       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7842       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7843                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7844                                         ExtVT.getVectorElementType(), 4)));
7845       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7846       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7847                        DAG.getValueType(MVT::v2i32));
7848     }
7849
7850     return Op;
7851   }
7852
7853   return SDValue();
7854 }
7855
7856 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7857                                                    SelectionDAG &DAG) const {
7858   SDLoc dl(Op);
7859   // Create a stack slot that is 16-byte aligned.
7860   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7861   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7862   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7863   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7864
7865   // Store the input value into Value#0 of the stack slot.
7866   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7867                                MachinePointerInfo());
7868   // Load it out.
7869   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
7870 }
7871
7872 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7873                                                   SelectionDAG &DAG) const {
7874   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7875          "Should only be called for ISD::INSERT_VECTOR_ELT");
7876   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7877   // We have legal lowering for constant indices but not for variable ones.
7878   if (C)
7879     return Op;
7880   return SDValue();
7881 }
7882
7883 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7884                                                    SelectionDAG &DAG) const {
7885   SDLoc dl(Op);
7886   SDNode *N = Op.getNode();
7887
7888   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7889          "Unknown extract_vector_elt type");
7890
7891   SDValue Value = N->getOperand(0);
7892
7893   // The first part of this is like the store lowering except that we don't
7894   // need to track the chain.
7895
7896   // The values are now known to be -1 (false) or 1 (true). To convert this
7897   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7898   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7899   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7900
7901   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7902   // understand how to form the extending load.
7903   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7904
7905   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7906
7907   // Now convert to an integer and store.
7908   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7909     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7910     Value);
7911
7912   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7913   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7914   MachinePointerInfo PtrInfo =
7915       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7916   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7917   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7918
7919   SDValue StoreChain = DAG.getEntryNode();
7920   SDValue Ops[] = {StoreChain,
7921                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7922                    Value, FIdx};
7923   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7924
7925   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7926     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7927
7928   // Extract the value requested.
7929   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7930   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7931   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7932
7933   SDValue IntVal =
7934       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
7935
7936   if (!Subtarget.useCRBits())
7937     return IntVal;
7938
7939   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7940 }
7941
7942 /// Lowering for QPX v4i1 loads
7943 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7944                                            SelectionDAG &DAG) const {
7945   SDLoc dl(Op);
7946   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7947   SDValue LoadChain = LN->getChain();
7948   SDValue BasePtr = LN->getBasePtr();
7949
7950   if (Op.getValueType() == MVT::v4f64 ||
7951       Op.getValueType() == MVT::v4f32) {
7952     EVT MemVT = LN->getMemoryVT();
7953     unsigned Alignment = LN->getAlignment();
7954
7955     // If this load is properly aligned, then it is legal.
7956     if (Alignment >= MemVT.getStoreSize())
7957       return Op;
7958
7959     EVT ScalarVT = Op.getValueType().getScalarType(),
7960         ScalarMemVT = MemVT.getScalarType();
7961     unsigned Stride = ScalarMemVT.getStoreSize();
7962
7963     SDValue Vals[4], LoadChains[4];
7964     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7965       SDValue Load;
7966       if (ScalarVT != ScalarMemVT)
7967         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7968                               BasePtr,
7969                               LN->getPointerInfo().getWithOffset(Idx * Stride),
7970                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
7971                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
7972       else
7973         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7974                            LN->getPointerInfo().getWithOffset(Idx * Stride),
7975                            MinAlign(Alignment, Idx * Stride),
7976                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
7977
7978       if (Idx == 0 && LN->isIndexed()) {
7979         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7980                "Unknown addressing mode on vector load");
7981         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7982                                   LN->getAddressingMode());
7983       }
7984
7985       Vals[Idx] = Load;
7986       LoadChains[Idx] = Load.getValue(1);
7987
7988       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7989                             DAG.getConstant(Stride, dl,
7990                                             BasePtr.getValueType()));
7991     }
7992
7993     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7994     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7995
7996     if (LN->isIndexed()) {
7997       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7998       return DAG.getMergeValues(RetOps, dl);
7999     }
8000
8001     SDValue RetOps[] = { Value, TF };
8002     return DAG.getMergeValues(RetOps, dl);
8003   }
8004
8005   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8006   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8007
8008   // To lower v4i1 from a byte array, we load the byte elements of the
8009   // vector and then reuse the BUILD_VECTOR logic.
8010
8011   SDValue VectElmts[4], VectElmtChains[4];
8012   for (unsigned i = 0; i < 4; ++i) {
8013     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8014     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8015
8016     VectElmts[i] = DAG.getExtLoad(
8017         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8018         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8019         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8020     VectElmtChains[i] = VectElmts[i].getValue(1);
8021   }
8022
8023   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8024   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8025
8026   SDValue RVals[] = { Value, LoadChain };
8027   return DAG.getMergeValues(RVals, dl);
8028 }
8029
8030 /// Lowering for QPX v4i1 stores
8031 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8032                                             SelectionDAG &DAG) const {
8033   SDLoc dl(Op);
8034   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8035   SDValue StoreChain = SN->getChain();
8036   SDValue BasePtr = SN->getBasePtr();
8037   SDValue Value = SN->getValue();
8038
8039   if (Value.getValueType() == MVT::v4f64 ||
8040       Value.getValueType() == MVT::v4f32) {
8041     EVT MemVT = SN->getMemoryVT();
8042     unsigned Alignment = SN->getAlignment();
8043
8044     // If this store is properly aligned, then it is legal.
8045     if (Alignment >= MemVT.getStoreSize())
8046       return Op;
8047
8048     EVT ScalarVT = Value.getValueType().getScalarType(),
8049         ScalarMemVT = MemVT.getScalarType();
8050     unsigned Stride = ScalarMemVT.getStoreSize();
8051
8052     SDValue Stores[4];
8053     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8054       SDValue Ex = DAG.getNode(
8055           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8056           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8057       SDValue Store;
8058       if (ScalarVT != ScalarMemVT)
8059         Store =
8060             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8061                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8062                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8063                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8064       else
8065         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8066                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8067                              MinAlign(Alignment, Idx * Stride),
8068                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8069
8070       if (Idx == 0 && SN->isIndexed()) {
8071         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8072                "Unknown addressing mode on vector store");
8073         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8074                                     SN->getAddressingMode());
8075       }
8076
8077       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8078                             DAG.getConstant(Stride, dl,
8079                                             BasePtr.getValueType()));
8080       Stores[Idx] = Store;
8081     }
8082
8083     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8084
8085     if (SN->isIndexed()) {
8086       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8087       return DAG.getMergeValues(RetOps, dl);
8088     }
8089
8090     return TF;
8091   }
8092
8093   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8094   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8095
8096   // The values are now known to be -1 (false) or 1 (true). To convert this
8097   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8098   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8099   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8100
8101   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8102   // understand how to form the extending load.
8103   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8104
8105   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8106
8107   // Now convert to an integer and store.
8108   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8109     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8110     Value);
8111
8112   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
8113   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
8114   MachinePointerInfo PtrInfo =
8115       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8116   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8117   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8118
8119   SDValue Ops[] = {StoreChain,
8120                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8121                    Value, FIdx};
8122   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8123
8124   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8125     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8126
8127   // Move data into the byte array.
8128   SDValue Loads[4], LoadChains[4];
8129   for (unsigned i = 0; i < 4; ++i) {
8130     unsigned Offset = 4*i;
8131     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8132     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8133
8134     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8135                            PtrInfo.getWithOffset(Offset));
8136     LoadChains[i] = Loads[i].getValue(1);
8137   }
8138
8139   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8140
8141   SDValue Stores[4];
8142   for (unsigned i = 0; i < 4; ++i) {
8143     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8144     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8145
8146     Stores[i] = DAG.getTruncStore(
8147         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8148         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8149         SN->getAAInfo());
8150   }
8151
8152   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8153
8154   return StoreChain;
8155 }
8156
8157 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8158   SDLoc dl(Op);
8159   if (Op.getValueType() == MVT::v4i32) {
8160     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8161
8162     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8163     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8164
8165     SDValue RHSSwap =   // = vrlw RHS, 16
8166       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8167
8168     // Shrinkify inputs to v8i16.
8169     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8170     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8171     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8172
8173     // Low parts multiplied together, generating 32-bit results (we ignore the
8174     // top parts).
8175     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8176                                         LHS, RHS, DAG, dl, MVT::v4i32);
8177
8178     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8179                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8180     // Shift the high parts up 16 bits.
8181     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8182                               Neg16, DAG, dl);
8183     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8184   } else if (Op.getValueType() == MVT::v8i16) {
8185     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8186
8187     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8188
8189     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8190                             LHS, RHS, Zero, DAG, dl);
8191   } else if (Op.getValueType() == MVT::v16i8) {
8192     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8193     bool isLittleEndian = Subtarget.isLittleEndian();
8194
8195     // Multiply the even 8-bit parts, producing 16-bit sums.
8196     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8197                                            LHS, RHS, DAG, dl, MVT::v8i16);
8198     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8199
8200     // Multiply the odd 8-bit parts, producing 16-bit sums.
8201     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8202                                           LHS, RHS, DAG, dl, MVT::v8i16);
8203     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8204
8205     // Merge the results together.  Because vmuleub and vmuloub are
8206     // instructions with a big-endian bias, we must reverse the
8207     // element numbering and reverse the meaning of "odd" and "even"
8208     // when generating little endian code.
8209     int Ops[16];
8210     for (unsigned i = 0; i != 8; ++i) {
8211       if (isLittleEndian) {
8212         Ops[i*2  ] = 2*i;
8213         Ops[i*2+1] = 2*i+16;
8214       } else {
8215         Ops[i*2  ] = 2*i+1;
8216         Ops[i*2+1] = 2*i+1+16;
8217       }
8218     }
8219     if (isLittleEndian)
8220       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8221     else
8222       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8223   } else {
8224     llvm_unreachable("Unknown mul to lower!");
8225   }
8226 }
8227
8228 /// LowerOperation - Provide custom lowering hooks for some operations.
8229 ///
8230 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8231   switch (Op.getOpcode()) {
8232   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8233   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8234   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8235   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8236   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8237   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8238   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8239   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8240   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8241   case ISD::VASTART:
8242     return LowerVASTART(Op, DAG);
8243
8244   case ISD::VAARG:
8245     return LowerVAARG(Op, DAG);
8246
8247   case ISD::VACOPY:
8248     return LowerVACOPY(Op, DAG);
8249
8250   case ISD::STACKRESTORE:
8251     return LowerSTACKRESTORE(Op, DAG);
8252
8253   case ISD::DYNAMIC_STACKALLOC:
8254     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8255
8256   case ISD::GET_DYNAMIC_AREA_OFFSET:
8257     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8258
8259   case ISD::EH_DWARF_CFA:
8260     return LowerEH_DWARF_CFA(Op, DAG);
8261
8262   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8263   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8264
8265   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8266   case ISD::STORE:              return LowerSTORE(Op, DAG);
8267   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8268   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8269   case ISD::FP_TO_UINT:
8270   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8271                                                       SDLoc(Op));
8272   case ISD::UINT_TO_FP:
8273   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8274   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8275
8276   // Lower 64-bit shifts.
8277   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8278   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8279   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8280
8281   // Vector-related lowering.
8282   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8283   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8284   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8285   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8286   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8287   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8288   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8289   case ISD::MUL:                return LowerMUL(Op, DAG);
8290
8291   // For counter-based loop handling.
8292   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8293
8294   // Frame & Return address.
8295   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8296   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8297   }
8298 }
8299
8300 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8301                                            SmallVectorImpl<SDValue>&Results,
8302                                            SelectionDAG &DAG) const {
8303   SDLoc dl(N);
8304   switch (N->getOpcode()) {
8305   default:
8306     llvm_unreachable("Do not know how to custom type legalize this operation!");
8307   case ISD::READCYCLECOUNTER: {
8308     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8309     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8310
8311     Results.push_back(RTB);
8312     Results.push_back(RTB.getValue(1));
8313     Results.push_back(RTB.getValue(2));
8314     break;
8315   }
8316   case ISD::INTRINSIC_W_CHAIN: {
8317     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8318         Intrinsic::ppc_is_decremented_ctr_nonzero)
8319       break;
8320
8321     assert(N->getValueType(0) == MVT::i1 &&
8322            "Unexpected result type for CTR decrement intrinsic");
8323     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8324                                  N->getValueType(0));
8325     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8326     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8327                                  N->getOperand(1));
8328
8329     Results.push_back(NewInt);
8330     Results.push_back(NewInt.getValue(1));
8331     break;
8332   }
8333   case ISD::VAARG: {
8334     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8335       return;
8336
8337     EVT VT = N->getValueType(0);
8338
8339     if (VT == MVT::i64) {
8340       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8341
8342       Results.push_back(NewNode);
8343       Results.push_back(NewNode.getValue(1));
8344     }
8345     return;
8346   }
8347   case ISD::FP_ROUND_INREG: {
8348     assert(N->getValueType(0) == MVT::ppcf128);
8349     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8350     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8351                              MVT::f64, N->getOperand(0),
8352                              DAG.getIntPtrConstant(0, dl));
8353     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8354                              MVT::f64, N->getOperand(0),
8355                              DAG.getIntPtrConstant(1, dl));
8356
8357     // Add the two halves of the long double in round-to-zero mode.
8358     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8359
8360     // We know the low half is about to be thrown away, so just use something
8361     // convenient.
8362     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8363                                 FPreg, FPreg));
8364     return;
8365   }
8366   case ISD::FP_TO_SINT:
8367   case ISD::FP_TO_UINT:
8368     // LowerFP_TO_INT() can only handle f32 and f64.
8369     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8370       return;
8371     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8372     return;
8373   }
8374 }
8375
8376 //===----------------------------------------------------------------------===//
8377 //  Other Lowering Code
8378 //===----------------------------------------------------------------------===//
8379
8380 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8381   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8382   Function *Func = Intrinsic::getDeclaration(M, Id);
8383   return Builder.CreateCall(Func, {});
8384 }
8385
8386 // The mappings for emitLeading/TrailingFence is taken from
8387 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8388 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8389                                          AtomicOrdering Ord, bool IsStore,
8390                                          bool IsLoad) const {
8391   if (Ord == AtomicOrdering::SequentiallyConsistent)
8392     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8393   if (isReleaseOrStronger(Ord))
8394     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8395   return nullptr;
8396 }
8397
8398 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8399                                           AtomicOrdering Ord, bool IsStore,
8400                                           bool IsLoad) const {
8401   if (IsLoad && isAcquireOrStronger(Ord))
8402     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8403   // FIXME: this is too conservative, a dependent branch + isync is enough.
8404   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8405   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8406   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8407   return nullptr;
8408 }
8409
8410 MachineBasicBlock *
8411 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8412                                     unsigned AtomicSize,
8413                                     unsigned BinOpcode,
8414                                     unsigned CmpOpcode,
8415                                     unsigned CmpPred) const {
8416   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8417   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8418
8419   auto LoadMnemonic = PPC::LDARX;
8420   auto StoreMnemonic = PPC::STDCX;
8421   switch (AtomicSize) {
8422   default:
8423     llvm_unreachable("Unexpected size of atomic entity");
8424   case 1:
8425     LoadMnemonic = PPC::LBARX;
8426     StoreMnemonic = PPC::STBCX;
8427     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8428     break;
8429   case 2:
8430     LoadMnemonic = PPC::LHARX;
8431     StoreMnemonic = PPC::STHCX;
8432     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8433     break;
8434   case 4:
8435     LoadMnemonic = PPC::LWARX;
8436     StoreMnemonic = PPC::STWCX;
8437     break;
8438   case 8:
8439     LoadMnemonic = PPC::LDARX;
8440     StoreMnemonic = PPC::STDCX;
8441     break;
8442   }
8443
8444   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8445   MachineFunction *F = BB->getParent();
8446   MachineFunction::iterator It = ++BB->getIterator();
8447
8448   unsigned dest = MI.getOperand(0).getReg();
8449   unsigned ptrA = MI.getOperand(1).getReg();
8450   unsigned ptrB = MI.getOperand(2).getReg();
8451   unsigned incr = MI.getOperand(3).getReg();
8452   DebugLoc dl = MI.getDebugLoc();
8453
8454   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8455   MachineBasicBlock *loop2MBB =
8456     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8457   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8458   F->insert(It, loopMBB);
8459   if (CmpOpcode)
8460     F->insert(It, loop2MBB);
8461   F->insert(It, exitMBB);
8462   exitMBB->splice(exitMBB->begin(), BB,
8463                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8464   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8465
8466   MachineRegisterInfo &RegInfo = F->getRegInfo();
8467   unsigned TmpReg = (!BinOpcode) ? incr :
8468     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8469                                            : &PPC::GPRCRegClass);
8470
8471   //  thisMBB:
8472   //   ...
8473   //   fallthrough --> loopMBB
8474   BB->addSuccessor(loopMBB);
8475
8476   //  loopMBB:
8477   //   l[wd]arx dest, ptr
8478   //   add r0, dest, incr
8479   //   st[wd]cx. r0, ptr
8480   //   bne- loopMBB
8481   //   fallthrough --> exitMBB
8482
8483   // For max/min...
8484   //  loopMBB:
8485   //   l[wd]arx dest, ptr
8486   //   cmpl?[wd] incr, dest
8487   //   bgt exitMBB
8488   //  loop2MBB:
8489   //   st[wd]cx. dest, ptr
8490   //   bne- loopMBB
8491   //   fallthrough --> exitMBB
8492
8493   BB = loopMBB;
8494   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8495     .addReg(ptrA).addReg(ptrB);
8496   if (BinOpcode)
8497     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8498   if (CmpOpcode) {
8499     // Signed comparisons of byte or halfword values must be sign-extended.
8500     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8501       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8502       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8503               ExtReg).addReg(dest);
8504       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8505         .addReg(incr).addReg(ExtReg);
8506     } else
8507       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8508         .addReg(incr).addReg(dest);
8509
8510     BuildMI(BB, dl, TII->get(PPC::BCC))
8511       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8512     BB->addSuccessor(loop2MBB);
8513     BB->addSuccessor(exitMBB);
8514     BB = loop2MBB;
8515   }
8516   BuildMI(BB, dl, TII->get(StoreMnemonic))
8517     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8518   BuildMI(BB, dl, TII->get(PPC::BCC))
8519     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8520   BB->addSuccessor(loopMBB);
8521   BB->addSuccessor(exitMBB);
8522
8523   //  exitMBB:
8524   //   ...
8525   BB = exitMBB;
8526   return BB;
8527 }
8528
8529 MachineBasicBlock *
8530 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8531                                             MachineBasicBlock *BB,
8532                                             bool is8bit, // operation
8533                                             unsigned BinOpcode,
8534                                             unsigned CmpOpcode,
8535                                             unsigned CmpPred) const {
8536   // If we support part-word atomic mnemonics, just use them
8537   if (Subtarget.hasPartwordAtomics())
8538     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8539                             CmpOpcode, CmpPred);
8540
8541   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8542   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8543   // In 64 bit mode we have to use 64 bits for addresses, even though the
8544   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8545   // registers without caring whether they're 32 or 64, but here we're
8546   // doing actual arithmetic on the addresses.
8547   bool is64bit = Subtarget.isPPC64();
8548   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8549
8550   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8551   MachineFunction *F = BB->getParent();
8552   MachineFunction::iterator It = ++BB->getIterator();
8553
8554   unsigned dest = MI.getOperand(0).getReg();
8555   unsigned ptrA = MI.getOperand(1).getReg();
8556   unsigned ptrB = MI.getOperand(2).getReg();
8557   unsigned incr = MI.getOperand(3).getReg();
8558   DebugLoc dl = MI.getDebugLoc();
8559
8560   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8561   MachineBasicBlock *loop2MBB =
8562     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8563   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8564   F->insert(It, loopMBB);
8565   if (CmpOpcode)
8566     F->insert(It, loop2MBB);
8567   F->insert(It, exitMBB);
8568   exitMBB->splice(exitMBB->begin(), BB,
8569                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8570   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8571
8572   MachineRegisterInfo &RegInfo = F->getRegInfo();
8573   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8574                                           : &PPC::GPRCRegClass;
8575   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8576   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8577   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8578   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8579   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8580   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8581   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8582   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8583   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8584   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8585   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8586   unsigned Ptr1Reg;
8587   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8588
8589   //  thisMBB:
8590   //   ...
8591   //   fallthrough --> loopMBB
8592   BB->addSuccessor(loopMBB);
8593
8594   // The 4-byte load must be aligned, while a char or short may be
8595   // anywhere in the word.  Hence all this nasty bookkeeping code.
8596   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8597   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8598   //   xori shift, shift1, 24 [16]
8599   //   rlwinm ptr, ptr1, 0, 0, 29
8600   //   slw incr2, incr, shift
8601   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8602   //   slw mask, mask2, shift
8603   //  loopMBB:
8604   //   lwarx tmpDest, ptr
8605   //   add tmp, tmpDest, incr2
8606   //   andc tmp2, tmpDest, mask
8607   //   and tmp3, tmp, mask
8608   //   or tmp4, tmp3, tmp2
8609   //   stwcx. tmp4, ptr
8610   //   bne- loopMBB
8611   //   fallthrough --> exitMBB
8612   //   srw dest, tmpDest, shift
8613   if (ptrA != ZeroReg) {
8614     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8615     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8616       .addReg(ptrA).addReg(ptrB);
8617   } else {
8618     Ptr1Reg = ptrB;
8619   }
8620   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8621       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8622   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8623       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8624   if (is64bit)
8625     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8626       .addReg(Ptr1Reg).addImm(0).addImm(61);
8627   else
8628     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8629       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8630   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8631       .addReg(incr).addReg(ShiftReg);
8632   if (is8bit)
8633     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8634   else {
8635     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8636     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8637   }
8638   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8639       .addReg(Mask2Reg).addReg(ShiftReg);
8640
8641   BB = loopMBB;
8642   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8643     .addReg(ZeroReg).addReg(PtrReg);
8644   if (BinOpcode)
8645     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8646       .addReg(Incr2Reg).addReg(TmpDestReg);
8647   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8648     .addReg(TmpDestReg).addReg(MaskReg);
8649   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8650     .addReg(TmpReg).addReg(MaskReg);
8651   if (CmpOpcode) {
8652     // For unsigned comparisons, we can directly compare the shifted values.
8653     // For signed comparisons we shift and sign extend.
8654     unsigned SReg = RegInfo.createVirtualRegister(RC);
8655     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
8656       .addReg(TmpDestReg).addReg(MaskReg);
8657     unsigned ValueReg = SReg;
8658     unsigned CmpReg = Incr2Reg;
8659     if (CmpOpcode == PPC::CMPW) {
8660       ValueReg = RegInfo.createVirtualRegister(RC);
8661       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
8662         .addReg(SReg).addReg(ShiftReg);
8663       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
8664       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
8665         .addReg(ValueReg);
8666       ValueReg = ValueSReg;
8667       CmpReg = incr;
8668     }
8669     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8670       .addReg(CmpReg).addReg(ValueReg);
8671     BuildMI(BB, dl, TII->get(PPC::BCC))
8672       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8673     BB->addSuccessor(loop2MBB);
8674     BB->addSuccessor(exitMBB);
8675     BB = loop2MBB;
8676   }
8677   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8678     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8679   BuildMI(BB, dl, TII->get(PPC::STWCX))
8680     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8681   BuildMI(BB, dl, TII->get(PPC::BCC))
8682     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8683   BB->addSuccessor(loopMBB);
8684   BB->addSuccessor(exitMBB);
8685
8686   //  exitMBB:
8687   //   ...
8688   BB = exitMBB;
8689   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8690     .addReg(ShiftReg);
8691   return BB;
8692 }
8693
8694 llvm::MachineBasicBlock *
8695 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8696                                     MachineBasicBlock *MBB) const {
8697   DebugLoc DL = MI.getDebugLoc();
8698   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8699
8700   MachineFunction *MF = MBB->getParent();
8701   MachineRegisterInfo &MRI = MF->getRegInfo();
8702
8703   const BasicBlock *BB = MBB->getBasicBlock();
8704   MachineFunction::iterator I = ++MBB->getIterator();
8705
8706   // Memory Reference
8707   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8708   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8709
8710   unsigned DstReg = MI.getOperand(0).getReg();
8711   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8712   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8713   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8714   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8715
8716   MVT PVT = getPointerTy(MF->getDataLayout());
8717   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8718          "Invalid Pointer Size!");
8719   // For v = setjmp(buf), we generate
8720   //
8721   // thisMBB:
8722   //  SjLjSetup mainMBB
8723   //  bl mainMBB
8724   //  v_restore = 1
8725   //  b sinkMBB
8726   //
8727   // mainMBB:
8728   //  buf[LabelOffset] = LR
8729   //  v_main = 0
8730   //
8731   // sinkMBB:
8732   //  v = phi(main, restore)
8733   //
8734
8735   MachineBasicBlock *thisMBB = MBB;
8736   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8737   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8738   MF->insert(I, mainMBB);
8739   MF->insert(I, sinkMBB);
8740
8741   MachineInstrBuilder MIB;
8742
8743   // Transfer the remainder of BB and its successor edges to sinkMBB.
8744   sinkMBB->splice(sinkMBB->begin(), MBB,
8745                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8746   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8747
8748   // Note that the structure of the jmp_buf used here is not compatible
8749   // with that used by libc, and is not designed to be. Specifically, it
8750   // stores only those 'reserved' registers that LLVM does not otherwise
8751   // understand how to spill. Also, by convention, by the time this
8752   // intrinsic is called, Clang has already stored the frame address in the
8753   // first slot of the buffer and stack address in the third. Following the
8754   // X86 target code, we'll store the jump address in the second slot. We also
8755   // need to save the TOC pointer (R2) to handle jumps between shared
8756   // libraries, and that will be stored in the fourth slot. The thread
8757   // identifier (R13) is not affected.
8758
8759   // thisMBB:
8760   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8761   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8762   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8763
8764   // Prepare IP either in reg.
8765   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8766   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8767   unsigned BufReg = MI.getOperand(1).getReg();
8768
8769   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8770     setUsesTOCBasePtr(*MBB->getParent());
8771     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8772             .addReg(PPC::X2)
8773             .addImm(TOCOffset)
8774             .addReg(BufReg);
8775     MIB.setMemRefs(MMOBegin, MMOEnd);
8776   }
8777
8778   // Naked functions never have a base pointer, and so we use r1. For all
8779   // other functions, this decision must be delayed until during PEI.
8780   unsigned BaseReg;
8781   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8782     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8783   else
8784     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8785
8786   MIB = BuildMI(*thisMBB, MI, DL,
8787                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8788             .addReg(BaseReg)
8789             .addImm(BPOffset)
8790             .addReg(BufReg);
8791   MIB.setMemRefs(MMOBegin, MMOEnd);
8792
8793   // Setup
8794   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8795   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8796   MIB.addRegMask(TRI->getNoPreservedMask());
8797
8798   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8799
8800   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8801           .addMBB(mainMBB);
8802   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8803
8804   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8805   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8806
8807   // mainMBB:
8808   //  mainDstReg = 0
8809   MIB =
8810       BuildMI(mainMBB, DL,
8811               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8812
8813   // Store IP
8814   if (Subtarget.isPPC64()) {
8815     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8816             .addReg(LabelReg)
8817             .addImm(LabelOffset)
8818             .addReg(BufReg);
8819   } else {
8820     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8821             .addReg(LabelReg)
8822             .addImm(LabelOffset)
8823             .addReg(BufReg);
8824   }
8825
8826   MIB.setMemRefs(MMOBegin, MMOEnd);
8827
8828   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8829   mainMBB->addSuccessor(sinkMBB);
8830
8831   // sinkMBB:
8832   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8833           TII->get(PPC::PHI), DstReg)
8834     .addReg(mainDstReg).addMBB(mainMBB)
8835     .addReg(restoreDstReg).addMBB(thisMBB);
8836
8837   MI.eraseFromParent();
8838   return sinkMBB;
8839 }
8840
8841 MachineBasicBlock *
8842 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8843                                      MachineBasicBlock *MBB) const {
8844   DebugLoc DL = MI.getDebugLoc();
8845   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8846
8847   MachineFunction *MF = MBB->getParent();
8848   MachineRegisterInfo &MRI = MF->getRegInfo();
8849
8850   // Memory Reference
8851   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8852   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8853
8854   MVT PVT = getPointerTy(MF->getDataLayout());
8855   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8856          "Invalid Pointer Size!");
8857
8858   const TargetRegisterClass *RC =
8859     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8860   unsigned Tmp = MRI.createVirtualRegister(RC);
8861   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8862   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8863   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8864   unsigned BP =
8865       (PVT == MVT::i64)
8866           ? PPC::X30
8867           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
8868                                                               : PPC::R30);
8869
8870   MachineInstrBuilder MIB;
8871
8872   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8873   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8874   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8875   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8876
8877   unsigned BufReg = MI.getOperand(0).getReg();
8878
8879   // Reload FP (the jumped-to function may not have had a
8880   // frame pointer, and if so, then its r31 will be restored
8881   // as necessary).
8882   if (PVT == MVT::i64) {
8883     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8884             .addImm(0)
8885             .addReg(BufReg);
8886   } else {
8887     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8888             .addImm(0)
8889             .addReg(BufReg);
8890   }
8891   MIB.setMemRefs(MMOBegin, MMOEnd);
8892
8893   // Reload IP
8894   if (PVT == MVT::i64) {
8895     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8896             .addImm(LabelOffset)
8897             .addReg(BufReg);
8898   } else {
8899     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8900             .addImm(LabelOffset)
8901             .addReg(BufReg);
8902   }
8903   MIB.setMemRefs(MMOBegin, MMOEnd);
8904
8905   // Reload SP
8906   if (PVT == MVT::i64) {
8907     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8908             .addImm(SPOffset)
8909             .addReg(BufReg);
8910   } else {
8911     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8912             .addImm(SPOffset)
8913             .addReg(BufReg);
8914   }
8915   MIB.setMemRefs(MMOBegin, MMOEnd);
8916
8917   // Reload BP
8918   if (PVT == MVT::i64) {
8919     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8920             .addImm(BPOffset)
8921             .addReg(BufReg);
8922   } else {
8923     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8924             .addImm(BPOffset)
8925             .addReg(BufReg);
8926   }
8927   MIB.setMemRefs(MMOBegin, MMOEnd);
8928
8929   // Reload TOC
8930   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8931     setUsesTOCBasePtr(*MBB->getParent());
8932     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8933             .addImm(TOCOffset)
8934             .addReg(BufReg);
8935
8936     MIB.setMemRefs(MMOBegin, MMOEnd);
8937   }
8938
8939   // Jump
8940   BuildMI(*MBB, MI, DL,
8941           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8942   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8943
8944   MI.eraseFromParent();
8945   return MBB;
8946 }
8947
8948 MachineBasicBlock *
8949 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8950                                                MachineBasicBlock *BB) const {
8951   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
8952       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8953     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8954         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8955       // Call lowering should have added an r2 operand to indicate a dependence
8956       // on the TOC base pointer value. It can't however, because there is no
8957       // way to mark the dependence as implicit there, and so the stackmap code
8958       // will confuse it with a regular operand. Instead, add the dependence
8959       // here.
8960       setUsesTOCBasePtr(*BB->getParent());
8961       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8962     }
8963
8964     return emitPatchPoint(MI, BB);
8965   }
8966
8967   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8968       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
8969     return emitEHSjLjSetJmp(MI, BB);
8970   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8971              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
8972     return emitEHSjLjLongJmp(MI, BB);
8973   }
8974
8975   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8976
8977   // To "insert" these instructions we actually have to insert their
8978   // control-flow patterns.
8979   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8980   MachineFunction::iterator It = ++BB->getIterator();
8981
8982   MachineFunction *F = BB->getParent();
8983
8984   if (Subtarget.hasISEL() &&
8985       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8986        MI.getOpcode() == PPC::SELECT_CC_I8 ||
8987        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
8988     SmallVector<MachineOperand, 2> Cond;
8989     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8990         MI.getOpcode() == PPC::SELECT_CC_I8)
8991       Cond.push_back(MI.getOperand(4));
8992     else
8993       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8994     Cond.push_back(MI.getOperand(1));
8995
8996     DebugLoc dl = MI.getDebugLoc();
8997     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
8998                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
8999   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9000              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9001              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9002              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9003              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9004              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9005              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9006              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9007              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9008              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9009              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9010              MI.getOpcode() == PPC::SELECT_I4 ||
9011              MI.getOpcode() == PPC::SELECT_I8 ||
9012              MI.getOpcode() == PPC::SELECT_F4 ||
9013              MI.getOpcode() == PPC::SELECT_F8 ||
9014              MI.getOpcode() == PPC::SELECT_QFRC ||
9015              MI.getOpcode() == PPC::SELECT_QSRC ||
9016              MI.getOpcode() == PPC::SELECT_QBRC ||
9017              MI.getOpcode() == PPC::SELECT_VRRC ||
9018              MI.getOpcode() == PPC::SELECT_VSFRC ||
9019              MI.getOpcode() == PPC::SELECT_VSSRC ||
9020              MI.getOpcode() == PPC::SELECT_VSRC) {
9021     // The incoming instruction knows the destination vreg to set, the
9022     // condition code register to branch on, the true/false values to
9023     // select between, and a branch opcode to use.
9024
9025     //  thisMBB:
9026     //  ...
9027     //   TrueVal = ...
9028     //   cmpTY ccX, r1, r2
9029     //   bCC copy1MBB
9030     //   fallthrough --> copy0MBB
9031     MachineBasicBlock *thisMBB = BB;
9032     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9033     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9034     DebugLoc dl = MI.getDebugLoc();
9035     F->insert(It, copy0MBB);
9036     F->insert(It, sinkMBB);
9037
9038     // Transfer the remainder of BB and its successor edges to sinkMBB.
9039     sinkMBB->splice(sinkMBB->begin(), BB,
9040                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9041     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9042
9043     // Next, add the true and fallthrough blocks as its successors.
9044     BB->addSuccessor(copy0MBB);
9045     BB->addSuccessor(sinkMBB);
9046
9047     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9048         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9049         MI.getOpcode() == PPC::SELECT_QFRC ||
9050         MI.getOpcode() == PPC::SELECT_QSRC ||
9051         MI.getOpcode() == PPC::SELECT_QBRC ||
9052         MI.getOpcode() == PPC::SELECT_VRRC ||
9053         MI.getOpcode() == PPC::SELECT_VSFRC ||
9054         MI.getOpcode() == PPC::SELECT_VSSRC ||
9055         MI.getOpcode() == PPC::SELECT_VSRC) {
9056       BuildMI(BB, dl, TII->get(PPC::BC))
9057           .addReg(MI.getOperand(1).getReg())
9058           .addMBB(sinkMBB);
9059     } else {
9060       unsigned SelectPred = MI.getOperand(4).getImm();
9061       BuildMI(BB, dl, TII->get(PPC::BCC))
9062           .addImm(SelectPred)
9063           .addReg(MI.getOperand(1).getReg())
9064           .addMBB(sinkMBB);
9065     }
9066
9067     //  copy0MBB:
9068     //   %FalseValue = ...
9069     //   # fallthrough to sinkMBB
9070     BB = copy0MBB;
9071
9072     // Update machine-CFG edges
9073     BB->addSuccessor(sinkMBB);
9074
9075     //  sinkMBB:
9076     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9077     //  ...
9078     BB = sinkMBB;
9079     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9080         .addReg(MI.getOperand(3).getReg())
9081         .addMBB(copy0MBB)
9082         .addReg(MI.getOperand(2).getReg())
9083         .addMBB(thisMBB);
9084   } else if (MI.getOpcode() == PPC::ReadTB) {
9085     // To read the 64-bit time-base register on a 32-bit target, we read the
9086     // two halves. Should the counter have wrapped while it was being read, we
9087     // need to try again.
9088     // ...
9089     // readLoop:
9090     // mfspr Rx,TBU # load from TBU
9091     // mfspr Ry,TB  # load from TB
9092     // mfspr Rz,TBU # load from TBU
9093     // cmpw crX,Rx,Rz # check if 'old'='new'
9094     // bne readLoop   # branch if they're not equal
9095     // ...
9096
9097     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9098     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9099     DebugLoc dl = MI.getDebugLoc();
9100     F->insert(It, readMBB);
9101     F->insert(It, sinkMBB);
9102
9103     // Transfer the remainder of BB and its successor edges to sinkMBB.
9104     sinkMBB->splice(sinkMBB->begin(), BB,
9105                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9106     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9107
9108     BB->addSuccessor(readMBB);
9109     BB = readMBB;
9110
9111     MachineRegisterInfo &RegInfo = F->getRegInfo();
9112     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9113     unsigned LoReg = MI.getOperand(0).getReg();
9114     unsigned HiReg = MI.getOperand(1).getReg();
9115
9116     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9117     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9118     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9119
9120     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9121
9122     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9123       .addReg(HiReg).addReg(ReadAgainReg);
9124     BuildMI(BB, dl, TII->get(PPC::BCC))
9125       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9126
9127     BB->addSuccessor(readMBB);
9128     BB->addSuccessor(sinkMBB);
9129   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9130     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9131   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9132     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9133   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9134     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9135   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9136     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9137
9138   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9139     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9140   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9141     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9142   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9143     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9144   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9145     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9146
9147   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9148     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9149   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9150     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9151   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9152     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9153   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9154     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9155
9156   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9157     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9158   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9159     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9160   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9161     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9162   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9163     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9164
9165   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9166     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9167   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9168     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9169   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9170     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9171   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9172     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9173
9174   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9175     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9176   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9177     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9178   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9179     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9180   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9181     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9182
9183   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9184     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9185   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9186     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9187   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9188     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9189   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9190     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9191
9192   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9193     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9194   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9195     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9196   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9197     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9198   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9199     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9200
9201   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9202     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9203   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9204     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9205   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9206     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9207   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9208     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9209
9210   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9211     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9212   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9213     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9214   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9215     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9216   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9217     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9218
9219   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9220     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9221   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9222     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9223   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9224     BB = EmitAtomicBinary(MI, BB, 4, 0);
9225   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9226     BB = EmitAtomicBinary(MI, BB, 8, 0);
9227
9228   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9229            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9230            (Subtarget.hasPartwordAtomics() &&
9231             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9232            (Subtarget.hasPartwordAtomics() &&
9233             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9234     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9235
9236     auto LoadMnemonic = PPC::LDARX;
9237     auto StoreMnemonic = PPC::STDCX;
9238     switch (MI.getOpcode()) {
9239     default:
9240       llvm_unreachable("Compare and swap of unknown size");
9241     case PPC::ATOMIC_CMP_SWAP_I8:
9242       LoadMnemonic = PPC::LBARX;
9243       StoreMnemonic = PPC::STBCX;
9244       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9245       break;
9246     case PPC::ATOMIC_CMP_SWAP_I16:
9247       LoadMnemonic = PPC::LHARX;
9248       StoreMnemonic = PPC::STHCX;
9249       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9250       break;
9251     case PPC::ATOMIC_CMP_SWAP_I32:
9252       LoadMnemonic = PPC::LWARX;
9253       StoreMnemonic = PPC::STWCX;
9254       break;
9255     case PPC::ATOMIC_CMP_SWAP_I64:
9256       LoadMnemonic = PPC::LDARX;
9257       StoreMnemonic = PPC::STDCX;
9258       break;
9259     }
9260     unsigned dest = MI.getOperand(0).getReg();
9261     unsigned ptrA = MI.getOperand(1).getReg();
9262     unsigned ptrB = MI.getOperand(2).getReg();
9263     unsigned oldval = MI.getOperand(3).getReg();
9264     unsigned newval = MI.getOperand(4).getReg();
9265     DebugLoc dl = MI.getDebugLoc();
9266
9267     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9268     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9269     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9270     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9271     F->insert(It, loop1MBB);
9272     F->insert(It, loop2MBB);
9273     F->insert(It, midMBB);
9274     F->insert(It, exitMBB);
9275     exitMBB->splice(exitMBB->begin(), BB,
9276                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9277     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9278
9279     //  thisMBB:
9280     //   ...
9281     //   fallthrough --> loopMBB
9282     BB->addSuccessor(loop1MBB);
9283
9284     // loop1MBB:
9285     //   l[bhwd]arx dest, ptr
9286     //   cmp[wd] dest, oldval
9287     //   bne- midMBB
9288     // loop2MBB:
9289     //   st[bhwd]cx. newval, ptr
9290     //   bne- loopMBB
9291     //   b exitBB
9292     // midMBB:
9293     //   st[bhwd]cx. dest, ptr
9294     // exitBB:
9295     BB = loop1MBB;
9296     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9297       .addReg(ptrA).addReg(ptrB);
9298     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9299       .addReg(oldval).addReg(dest);
9300     BuildMI(BB, dl, TII->get(PPC::BCC))
9301       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9302     BB->addSuccessor(loop2MBB);
9303     BB->addSuccessor(midMBB);
9304
9305     BB = loop2MBB;
9306     BuildMI(BB, dl, TII->get(StoreMnemonic))
9307       .addReg(newval).addReg(ptrA).addReg(ptrB);
9308     BuildMI(BB, dl, TII->get(PPC::BCC))
9309       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9310     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9311     BB->addSuccessor(loop1MBB);
9312     BB->addSuccessor(exitMBB);
9313
9314     BB = midMBB;
9315     BuildMI(BB, dl, TII->get(StoreMnemonic))
9316       .addReg(dest).addReg(ptrA).addReg(ptrB);
9317     BB->addSuccessor(exitMBB);
9318
9319     //  exitMBB:
9320     //   ...
9321     BB = exitMBB;
9322   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9323              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9324     // We must use 64-bit registers for addresses when targeting 64-bit,
9325     // since we're actually doing arithmetic on them.  Other registers
9326     // can be 32-bit.
9327     bool is64bit = Subtarget.isPPC64();
9328     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9329
9330     unsigned dest = MI.getOperand(0).getReg();
9331     unsigned ptrA = MI.getOperand(1).getReg();
9332     unsigned ptrB = MI.getOperand(2).getReg();
9333     unsigned oldval = MI.getOperand(3).getReg();
9334     unsigned newval = MI.getOperand(4).getReg();
9335     DebugLoc dl = MI.getDebugLoc();
9336
9337     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9338     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9339     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9340     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9341     F->insert(It, loop1MBB);
9342     F->insert(It, loop2MBB);
9343     F->insert(It, midMBB);
9344     F->insert(It, exitMBB);
9345     exitMBB->splice(exitMBB->begin(), BB,
9346                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9347     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9348
9349     MachineRegisterInfo &RegInfo = F->getRegInfo();
9350     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9351                                             : &PPC::GPRCRegClass;
9352     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9353     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9354     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
9355     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9356     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9357     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9358     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9359     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9360     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9361     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9362     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9363     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9364     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9365     unsigned Ptr1Reg;
9366     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9367     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9368     //  thisMBB:
9369     //   ...
9370     //   fallthrough --> loopMBB
9371     BB->addSuccessor(loop1MBB);
9372
9373     // The 4-byte load must be aligned, while a char or short may be
9374     // anywhere in the word.  Hence all this nasty bookkeeping code.
9375     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9376     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9377     //   xori shift, shift1, 24 [16]
9378     //   rlwinm ptr, ptr1, 0, 0, 29
9379     //   slw newval2, newval, shift
9380     //   slw oldval2, oldval,shift
9381     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9382     //   slw mask, mask2, shift
9383     //   and newval3, newval2, mask
9384     //   and oldval3, oldval2, mask
9385     // loop1MBB:
9386     //   lwarx tmpDest, ptr
9387     //   and tmp, tmpDest, mask
9388     //   cmpw tmp, oldval3
9389     //   bne- midMBB
9390     // loop2MBB:
9391     //   andc tmp2, tmpDest, mask
9392     //   or tmp4, tmp2, newval3
9393     //   stwcx. tmp4, ptr
9394     //   bne- loop1MBB
9395     //   b exitBB
9396     // midMBB:
9397     //   stwcx. tmpDest, ptr
9398     // exitBB:
9399     //   srw dest, tmpDest, shift
9400     if (ptrA != ZeroReg) {
9401       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9402       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9403         .addReg(ptrA).addReg(ptrB);
9404     } else {
9405       Ptr1Reg = ptrB;
9406     }
9407     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9408         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9409     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9410         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9411     if (is64bit)
9412       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9413         .addReg(Ptr1Reg).addImm(0).addImm(61);
9414     else
9415       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9416         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9417     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9418         .addReg(newval).addReg(ShiftReg);
9419     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9420         .addReg(oldval).addReg(ShiftReg);
9421     if (is8bit)
9422       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9423     else {
9424       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9425       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9426         .addReg(Mask3Reg).addImm(65535);
9427     }
9428     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9429         .addReg(Mask2Reg).addReg(ShiftReg);
9430     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9431         .addReg(NewVal2Reg).addReg(MaskReg);
9432     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9433         .addReg(OldVal2Reg).addReg(MaskReg);
9434
9435     BB = loop1MBB;
9436     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9437         .addReg(ZeroReg).addReg(PtrReg);
9438     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9439         .addReg(TmpDestReg).addReg(MaskReg);
9440     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9441         .addReg(TmpReg).addReg(OldVal3Reg);
9442     BuildMI(BB, dl, TII->get(PPC::BCC))
9443         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9444     BB->addSuccessor(loop2MBB);
9445     BB->addSuccessor(midMBB);
9446
9447     BB = loop2MBB;
9448     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9449         .addReg(TmpDestReg).addReg(MaskReg);
9450     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9451         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9452     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9453         .addReg(ZeroReg).addReg(PtrReg);
9454     BuildMI(BB, dl, TII->get(PPC::BCC))
9455       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9456     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9457     BB->addSuccessor(loop1MBB);
9458     BB->addSuccessor(exitMBB);
9459
9460     BB = midMBB;
9461     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9462       .addReg(ZeroReg).addReg(PtrReg);
9463     BB->addSuccessor(exitMBB);
9464
9465     //  exitMBB:
9466     //   ...
9467     BB = exitMBB;
9468     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9469       .addReg(ShiftReg);
9470   } else if (MI.getOpcode() == PPC::FADDrtz) {
9471     // This pseudo performs an FADD with rounding mode temporarily forced
9472     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9473     // is not modeled at the SelectionDAG level.
9474     unsigned Dest = MI.getOperand(0).getReg();
9475     unsigned Src1 = MI.getOperand(1).getReg();
9476     unsigned Src2 = MI.getOperand(2).getReg();
9477     DebugLoc dl = MI.getDebugLoc();
9478
9479     MachineRegisterInfo &RegInfo = F->getRegInfo();
9480     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9481
9482     // Save FPSCR value.
9483     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9484
9485     // Set rounding mode to round-to-zero.
9486     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9487     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9488
9489     // Perform addition.
9490     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9491
9492     // Restore FPSCR value.
9493     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9494   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9495              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9496              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9497              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9498     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9499                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9500                           ? PPC::ANDIo8
9501                           : PPC::ANDIo;
9502     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9503                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9504
9505     MachineRegisterInfo &RegInfo = F->getRegInfo();
9506     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9507                                                   &PPC::GPRCRegClass :
9508                                                   &PPC::G8RCRegClass);
9509
9510     DebugLoc dl = MI.getDebugLoc();
9511     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9512         .addReg(MI.getOperand(1).getReg())
9513         .addImm(1);
9514     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9515             MI.getOperand(0).getReg())
9516         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9517   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9518     DebugLoc Dl = MI.getDebugLoc();
9519     MachineRegisterInfo &RegInfo = F->getRegInfo();
9520     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9521     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9522     return BB;
9523   } else {
9524     llvm_unreachable("Unexpected instr type to insert");
9525   }
9526
9527   MI.eraseFromParent(); // The pseudo instruction is gone now.
9528   return BB;
9529 }
9530
9531 //===----------------------------------------------------------------------===//
9532 // Target Optimization Hooks
9533 //===----------------------------------------------------------------------===//
9534
9535 static std::string getRecipOp(const char *Base, EVT VT) {
9536   std::string RecipOp(Base);
9537   if (VT.getScalarType() == MVT::f64)
9538     RecipOp += "d";
9539   else
9540     RecipOp += "f";
9541
9542   if (VT.isVector())
9543     RecipOp = "vec-" + RecipOp;
9544
9545   return RecipOp;
9546 }
9547
9548 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9549                                             DAGCombinerInfo &DCI,
9550                                             unsigned &RefinementSteps,
9551                                             bool &UseOneConstNR) const {
9552   EVT VT = Operand.getValueType();
9553   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9554       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9555       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9556       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9557       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9558       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9559     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9560     std::string RecipOp = getRecipOp("sqrt", VT);
9561     if (!Recips.isEnabled(RecipOp))
9562       return SDValue();
9563
9564     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9565     UseOneConstNR = true;
9566     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9567   }
9568   return SDValue();
9569 }
9570
9571 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9572                                             DAGCombinerInfo &DCI,
9573                                             unsigned &RefinementSteps) const {
9574   EVT VT = Operand.getValueType();
9575   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9576       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9577       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9578       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9579       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9580       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9581     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9582     std::string RecipOp = getRecipOp("div", VT);
9583     if (!Recips.isEnabled(RecipOp))
9584       return SDValue();
9585
9586     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9587     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9588   }
9589   return SDValue();
9590 }
9591
9592 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9593   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9594   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9595   // enabled for division), this functionality is redundant with the default
9596   // combiner logic (once the division -> reciprocal/multiply transformation
9597   // has taken place). As a result, this matters more for older cores than for
9598   // newer ones.
9599
9600   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9601   // reciprocal if there are two or more FDIVs (for embedded cores with only
9602   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9603   switch (Subtarget.getDarwinDirective()) {
9604   default:
9605     return 3;
9606   case PPC::DIR_440:
9607   case PPC::DIR_A2:
9608   case PPC::DIR_E500mc:
9609   case PPC::DIR_E5500:
9610     return 2;
9611   }
9612 }
9613
9614 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9615 // collapsed, and so we need to look through chains of them.
9616 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9617                                      int64_t& Offset, SelectionDAG &DAG) {
9618   if (DAG.isBaseWithConstantOffset(Loc)) {
9619     Base = Loc.getOperand(0);
9620     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9621
9622     // The base might itself be a base plus an offset, and if so, accumulate
9623     // that as well.
9624     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9625   }
9626 }
9627
9628 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9629                             unsigned Bytes, int Dist,
9630                             SelectionDAG &DAG) {
9631   if (VT.getSizeInBits() / 8 != Bytes)
9632     return false;
9633
9634   SDValue BaseLoc = Base->getBasePtr();
9635   if (Loc.getOpcode() == ISD::FrameIndex) {
9636     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9637       return false;
9638     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9639     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9640     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9641     int FS  = MFI->getObjectSize(FI);
9642     int BFS = MFI->getObjectSize(BFI);
9643     if (FS != BFS || FS != (int)Bytes) return false;
9644     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9645   }
9646
9647   SDValue Base1 = Loc, Base2 = BaseLoc;
9648   int64_t Offset1 = 0, Offset2 = 0;
9649   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9650   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9651   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9652     return true;
9653
9654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655   const GlobalValue *GV1 = nullptr;
9656   const GlobalValue *GV2 = nullptr;
9657   Offset1 = 0;
9658   Offset2 = 0;
9659   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9660   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9661   if (isGA1 && isGA2 && GV1 == GV2)
9662     return Offset1 == (Offset2 + Dist*Bytes);
9663   return false;
9664 }
9665
9666 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9667 // not enforce equality of the chain operands.
9668 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9669                             unsigned Bytes, int Dist,
9670                             SelectionDAG &DAG) {
9671   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9672     EVT VT = LS->getMemoryVT();
9673     SDValue Loc = LS->getBasePtr();
9674     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9675   }
9676
9677   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9678     EVT VT;
9679     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9680     default: return false;
9681     case Intrinsic::ppc_qpx_qvlfd:
9682     case Intrinsic::ppc_qpx_qvlfda:
9683       VT = MVT::v4f64;
9684       break;
9685     case Intrinsic::ppc_qpx_qvlfs:
9686     case Intrinsic::ppc_qpx_qvlfsa:
9687       VT = MVT::v4f32;
9688       break;
9689     case Intrinsic::ppc_qpx_qvlfcd:
9690     case Intrinsic::ppc_qpx_qvlfcda:
9691       VT = MVT::v2f64;
9692       break;
9693     case Intrinsic::ppc_qpx_qvlfcs:
9694     case Intrinsic::ppc_qpx_qvlfcsa:
9695       VT = MVT::v2f32;
9696       break;
9697     case Intrinsic::ppc_qpx_qvlfiwa:
9698     case Intrinsic::ppc_qpx_qvlfiwz:
9699     case Intrinsic::ppc_altivec_lvx:
9700     case Intrinsic::ppc_altivec_lvxl:
9701     case Intrinsic::ppc_vsx_lxvw4x:
9702       VT = MVT::v4i32;
9703       break;
9704     case Intrinsic::ppc_vsx_lxvd2x:
9705       VT = MVT::v2f64;
9706       break;
9707     case Intrinsic::ppc_altivec_lvebx:
9708       VT = MVT::i8;
9709       break;
9710     case Intrinsic::ppc_altivec_lvehx:
9711       VT = MVT::i16;
9712       break;
9713     case Intrinsic::ppc_altivec_lvewx:
9714       VT = MVT::i32;
9715       break;
9716     }
9717
9718     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9719   }
9720
9721   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9722     EVT VT;
9723     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9724     default: return false;
9725     case Intrinsic::ppc_qpx_qvstfd:
9726     case Intrinsic::ppc_qpx_qvstfda:
9727       VT = MVT::v4f64;
9728       break;
9729     case Intrinsic::ppc_qpx_qvstfs:
9730     case Intrinsic::ppc_qpx_qvstfsa:
9731       VT = MVT::v4f32;
9732       break;
9733     case Intrinsic::ppc_qpx_qvstfcd:
9734     case Intrinsic::ppc_qpx_qvstfcda:
9735       VT = MVT::v2f64;
9736       break;
9737     case Intrinsic::ppc_qpx_qvstfcs:
9738     case Intrinsic::ppc_qpx_qvstfcsa:
9739       VT = MVT::v2f32;
9740       break;
9741     case Intrinsic::ppc_qpx_qvstfiw:
9742     case Intrinsic::ppc_qpx_qvstfiwa:
9743     case Intrinsic::ppc_altivec_stvx:
9744     case Intrinsic::ppc_altivec_stvxl:
9745     case Intrinsic::ppc_vsx_stxvw4x:
9746       VT = MVT::v4i32;
9747       break;
9748     case Intrinsic::ppc_vsx_stxvd2x:
9749       VT = MVT::v2f64;
9750       break;
9751     case Intrinsic::ppc_altivec_stvebx:
9752       VT = MVT::i8;
9753       break;
9754     case Intrinsic::ppc_altivec_stvehx:
9755       VT = MVT::i16;
9756       break;
9757     case Intrinsic::ppc_altivec_stvewx:
9758       VT = MVT::i32;
9759       break;
9760     }
9761
9762     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9763   }
9764
9765   return false;
9766 }
9767
9768 // Return true is there is a nearyby consecutive load to the one provided
9769 // (regardless of alignment). We search up and down the chain, looking though
9770 // token factors and other loads (but nothing else). As a result, a true result
9771 // indicates that it is safe to create a new consecutive load adjacent to the
9772 // load provided.
9773 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9774   SDValue Chain = LD->getChain();
9775   EVT VT = LD->getMemoryVT();
9776
9777   SmallSet<SDNode *, 16> LoadRoots;
9778   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9779   SmallSet<SDNode *, 16> Visited;
9780
9781   // First, search up the chain, branching to follow all token-factor operands.
9782   // If we find a consecutive load, then we're done, otherwise, record all
9783   // nodes just above the top-level loads and token factors.
9784   while (!Queue.empty()) {
9785     SDNode *ChainNext = Queue.pop_back_val();
9786     if (!Visited.insert(ChainNext).second)
9787       continue;
9788
9789     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9790       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9791         return true;
9792
9793       if (!Visited.count(ChainLD->getChain().getNode()))
9794         Queue.push_back(ChainLD->getChain().getNode());
9795     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9796       for (const SDUse &O : ChainNext->ops())
9797         if (!Visited.count(O.getNode()))
9798           Queue.push_back(O.getNode());
9799     } else
9800       LoadRoots.insert(ChainNext);
9801   }
9802
9803   // Second, search down the chain, starting from the top-level nodes recorded
9804   // in the first phase. These top-level nodes are the nodes just above all
9805   // loads and token factors. Starting with their uses, recursively look though
9806   // all loads (just the chain uses) and token factors to find a consecutive
9807   // load.
9808   Visited.clear();
9809   Queue.clear();
9810
9811   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9812        IE = LoadRoots.end(); I != IE; ++I) {
9813     Queue.push_back(*I);
9814
9815     while (!Queue.empty()) {
9816       SDNode *LoadRoot = Queue.pop_back_val();
9817       if (!Visited.insert(LoadRoot).second)
9818         continue;
9819
9820       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9821         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9822           return true;
9823
9824       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9825            UE = LoadRoot->use_end(); UI != UE; ++UI)
9826         if (((isa<MemSDNode>(*UI) &&
9827             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9828             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9829           Queue.push_back(*UI);
9830     }
9831   }
9832
9833   return false;
9834 }
9835
9836 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9837                                                   DAGCombinerInfo &DCI) const {
9838   SelectionDAG &DAG = DCI.DAG;
9839   SDLoc dl(N);
9840
9841   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9842   // If we're tracking CR bits, we need to be careful that we don't have:
9843   //   trunc(binary-ops(zext(x), zext(y)))
9844   // or
9845   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9846   // such that we're unnecessarily moving things into GPRs when it would be
9847   // better to keep them in CR bits.
9848
9849   // Note that trunc here can be an actual i1 trunc, or can be the effective
9850   // truncation that comes from a setcc or select_cc.
9851   if (N->getOpcode() == ISD::TRUNCATE &&
9852       N->getValueType(0) != MVT::i1)
9853     return SDValue();
9854
9855   if (N->getOperand(0).getValueType() != MVT::i32 &&
9856       N->getOperand(0).getValueType() != MVT::i64)
9857     return SDValue();
9858
9859   if (N->getOpcode() == ISD::SETCC ||
9860       N->getOpcode() == ISD::SELECT_CC) {
9861     // If we're looking at a comparison, then we need to make sure that the
9862     // high bits (all except for the first) don't matter the result.
9863     ISD::CondCode CC =
9864       cast<CondCodeSDNode>(N->getOperand(
9865         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9866     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9867
9868     if (ISD::isSignedIntSetCC(CC)) {
9869       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9870           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9871         return SDValue();
9872     } else if (ISD::isUnsignedIntSetCC(CC)) {
9873       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9874                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9875           !DAG.MaskedValueIsZero(N->getOperand(1),
9876                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9877         return SDValue();
9878     } else {
9879       // This is neither a signed nor an unsigned comparison, just make sure
9880       // that the high bits are equal.
9881       APInt Op1Zero, Op1One;
9882       APInt Op2Zero, Op2One;
9883       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9884       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9885
9886       // We don't really care about what is known about the first bit (if
9887       // anything), so clear it in all masks prior to comparing them.
9888       Op1Zero.clearBit(0); Op1One.clearBit(0);
9889       Op2Zero.clearBit(0); Op2One.clearBit(0);
9890
9891       if (Op1Zero != Op2Zero || Op1One != Op2One)
9892         return SDValue();
9893     }
9894   }
9895
9896   // We now know that the higher-order bits are irrelevant, we just need to
9897   // make sure that all of the intermediate operations are bit operations, and
9898   // all inputs are extensions.
9899   if (N->getOperand(0).getOpcode() != ISD::AND &&
9900       N->getOperand(0).getOpcode() != ISD::OR  &&
9901       N->getOperand(0).getOpcode() != ISD::XOR &&
9902       N->getOperand(0).getOpcode() != ISD::SELECT &&
9903       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9904       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9905       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9906       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9907       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9908     return SDValue();
9909
9910   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9911       N->getOperand(1).getOpcode() != ISD::AND &&
9912       N->getOperand(1).getOpcode() != ISD::OR  &&
9913       N->getOperand(1).getOpcode() != ISD::XOR &&
9914       N->getOperand(1).getOpcode() != ISD::SELECT &&
9915       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9916       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9917       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9918       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9919       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9920     return SDValue();
9921
9922   SmallVector<SDValue, 4> Inputs;
9923   SmallVector<SDValue, 8> BinOps, PromOps;
9924   SmallPtrSet<SDNode *, 16> Visited;
9925
9926   for (unsigned i = 0; i < 2; ++i) {
9927     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9928           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9929           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9930           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9931         isa<ConstantSDNode>(N->getOperand(i)))
9932       Inputs.push_back(N->getOperand(i));
9933     else
9934       BinOps.push_back(N->getOperand(i));
9935
9936     if (N->getOpcode() == ISD::TRUNCATE)
9937       break;
9938   }
9939
9940   // Visit all inputs, collect all binary operations (and, or, xor and
9941   // select) that are all fed by extensions.
9942   while (!BinOps.empty()) {
9943     SDValue BinOp = BinOps.back();
9944     BinOps.pop_back();
9945
9946     if (!Visited.insert(BinOp.getNode()).second)
9947       continue;
9948
9949     PromOps.push_back(BinOp);
9950
9951     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9952       // The condition of the select is not promoted.
9953       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9954         continue;
9955       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9956         continue;
9957
9958       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9959             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9960             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9961            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9962           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9963         Inputs.push_back(BinOp.getOperand(i));
9964       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9965                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9966                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9967                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9968                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9969                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9970                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9971                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9972                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9973         BinOps.push_back(BinOp.getOperand(i));
9974       } else {
9975         // We have an input that is not an extension or another binary
9976         // operation; we'll abort this transformation.
9977         return SDValue();
9978       }
9979     }
9980   }
9981
9982   // Make sure that this is a self-contained cluster of operations (which
9983   // is not quite the same thing as saying that everything has only one
9984   // use).
9985   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9986     if (isa<ConstantSDNode>(Inputs[i]))
9987       continue;
9988
9989     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9990                               UE = Inputs[i].getNode()->use_end();
9991          UI != UE; ++UI) {
9992       SDNode *User = *UI;
9993       if (User != N && !Visited.count(User))
9994         return SDValue();
9995
9996       // Make sure that we're not going to promote the non-output-value
9997       // operand(s) or SELECT or SELECT_CC.
9998       // FIXME: Although we could sometimes handle this, and it does occur in
9999       // practice that one of the condition inputs to the select is also one of
10000       // the outputs, we currently can't deal with this.
10001       if (User->getOpcode() == ISD::SELECT) {
10002         if (User->getOperand(0) == Inputs[i])
10003           return SDValue();
10004       } else if (User->getOpcode() == ISD::SELECT_CC) {
10005         if (User->getOperand(0) == Inputs[i] ||
10006             User->getOperand(1) == Inputs[i])
10007           return SDValue();
10008       }
10009     }
10010   }
10011
10012   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10013     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10014                               UE = PromOps[i].getNode()->use_end();
10015          UI != UE; ++UI) {
10016       SDNode *User = *UI;
10017       if (User != N && !Visited.count(User))
10018         return SDValue();
10019
10020       // Make sure that we're not going to promote the non-output-value
10021       // operand(s) or SELECT or SELECT_CC.
10022       // FIXME: Although we could sometimes handle this, and it does occur in
10023       // practice that one of the condition inputs to the select is also one of
10024       // the outputs, we currently can't deal with this.
10025       if (User->getOpcode() == ISD::SELECT) {
10026         if (User->getOperand(0) == PromOps[i])
10027           return SDValue();
10028       } else if (User->getOpcode() == ISD::SELECT_CC) {
10029         if (User->getOperand(0) == PromOps[i] ||
10030             User->getOperand(1) == PromOps[i])
10031           return SDValue();
10032       }
10033     }
10034   }
10035
10036   // Replace all inputs with the extension operand.
10037   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10038     // Constants may have users outside the cluster of to-be-promoted nodes,
10039     // and so we need to replace those as we do the promotions.
10040     if (isa<ConstantSDNode>(Inputs[i]))
10041       continue;
10042     else
10043       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10044   }
10045
10046   std::list<HandleSDNode> PromOpHandles;
10047   for (auto &PromOp : PromOps)
10048     PromOpHandles.emplace_back(PromOp);
10049
10050   // Replace all operations (these are all the same, but have a different
10051   // (i1) return type). DAG.getNode will validate that the types of
10052   // a binary operator match, so go through the list in reverse so that
10053   // we've likely promoted both operands first. Any intermediate truncations or
10054   // extensions disappear.
10055   while (!PromOpHandles.empty()) {
10056     SDValue PromOp = PromOpHandles.back().getValue();
10057     PromOpHandles.pop_back();
10058
10059     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10060         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10061         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10062         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10063       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10064           PromOp.getOperand(0).getValueType() != MVT::i1) {
10065         // The operand is not yet ready (see comment below).
10066         PromOpHandles.emplace_front(PromOp);
10067         continue;
10068       }
10069
10070       SDValue RepValue = PromOp.getOperand(0);
10071       if (isa<ConstantSDNode>(RepValue))
10072         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10073
10074       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10075       continue;
10076     }
10077
10078     unsigned C;
10079     switch (PromOp.getOpcode()) {
10080     default:             C = 0; break;
10081     case ISD::SELECT:    C = 1; break;
10082     case ISD::SELECT_CC: C = 2; break;
10083     }
10084
10085     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10086          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10087         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10088          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10089       // The to-be-promoted operands of this node have not yet been
10090       // promoted (this should be rare because we're going through the
10091       // list backward, but if one of the operands has several users in
10092       // this cluster of to-be-promoted nodes, it is possible).
10093       PromOpHandles.emplace_front(PromOp);
10094       continue;
10095     }
10096
10097     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10098                                 PromOp.getNode()->op_end());
10099
10100     // If there are any constant inputs, make sure they're replaced now.
10101     for (unsigned i = 0; i < 2; ++i)
10102       if (isa<ConstantSDNode>(Ops[C+i]))
10103         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10104
10105     DAG.ReplaceAllUsesOfValueWith(PromOp,
10106       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10107   }
10108
10109   // Now we're left with the initial truncation itself.
10110   if (N->getOpcode() == ISD::TRUNCATE)
10111     return N->getOperand(0);
10112
10113   // Otherwise, this is a comparison. The operands to be compared have just
10114   // changed type (to i1), but everything else is the same.
10115   return SDValue(N, 0);
10116 }
10117
10118 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10119                                                   DAGCombinerInfo &DCI) const {
10120   SelectionDAG &DAG = DCI.DAG;
10121   SDLoc dl(N);
10122
10123   // If we're tracking CR bits, we need to be careful that we don't have:
10124   //   zext(binary-ops(trunc(x), trunc(y)))
10125   // or
10126   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10127   // such that we're unnecessarily moving things into CR bits that can more
10128   // efficiently stay in GPRs. Note that if we're not certain that the high
10129   // bits are set as required by the final extension, we still may need to do
10130   // some masking to get the proper behavior.
10131
10132   // This same functionality is important on PPC64 when dealing with
10133   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10134   // the return values of functions. Because it is so similar, it is handled
10135   // here as well.
10136
10137   if (N->getValueType(0) != MVT::i32 &&
10138       N->getValueType(0) != MVT::i64)
10139     return SDValue();
10140
10141   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10142         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10143     return SDValue();
10144
10145   if (N->getOperand(0).getOpcode() != ISD::AND &&
10146       N->getOperand(0).getOpcode() != ISD::OR  &&
10147       N->getOperand(0).getOpcode() != ISD::XOR &&
10148       N->getOperand(0).getOpcode() != ISD::SELECT &&
10149       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10150     return SDValue();
10151
10152   SmallVector<SDValue, 4> Inputs;
10153   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10154   SmallPtrSet<SDNode *, 16> Visited;
10155
10156   // Visit all inputs, collect all binary operations (and, or, xor and
10157   // select) that are all fed by truncations.
10158   while (!BinOps.empty()) {
10159     SDValue BinOp = BinOps.back();
10160     BinOps.pop_back();
10161
10162     if (!Visited.insert(BinOp.getNode()).second)
10163       continue;
10164
10165     PromOps.push_back(BinOp);
10166
10167     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10168       // The condition of the select is not promoted.
10169       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10170         continue;
10171       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10172         continue;
10173
10174       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10175           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10176         Inputs.push_back(BinOp.getOperand(i));
10177       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10178                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10179                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10180                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10181                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10182         BinOps.push_back(BinOp.getOperand(i));
10183       } else {
10184         // We have an input that is not a truncation or another binary
10185         // operation; we'll abort this transformation.
10186         return SDValue();
10187       }
10188     }
10189   }
10190
10191   // The operands of a select that must be truncated when the select is
10192   // promoted because the operand is actually part of the to-be-promoted set.
10193   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10194
10195   // Make sure that this is a self-contained cluster of operations (which
10196   // is not quite the same thing as saying that everything has only one
10197   // use).
10198   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10199     if (isa<ConstantSDNode>(Inputs[i]))
10200       continue;
10201
10202     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10203                               UE = Inputs[i].getNode()->use_end();
10204          UI != UE; ++UI) {
10205       SDNode *User = *UI;
10206       if (User != N && !Visited.count(User))
10207         return SDValue();
10208
10209       // If we're going to promote the non-output-value operand(s) or SELECT or
10210       // SELECT_CC, record them for truncation.
10211       if (User->getOpcode() == ISD::SELECT) {
10212         if (User->getOperand(0) == Inputs[i])
10213           SelectTruncOp[0].insert(std::make_pair(User,
10214                                     User->getOperand(0).getValueType()));
10215       } else if (User->getOpcode() == ISD::SELECT_CC) {
10216         if (User->getOperand(0) == Inputs[i])
10217           SelectTruncOp[0].insert(std::make_pair(User,
10218                                     User->getOperand(0).getValueType()));
10219         if (User->getOperand(1) == Inputs[i])
10220           SelectTruncOp[1].insert(std::make_pair(User,
10221                                     User->getOperand(1).getValueType()));
10222       }
10223     }
10224   }
10225
10226   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10227     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10228                               UE = PromOps[i].getNode()->use_end();
10229          UI != UE; ++UI) {
10230       SDNode *User = *UI;
10231       if (User != N && !Visited.count(User))
10232         return SDValue();
10233
10234       // If we're going to promote the non-output-value operand(s) or SELECT or
10235       // SELECT_CC, record them for truncation.
10236       if (User->getOpcode() == ISD::SELECT) {
10237         if (User->getOperand(0) == PromOps[i])
10238           SelectTruncOp[0].insert(std::make_pair(User,
10239                                     User->getOperand(0).getValueType()));
10240       } else if (User->getOpcode() == ISD::SELECT_CC) {
10241         if (User->getOperand(0) == PromOps[i])
10242           SelectTruncOp[0].insert(std::make_pair(User,
10243                                     User->getOperand(0).getValueType()));
10244         if (User->getOperand(1) == PromOps[i])
10245           SelectTruncOp[1].insert(std::make_pair(User,
10246                                     User->getOperand(1).getValueType()));
10247       }
10248     }
10249   }
10250
10251   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10252   bool ReallyNeedsExt = false;
10253   if (N->getOpcode() != ISD::ANY_EXTEND) {
10254     // If all of the inputs are not already sign/zero extended, then
10255     // we'll still need to do that at the end.
10256     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10257       if (isa<ConstantSDNode>(Inputs[i]))
10258         continue;
10259
10260       unsigned OpBits =
10261         Inputs[i].getOperand(0).getValueSizeInBits();
10262       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10263
10264       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10265            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10266                                   APInt::getHighBitsSet(OpBits,
10267                                                         OpBits-PromBits))) ||
10268           (N->getOpcode() == ISD::SIGN_EXTEND &&
10269            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10270              (OpBits-(PromBits-1)))) {
10271         ReallyNeedsExt = true;
10272         break;
10273       }
10274     }
10275   }
10276
10277   // Replace all inputs, either with the truncation operand, or a
10278   // truncation or extension to the final output type.
10279   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10280     // Constant inputs need to be replaced with the to-be-promoted nodes that
10281     // use them because they might have users outside of the cluster of
10282     // promoted nodes.
10283     if (isa<ConstantSDNode>(Inputs[i]))
10284       continue;
10285
10286     SDValue InSrc = Inputs[i].getOperand(0);
10287     if (Inputs[i].getValueType() == N->getValueType(0))
10288       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10289     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10290       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10291         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10292     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10293       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10294         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10295     else
10296       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10297         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10298   }
10299
10300   std::list<HandleSDNode> PromOpHandles;
10301   for (auto &PromOp : PromOps)
10302     PromOpHandles.emplace_back(PromOp);
10303
10304   // Replace all operations (these are all the same, but have a different
10305   // (promoted) return type). DAG.getNode will validate that the types of
10306   // a binary operator match, so go through the list in reverse so that
10307   // we've likely promoted both operands first.
10308   while (!PromOpHandles.empty()) {
10309     SDValue PromOp = PromOpHandles.back().getValue();
10310     PromOpHandles.pop_back();
10311
10312     unsigned C;
10313     switch (PromOp.getOpcode()) {
10314     default:             C = 0; break;
10315     case ISD::SELECT:    C = 1; break;
10316     case ISD::SELECT_CC: C = 2; break;
10317     }
10318
10319     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10320          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10321         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10322          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10323       // The to-be-promoted operands of this node have not yet been
10324       // promoted (this should be rare because we're going through the
10325       // list backward, but if one of the operands has several users in
10326       // this cluster of to-be-promoted nodes, it is possible).
10327       PromOpHandles.emplace_front(PromOp);
10328       continue;
10329     }
10330
10331     // For SELECT and SELECT_CC nodes, we do a similar check for any
10332     // to-be-promoted comparison inputs.
10333     if (PromOp.getOpcode() == ISD::SELECT ||
10334         PromOp.getOpcode() == ISD::SELECT_CC) {
10335       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10336            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10337           (SelectTruncOp[1].count(PromOp.getNode()) &&
10338            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10339         PromOpHandles.emplace_front(PromOp);
10340         continue;
10341       }
10342     }
10343
10344     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10345                                 PromOp.getNode()->op_end());
10346
10347     // If this node has constant inputs, then they'll need to be promoted here.
10348     for (unsigned i = 0; i < 2; ++i) {
10349       if (!isa<ConstantSDNode>(Ops[C+i]))
10350         continue;
10351       if (Ops[C+i].getValueType() == N->getValueType(0))
10352         continue;
10353
10354       if (N->getOpcode() == ISD::SIGN_EXTEND)
10355         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10356       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10357         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10358       else
10359         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10360     }
10361
10362     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10363     // truncate them again to the original value type.
10364     if (PromOp.getOpcode() == ISD::SELECT ||
10365         PromOp.getOpcode() == ISD::SELECT_CC) {
10366       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10367       if (SI0 != SelectTruncOp[0].end())
10368         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10369       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10370       if (SI1 != SelectTruncOp[1].end())
10371         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10372     }
10373
10374     DAG.ReplaceAllUsesOfValueWith(PromOp,
10375       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10376   }
10377
10378   // Now we're left with the initial extension itself.
10379   if (!ReallyNeedsExt)
10380     return N->getOperand(0);
10381
10382   // To zero extend, just mask off everything except for the first bit (in the
10383   // i1 case).
10384   if (N->getOpcode() == ISD::ZERO_EXTEND)
10385     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10386                        DAG.getConstant(APInt::getLowBitsSet(
10387                                          N->getValueSizeInBits(0), PromBits),
10388                                        dl, N->getValueType(0)));
10389
10390   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10391          "Invalid extension type");
10392   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10393   SDValue ShiftCst =
10394       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10395   return DAG.getNode(
10396       ISD::SRA, dl, N->getValueType(0),
10397       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10398       ShiftCst);
10399 }
10400
10401 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10402                                                  DAGCombinerInfo &DCI) const {
10403   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10404          "Should be called with a BUILD_VECTOR node");
10405
10406   SelectionDAG &DAG = DCI.DAG;
10407   SDLoc dl(N);
10408   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10409     return SDValue();
10410
10411   // Looking for:
10412   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10413   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10414       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10415     return SDValue();
10416   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10417       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10418     return SDValue();
10419   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10420     return SDValue();
10421
10422   SDValue Ext1 = N->getOperand(0).getOperand(0);
10423   SDValue Ext2 = N->getOperand(1).getOperand(0);
10424   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10425      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10426     return SDValue();
10427
10428   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10429   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10430   if (!Ext1Op || !Ext2Op)
10431     return SDValue();
10432   if (Ext1.getValueType() != MVT::i32 ||
10433       Ext2.getValueType() != MVT::i32)
10434   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10435     return SDValue();
10436
10437   int FirstElem = Ext1Op->getZExtValue();
10438   int SecondElem = Ext2Op->getZExtValue();
10439   int SubvecIdx;
10440   if (FirstElem == 0 && SecondElem == 1)
10441     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10442   else if (FirstElem == 2 && SecondElem == 3)
10443     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10444   else
10445     return SDValue();
10446
10447   SDValue SrcVec = Ext1.getOperand(0);
10448   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10449     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10450   return DAG.getNode(NodeType, dl, MVT::v2f64,
10451                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10452 }
10453
10454 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10455                                               DAGCombinerInfo &DCI) const {
10456   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10457           N->getOpcode() == ISD::UINT_TO_FP) &&
10458          "Need an int -> FP conversion node here");
10459
10460   if (useSoftFloat() || !Subtarget.has64BitSupport())
10461     return SDValue();
10462
10463   SelectionDAG &DAG = DCI.DAG;
10464   SDLoc dl(N);
10465   SDValue Op(N, 0);
10466
10467   // Don't handle ppc_fp128 here or i1 conversions.
10468   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10469     return SDValue();
10470   if (Op.getOperand(0).getValueType() == MVT::i1)
10471     return SDValue();
10472
10473   // For i32 intermediate values, unfortunately, the conversion functions
10474   // leave the upper 32 bits of the value are undefined. Within the set of
10475   // scalar instructions, we have no method for zero- or sign-extending the
10476   // value. Thus, we cannot handle i32 intermediate values here.
10477   if (Op.getOperand(0).getValueType() == MVT::i32)
10478     return SDValue();
10479
10480   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10481          "UINT_TO_FP is supported only with FPCVT");
10482
10483   // If we have FCFIDS, then use it when converting to single-precision.
10484   // Otherwise, convert to double-precision and then round.
10485   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10486                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10487                                                             : PPCISD::FCFIDS)
10488                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10489                                                             : PPCISD::FCFID);
10490   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10491                   ? MVT::f32
10492                   : MVT::f64;
10493
10494   // If we're converting from a float, to an int, and back to a float again,
10495   // then we don't need the store/load pair at all.
10496   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10497        Subtarget.hasFPCVT()) ||
10498       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10499     SDValue Src = Op.getOperand(0).getOperand(0);
10500     if (Src.getValueType() == MVT::f32) {
10501       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10502       DCI.AddToWorklist(Src.getNode());
10503     } else if (Src.getValueType() != MVT::f64) {
10504       // Make sure that we don't pick up a ppc_fp128 source value.
10505       return SDValue();
10506     }
10507
10508     unsigned FCTOp =
10509       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10510                                                         PPCISD::FCTIDUZ;
10511
10512     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10513     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10514
10515     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10516       FP = DAG.getNode(ISD::FP_ROUND, dl,
10517                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10518       DCI.AddToWorklist(FP.getNode());
10519     }
10520
10521     return FP;
10522   }
10523
10524   return SDValue();
10525 }
10526
10527 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10528 // builtins) into loads with swaps.
10529 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10530                                               DAGCombinerInfo &DCI) const {
10531   SelectionDAG &DAG = DCI.DAG;
10532   SDLoc dl(N);
10533   SDValue Chain;
10534   SDValue Base;
10535   MachineMemOperand *MMO;
10536
10537   switch (N->getOpcode()) {
10538   default:
10539     llvm_unreachable("Unexpected opcode for little endian VSX load");
10540   case ISD::LOAD: {
10541     LoadSDNode *LD = cast<LoadSDNode>(N);
10542     Chain = LD->getChain();
10543     Base = LD->getBasePtr();
10544     MMO = LD->getMemOperand();
10545     // If the MMO suggests this isn't a load of a full vector, leave
10546     // things alone.  For a built-in, we have to make the change for
10547     // correctness, so if there is a size problem that will be a bug.
10548     if (MMO->getSize() < 16)
10549       return SDValue();
10550     break;
10551   }
10552   case ISD::INTRINSIC_W_CHAIN: {
10553     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10554     Chain = Intrin->getChain();
10555     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10556     // us what we want. Get operand 2 instead.
10557     Base = Intrin->getOperand(2);
10558     MMO = Intrin->getMemOperand();
10559     break;
10560   }
10561   }
10562
10563   MVT VecTy = N->getValueType(0).getSimpleVT();
10564   SDValue LoadOps[] = { Chain, Base };
10565   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10566                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10567                                          LoadOps, MVT::v2f64, MMO);
10568
10569   DCI.AddToWorklist(Load.getNode());
10570   Chain = Load.getValue(1);
10571   SDValue Swap = DAG.getNode(
10572       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10573   DCI.AddToWorklist(Swap.getNode());
10574
10575   // Add a bitcast if the resulting load type doesn't match v2f64.
10576   if (VecTy != MVT::v2f64) {
10577     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10578     DCI.AddToWorklist(N.getNode());
10579     // Package {bitcast value, swap's chain} to match Load's shape.
10580     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10581                        N, Swap.getValue(1));
10582   }
10583
10584   return Swap;
10585 }
10586
10587 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10588 // builtins) into stores with swaps.
10589 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10590                                                DAGCombinerInfo &DCI) const {
10591   SelectionDAG &DAG = DCI.DAG;
10592   SDLoc dl(N);
10593   SDValue Chain;
10594   SDValue Base;
10595   unsigned SrcOpnd;
10596   MachineMemOperand *MMO;
10597
10598   switch (N->getOpcode()) {
10599   default:
10600     llvm_unreachable("Unexpected opcode for little endian VSX store");
10601   case ISD::STORE: {
10602     StoreSDNode *ST = cast<StoreSDNode>(N);
10603     Chain = ST->getChain();
10604     Base = ST->getBasePtr();
10605     MMO = ST->getMemOperand();
10606     SrcOpnd = 1;
10607     // If the MMO suggests this isn't a store of a full vector, leave
10608     // things alone.  For a built-in, we have to make the change for
10609     // correctness, so if there is a size problem that will be a bug.
10610     if (MMO->getSize() < 16)
10611       return SDValue();
10612     break;
10613   }
10614   case ISD::INTRINSIC_VOID: {
10615     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10616     Chain = Intrin->getChain();
10617     // Intrin->getBasePtr() oddly does not get what we want.
10618     Base = Intrin->getOperand(3);
10619     MMO = Intrin->getMemOperand();
10620     SrcOpnd = 2;
10621     break;
10622   }
10623   }
10624
10625   SDValue Src = N->getOperand(SrcOpnd);
10626   MVT VecTy = Src.getValueType().getSimpleVT();
10627
10628   // All stores are done as v2f64 and possible bit cast.
10629   if (VecTy != MVT::v2f64) {
10630     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10631     DCI.AddToWorklist(Src.getNode());
10632   }
10633
10634   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10635                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10636   DCI.AddToWorklist(Swap.getNode());
10637   Chain = Swap.getValue(1);
10638   SDValue StoreOps[] = { Chain, Swap, Base };
10639   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10640                                           DAG.getVTList(MVT::Other),
10641                                           StoreOps, VecTy, MMO);
10642   DCI.AddToWorklist(Store.getNode());
10643   return Store;
10644 }
10645
10646 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10647                                              DAGCombinerInfo &DCI) const {
10648   SelectionDAG &DAG = DCI.DAG;
10649   SDLoc dl(N);
10650   switch (N->getOpcode()) {
10651   default: break;
10652   case PPCISD::SHL:
10653     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10654         return N->getOperand(0);
10655     break;
10656   case PPCISD::SRL:
10657     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10658         return N->getOperand(0);
10659     break;
10660   case PPCISD::SRA:
10661     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10662       if (C->isNullValue() ||   //  0 >>s V -> 0.
10663           C->isAllOnesValue())    // -1 >>s V -> -1.
10664         return N->getOperand(0);
10665     }
10666     break;
10667   case ISD::SIGN_EXTEND:
10668   case ISD::ZERO_EXTEND:
10669   case ISD::ANY_EXTEND:
10670     return DAGCombineExtBoolTrunc(N, DCI);
10671   case ISD::TRUNCATE:
10672   case ISD::SETCC:
10673   case ISD::SELECT_CC:
10674     return DAGCombineTruncBoolExt(N, DCI);
10675   case ISD::SINT_TO_FP:
10676   case ISD::UINT_TO_FP:
10677     return combineFPToIntToFP(N, DCI);
10678   case ISD::STORE: {
10679     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10680     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10681         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10682         N->getOperand(1).getValueType() == MVT::i32 &&
10683         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10684       SDValue Val = N->getOperand(1).getOperand(0);
10685       if (Val.getValueType() == MVT::f32) {
10686         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10687         DCI.AddToWorklist(Val.getNode());
10688       }
10689       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10690       DCI.AddToWorklist(Val.getNode());
10691
10692       SDValue Ops[] = {
10693         N->getOperand(0), Val, N->getOperand(2),
10694         DAG.getValueType(N->getOperand(1).getValueType())
10695       };
10696
10697       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10698               DAG.getVTList(MVT::Other), Ops,
10699               cast<StoreSDNode>(N)->getMemoryVT(),
10700               cast<StoreSDNode>(N)->getMemOperand());
10701       DCI.AddToWorklist(Val.getNode());
10702       return Val;
10703     }
10704
10705     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10706     if (cast<StoreSDNode>(N)->isUnindexed() &&
10707         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10708         N->getOperand(1).getNode()->hasOneUse() &&
10709         (N->getOperand(1).getValueType() == MVT::i32 ||
10710          N->getOperand(1).getValueType() == MVT::i16 ||
10711          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10712           N->getOperand(1).getValueType() == MVT::i64))) {
10713       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10714       // Do an any-extend to 32-bits if this is a half-word input.
10715       if (BSwapOp.getValueType() == MVT::i16)
10716         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10717
10718       SDValue Ops[] = {
10719         N->getOperand(0), BSwapOp, N->getOperand(2),
10720         DAG.getValueType(N->getOperand(1).getValueType())
10721       };
10722       return
10723         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10724                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10725                                 cast<StoreSDNode>(N)->getMemOperand());
10726     }
10727
10728     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10729     EVT VT = N->getOperand(1).getValueType();
10730     if (VT.isSimple()) {
10731       MVT StoreVT = VT.getSimpleVT();
10732       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10733           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10734            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10735         return expandVSXStoreForLE(N, DCI);
10736     }
10737     break;
10738   }
10739   case ISD::LOAD: {
10740     LoadSDNode *LD = cast<LoadSDNode>(N);
10741     EVT VT = LD->getValueType(0);
10742
10743     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10744     if (VT.isSimple()) {
10745       MVT LoadVT = VT.getSimpleVT();
10746       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10747           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10748            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10749         return expandVSXLoadForLE(N, DCI);
10750     }
10751
10752     // We sometimes end up with a 64-bit integer load, from which we extract
10753     // two single-precision floating-point numbers. This happens with
10754     // std::complex<float>, and other similar structures, because of the way we
10755     // canonicalize structure copies. However, if we lack direct moves,
10756     // then the final bitcasts from the extracted integer values to the
10757     // floating-point numbers turn into store/load pairs. Even with direct moves,
10758     // just loading the two floating-point numbers is likely better.
10759     auto ReplaceTwoFloatLoad = [&]() {
10760       if (VT != MVT::i64)
10761         return false;
10762
10763       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10764           LD->isVolatile())
10765         return false;
10766
10767       //  We're looking for a sequence like this:
10768       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10769       //      t16: i64 = srl t13, Constant:i32<32>
10770       //    t17: i32 = truncate t16
10771       //  t18: f32 = bitcast t17
10772       //    t19: i32 = truncate t13
10773       //  t20: f32 = bitcast t19
10774
10775       if (!LD->hasNUsesOfValue(2, 0))
10776         return false;
10777
10778       auto UI = LD->use_begin();
10779       while (UI.getUse().getResNo() != 0) ++UI;
10780       SDNode *Trunc = *UI++;
10781       while (UI.getUse().getResNo() != 0) ++UI;
10782       SDNode *RightShift = *UI;
10783       if (Trunc->getOpcode() != ISD::TRUNCATE)
10784         std::swap(Trunc, RightShift);
10785
10786       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10787           Trunc->getValueType(0) != MVT::i32 ||
10788           !Trunc->hasOneUse())
10789         return false;
10790       if (RightShift->getOpcode() != ISD::SRL ||
10791           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10792           RightShift->getConstantOperandVal(1) != 32 ||
10793           !RightShift->hasOneUse())
10794         return false;
10795
10796       SDNode *Trunc2 = *RightShift->use_begin();
10797       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10798           Trunc2->getValueType(0) != MVT::i32 ||
10799           !Trunc2->hasOneUse())
10800         return false;
10801
10802       SDNode *Bitcast = *Trunc->use_begin();
10803       SDNode *Bitcast2 = *Trunc2->use_begin();
10804
10805       if (Bitcast->getOpcode() != ISD::BITCAST ||
10806           Bitcast->getValueType(0) != MVT::f32)
10807         return false;
10808       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10809           Bitcast2->getValueType(0) != MVT::f32)
10810         return false;
10811
10812       if (Subtarget.isLittleEndian())
10813         std::swap(Bitcast, Bitcast2);
10814
10815       // Bitcast has the second float (in memory-layout order) and Bitcast2
10816       // has the first one.
10817
10818       SDValue BasePtr = LD->getBasePtr();
10819       if (LD->isIndexed()) {
10820         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10821                "Non-pre-inc AM on PPC?");
10822         BasePtr =
10823           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10824                       LD->getOffset());
10825       }
10826
10827       auto MMOFlags =
10828           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
10829       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10830                                       LD->getPointerInfo(), LD->getAlignment(),
10831                                       MMOFlags, LD->getAAInfo());
10832       SDValue AddPtr =
10833         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10834                     BasePtr, DAG.getIntPtrConstant(4, dl));
10835       SDValue FloatLoad2 = DAG.getLoad(
10836           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10837           LD->getPointerInfo().getWithOffset(4),
10838           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
10839
10840       if (LD->isIndexed()) {
10841         // Note that DAGCombine should re-form any pre-increment load(s) from
10842         // what is produced here if that makes sense.
10843         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10844       }
10845
10846       DCI.CombineTo(Bitcast2, FloatLoad);
10847       DCI.CombineTo(Bitcast, FloatLoad2);
10848
10849       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10850                                     SDValue(FloatLoad2.getNode(), 1));
10851       return true;
10852     };
10853
10854     if (ReplaceTwoFloatLoad())
10855       return SDValue(N, 0);
10856
10857     EVT MemVT = LD->getMemoryVT();
10858     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10859     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10860     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10861     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10862     if (LD->isUnindexed() && VT.isVector() &&
10863         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10864           // P8 and later hardware should just use LOAD.
10865           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10866                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10867          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10868           LD->getAlignment() >= ScalarABIAlignment)) &&
10869         LD->getAlignment() < ABIAlignment) {
10870       // This is a type-legal unaligned Altivec or QPX load.
10871       SDValue Chain = LD->getChain();
10872       SDValue Ptr = LD->getBasePtr();
10873       bool isLittleEndian = Subtarget.isLittleEndian();
10874
10875       // This implements the loading of unaligned vectors as described in
10876       // the venerable Apple Velocity Engine overview. Specifically:
10877       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10878       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10879       //
10880       // The general idea is to expand a sequence of one or more unaligned
10881       // loads into an alignment-based permutation-control instruction (lvsl
10882       // or lvsr), a series of regular vector loads (which always truncate
10883       // their input address to an aligned address), and a series of
10884       // permutations.  The results of these permutations are the requested
10885       // loaded values.  The trick is that the last "extra" load is not taken
10886       // from the address you might suspect (sizeof(vector) bytes after the
10887       // last requested load), but rather sizeof(vector) - 1 bytes after the
10888       // last requested vector. The point of this is to avoid a page fault if
10889       // the base address happened to be aligned. This works because if the
10890       // base address is aligned, then adding less than a full vector length
10891       // will cause the last vector in the sequence to be (re)loaded.
10892       // Otherwise, the next vector will be fetched as you might suspect was
10893       // necessary.
10894
10895       // We might be able to reuse the permutation generation from
10896       // a different base address offset from this one by an aligned amount.
10897       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10898       // optimization later.
10899       Intrinsic::ID Intr, IntrLD, IntrPerm;
10900       MVT PermCntlTy, PermTy, LDTy;
10901       if (Subtarget.hasAltivec()) {
10902         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10903                                  Intrinsic::ppc_altivec_lvsl;
10904         IntrLD = Intrinsic::ppc_altivec_lvx;
10905         IntrPerm = Intrinsic::ppc_altivec_vperm;
10906         PermCntlTy = MVT::v16i8;
10907         PermTy = MVT::v4i32;
10908         LDTy = MVT::v4i32;
10909       } else {
10910         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10911                                        Intrinsic::ppc_qpx_qvlpcls;
10912         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10913                                        Intrinsic::ppc_qpx_qvlfs;
10914         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10915         PermCntlTy = MVT::v4f64;
10916         PermTy = MVT::v4f64;
10917         LDTy = MemVT.getSimpleVT();
10918       }
10919
10920       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10921
10922       // Create the new MMO for the new base load. It is like the original MMO,
10923       // but represents an area in memory almost twice the vector size centered
10924       // on the original address. If the address is unaligned, we might start
10925       // reading up to (sizeof(vector)-1) bytes below the address of the
10926       // original unaligned load.
10927       MachineFunction &MF = DAG.getMachineFunction();
10928       MachineMemOperand *BaseMMO =
10929         MF.getMachineMemOperand(LD->getMemOperand(),
10930                                 -(long)MemVT.getStoreSize()+1,
10931                                 2*MemVT.getStoreSize()-1);
10932
10933       // Create the new base load.
10934       SDValue LDXIntID =
10935           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10936       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10937       SDValue BaseLoad =
10938         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10939                                 DAG.getVTList(PermTy, MVT::Other),
10940                                 BaseLoadOps, LDTy, BaseMMO);
10941
10942       // Note that the value of IncOffset (which is provided to the next
10943       // load's pointer info offset value, and thus used to calculate the
10944       // alignment), and the value of IncValue (which is actually used to
10945       // increment the pointer value) are different! This is because we
10946       // require the next load to appear to be aligned, even though it
10947       // is actually offset from the base pointer by a lesser amount.
10948       int IncOffset = VT.getSizeInBits() / 8;
10949       int IncValue = IncOffset;
10950
10951       // Walk (both up and down) the chain looking for another load at the real
10952       // (aligned) offset (the alignment of the other load does not matter in
10953       // this case). If found, then do not use the offset reduction trick, as
10954       // that will prevent the loads from being later combined (as they would
10955       // otherwise be duplicates).
10956       if (!findConsecutiveLoad(LD, DAG))
10957         --IncValue;
10958
10959       SDValue Increment =
10960           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10961       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10962
10963       MachineMemOperand *ExtraMMO =
10964         MF.getMachineMemOperand(LD->getMemOperand(),
10965                                 1, 2*MemVT.getStoreSize()-1);
10966       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10967       SDValue ExtraLoad =
10968         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10969                                 DAG.getVTList(PermTy, MVT::Other),
10970                                 ExtraLoadOps, LDTy, ExtraMMO);
10971
10972       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10973         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10974
10975       // Because vperm has a big-endian bias, we must reverse the order
10976       // of the input vectors and complement the permute control vector
10977       // when generating little endian code.  We have already handled the
10978       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10979       // and ExtraLoad here.
10980       SDValue Perm;
10981       if (isLittleEndian)
10982         Perm = BuildIntrinsicOp(IntrPerm,
10983                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10984       else
10985         Perm = BuildIntrinsicOp(IntrPerm,
10986                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10987
10988       if (VT != PermTy)
10989         Perm = Subtarget.hasAltivec() ?
10990                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10991                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10992                                DAG.getTargetConstant(1, dl, MVT::i64));
10993                                // second argument is 1 because this rounding
10994                                // is always exact.
10995
10996       // The output of the permutation is our loaded result, the TokenFactor is
10997       // our new chain.
10998       DCI.CombineTo(N, Perm, TF);
10999       return SDValue(N, 0);
11000     }
11001     }
11002     break;
11003     case ISD::INTRINSIC_WO_CHAIN: {
11004       bool isLittleEndian = Subtarget.isLittleEndian();
11005       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11006       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11007                                            : Intrinsic::ppc_altivec_lvsl);
11008       if ((IID == Intr ||
11009            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11010            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11011         N->getOperand(1)->getOpcode() == ISD::ADD) {
11012         SDValue Add = N->getOperand(1);
11013
11014         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11015                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11016
11017         if (DAG.MaskedValueIsZero(
11018                 Add->getOperand(1),
11019                 APInt::getAllOnesValue(Bits /* alignment */)
11020                     .zext(
11021                         Add.getValueType().getScalarType().getSizeInBits()))) {
11022           SDNode *BasePtr = Add->getOperand(0).getNode();
11023           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11024                                     UE = BasePtr->use_end();
11025                UI != UE; ++UI) {
11026             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11027                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11028               // We've found another LVSL/LVSR, and this address is an aligned
11029               // multiple of that one. The results will be the same, so use the
11030               // one we've just found instead.
11031
11032               return SDValue(*UI, 0);
11033             }
11034           }
11035         }
11036
11037         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11038           SDNode *BasePtr = Add->getOperand(0).getNode();
11039           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11040                UE = BasePtr->use_end(); UI != UE; ++UI) {
11041             if (UI->getOpcode() == ISD::ADD &&
11042                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11043                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11044                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11045                 (1ULL << Bits) == 0) {
11046               SDNode *OtherAdd = *UI;
11047               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11048                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11049                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11050                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11051                   return SDValue(*VI, 0);
11052                 }
11053               }
11054             }
11055           }
11056         }
11057       }
11058     }
11059
11060     break;
11061   case ISD::INTRINSIC_W_CHAIN: {
11062     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11063     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
11064       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11065       default:
11066         break;
11067       case Intrinsic::ppc_vsx_lxvw4x:
11068       case Intrinsic::ppc_vsx_lxvd2x:
11069         return expandVSXLoadForLE(N, DCI);
11070       }
11071     }
11072     break;
11073   }
11074   case ISD::INTRINSIC_VOID: {
11075     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11076     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
11077       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11078       default:
11079         break;
11080       case Intrinsic::ppc_vsx_stxvw4x:
11081       case Intrinsic::ppc_vsx_stxvd2x:
11082         return expandVSXStoreForLE(N, DCI);
11083       }
11084     }
11085     break;
11086   }
11087   case ISD::BSWAP:
11088     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11089     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11090         N->getOperand(0).hasOneUse() &&
11091         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11092          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11093           N->getValueType(0) == MVT::i64))) {
11094       SDValue Load = N->getOperand(0);
11095       LoadSDNode *LD = cast<LoadSDNode>(Load);
11096       // Create the byte-swapping load.
11097       SDValue Ops[] = {
11098         LD->getChain(),    // Chain
11099         LD->getBasePtr(),  // Ptr
11100         DAG.getValueType(N->getValueType(0)) // VT
11101       };
11102       SDValue BSLoad =
11103         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11104                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11105                                               MVT::i64 : MVT::i32, MVT::Other),
11106                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11107
11108       // If this is an i16 load, insert the truncate.
11109       SDValue ResVal = BSLoad;
11110       if (N->getValueType(0) == MVT::i16)
11111         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11112
11113       // First, combine the bswap away.  This makes the value produced by the
11114       // load dead.
11115       DCI.CombineTo(N, ResVal);
11116
11117       // Next, combine the load away, we give it a bogus result value but a real
11118       // chain result.  The result value is dead because the bswap is dead.
11119       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11120
11121       // Return N so it doesn't get rechecked!
11122       return SDValue(N, 0);
11123     }
11124
11125     break;
11126   case PPCISD::VCMP: {
11127     // If a VCMPo node already exists with exactly the same operands as this
11128     // node, use its result instead of this node (VCMPo computes both a CR6 and
11129     // a normal output).
11130     //
11131     if (!N->getOperand(0).hasOneUse() &&
11132         !N->getOperand(1).hasOneUse() &&
11133         !N->getOperand(2).hasOneUse()) {
11134
11135       // Scan all of the users of the LHS, looking for VCMPo's that match.
11136       SDNode *VCMPoNode = nullptr;
11137
11138       SDNode *LHSN = N->getOperand(0).getNode();
11139       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11140            UI != E; ++UI)
11141         if (UI->getOpcode() == PPCISD::VCMPo &&
11142             UI->getOperand(1) == N->getOperand(1) &&
11143             UI->getOperand(2) == N->getOperand(2) &&
11144             UI->getOperand(0) == N->getOperand(0)) {
11145           VCMPoNode = *UI;
11146           break;
11147         }
11148
11149       // If there is no VCMPo node, or if the flag value has a single use, don't
11150       // transform this.
11151       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11152         break;
11153
11154       // Look at the (necessarily single) use of the flag value.  If it has a
11155       // chain, this transformation is more complex.  Note that multiple things
11156       // could use the value result, which we should ignore.
11157       SDNode *FlagUser = nullptr;
11158       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11159            FlagUser == nullptr; ++UI) {
11160         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11161         SDNode *User = *UI;
11162         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11163           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11164             FlagUser = User;
11165             break;
11166           }
11167         }
11168       }
11169
11170       // If the user is a MFOCRF instruction, we know this is safe.
11171       // Otherwise we give up for right now.
11172       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11173         return SDValue(VCMPoNode, 0);
11174     }
11175     break;
11176   }
11177   case ISD::BRCOND: {
11178     SDValue Cond = N->getOperand(1);
11179     SDValue Target = N->getOperand(2);
11180
11181     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11182         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11183           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11184
11185       // We now need to make the intrinsic dead (it cannot be instruction
11186       // selected).
11187       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11188       assert(Cond.getNode()->hasOneUse() &&
11189              "Counter decrement has more than one use");
11190
11191       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11192                          N->getOperand(0), Target);
11193     }
11194   }
11195   break;
11196   case ISD::BR_CC: {
11197     // If this is a branch on an altivec predicate comparison, lower this so
11198     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11199     // lowering is done pre-legalize, because the legalizer lowers the predicate
11200     // compare down to code that is difficult to reassemble.
11201     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11202     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11203
11204     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11205     // value. If so, pass-through the AND to get to the intrinsic.
11206     if (LHS.getOpcode() == ISD::AND &&
11207         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11208         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11209           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11210         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11211         !isNullConstant(LHS.getOperand(1)))
11212       LHS = LHS.getOperand(0);
11213
11214     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11215         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11216           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11217         isa<ConstantSDNode>(RHS)) {
11218       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11219              "Counter decrement comparison is not EQ or NE");
11220
11221       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11222       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11223                     (CC == ISD::SETNE && !Val);
11224
11225       // We now need to make the intrinsic dead (it cannot be instruction
11226       // selected).
11227       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11228       assert(LHS.getNode()->hasOneUse() &&
11229              "Counter decrement has more than one use");
11230
11231       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11232                          N->getOperand(0), N->getOperand(4));
11233     }
11234
11235     int CompareOpc;
11236     bool isDot;
11237
11238     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11239         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11240         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11241       assert(isDot && "Can't compare against a vector result!");
11242
11243       // If this is a comparison against something other than 0/1, then we know
11244       // that the condition is never/always true.
11245       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11246       if (Val != 0 && Val != 1) {
11247         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11248           return N->getOperand(0);
11249         // Always !=, turn it into an unconditional branch.
11250         return DAG.getNode(ISD::BR, dl, MVT::Other,
11251                            N->getOperand(0), N->getOperand(4));
11252       }
11253
11254       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11255
11256       // Create the PPCISD altivec 'dot' comparison node.
11257       SDValue Ops[] = {
11258         LHS.getOperand(2),  // LHS of compare
11259         LHS.getOperand(3),  // RHS of compare
11260         DAG.getConstant(CompareOpc, dl, MVT::i32)
11261       };
11262       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11263       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11264
11265       // Unpack the result based on how the target uses it.
11266       PPC::Predicate CompOpc;
11267       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11268       default:  // Can't happen, don't crash on invalid number though.
11269       case 0:   // Branch on the value of the EQ bit of CR6.
11270         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11271         break;
11272       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11273         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11274         break;
11275       case 2:   // Branch on the value of the LT bit of CR6.
11276         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11277         break;
11278       case 3:   // Branch on the inverted value of the LT bit of CR6.
11279         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11280         break;
11281       }
11282
11283       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11284                          DAG.getConstant(CompOpc, dl, MVT::i32),
11285                          DAG.getRegister(PPC::CR6, MVT::i32),
11286                          N->getOperand(4), CompNode.getValue(1));
11287     }
11288     break;
11289   }
11290   case ISD::BUILD_VECTOR:
11291     return DAGCombineBuildVector(N, DCI);
11292   }
11293
11294   return SDValue();
11295 }
11296
11297 SDValue
11298 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11299                                   SelectionDAG &DAG,
11300                                   std::vector<SDNode *> *Created) const {
11301   // fold (sdiv X, pow2)
11302   EVT VT = N->getValueType(0);
11303   if (VT == MVT::i64 && !Subtarget.isPPC64())
11304     return SDValue();
11305   if ((VT != MVT::i32 && VT != MVT::i64) ||
11306       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11307     return SDValue();
11308
11309   SDLoc DL(N);
11310   SDValue N0 = N->getOperand(0);
11311
11312   bool IsNegPow2 = (-Divisor).isPowerOf2();
11313   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11314   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11315
11316   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11317   if (Created)
11318     Created->push_back(Op.getNode());
11319
11320   if (IsNegPow2) {
11321     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11322     if (Created)
11323       Created->push_back(Op.getNode());
11324   }
11325
11326   return Op;
11327 }
11328
11329 //===----------------------------------------------------------------------===//
11330 // Inline Assembly Support
11331 //===----------------------------------------------------------------------===//
11332
11333 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11334                                                       APInt &KnownZero,
11335                                                       APInt &KnownOne,
11336                                                       const SelectionDAG &DAG,
11337                                                       unsigned Depth) const {
11338   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11339   switch (Op.getOpcode()) {
11340   default: break;
11341   case PPCISD::LBRX: {
11342     // lhbrx is known to have the top bits cleared out.
11343     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11344       KnownZero = 0xFFFF0000;
11345     break;
11346   }
11347   case ISD::INTRINSIC_WO_CHAIN: {
11348     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11349     default: break;
11350     case Intrinsic::ppc_altivec_vcmpbfp_p:
11351     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11352     case Intrinsic::ppc_altivec_vcmpequb_p:
11353     case Intrinsic::ppc_altivec_vcmpequh_p:
11354     case Intrinsic::ppc_altivec_vcmpequw_p:
11355     case Intrinsic::ppc_altivec_vcmpequd_p:
11356     case Intrinsic::ppc_altivec_vcmpgefp_p:
11357     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11358     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11359     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11360     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11361     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11362     case Intrinsic::ppc_altivec_vcmpgtub_p:
11363     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11364     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11365     case Intrinsic::ppc_altivec_vcmpgtud_p:
11366       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11367       break;
11368     }
11369   }
11370   }
11371 }
11372
11373 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11374   switch (Subtarget.getDarwinDirective()) {
11375   default: break;
11376   case PPC::DIR_970:
11377   case PPC::DIR_PWR4:
11378   case PPC::DIR_PWR5:
11379   case PPC::DIR_PWR5X:
11380   case PPC::DIR_PWR6:
11381   case PPC::DIR_PWR6X:
11382   case PPC::DIR_PWR7:
11383   case PPC::DIR_PWR8:
11384   case PPC::DIR_PWR9: {
11385     if (!ML)
11386       break;
11387
11388     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11389
11390     // For small loops (between 5 and 8 instructions), align to a 32-byte
11391     // boundary so that the entire loop fits in one instruction-cache line.
11392     uint64_t LoopSize = 0;
11393     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11394       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11395         LoopSize += TII->GetInstSizeInBytes(*J);
11396         if (LoopSize > 32)
11397           break;
11398       }
11399
11400     if (LoopSize > 16 && LoopSize <= 32)
11401       return 5;
11402
11403     break;
11404   }
11405   }
11406
11407   return TargetLowering::getPrefLoopAlignment(ML);
11408 }
11409
11410 /// getConstraintType - Given a constraint, return the type of
11411 /// constraint it is for this target.
11412 PPCTargetLowering::ConstraintType
11413 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11414   if (Constraint.size() == 1) {
11415     switch (Constraint[0]) {
11416     default: break;
11417     case 'b':
11418     case 'r':
11419     case 'f':
11420     case 'd':
11421     case 'v':
11422     case 'y':
11423       return C_RegisterClass;
11424     case 'Z':
11425       // FIXME: While Z does indicate a memory constraint, it specifically
11426       // indicates an r+r address (used in conjunction with the 'y' modifier
11427       // in the replacement string). Currently, we're forcing the base
11428       // register to be r0 in the asm printer (which is interpreted as zero)
11429       // and forming the complete address in the second register. This is
11430       // suboptimal.
11431       return C_Memory;
11432     }
11433   } else if (Constraint == "wc") { // individual CR bits.
11434     return C_RegisterClass;
11435   } else if (Constraint == "wa" || Constraint == "wd" ||
11436              Constraint == "wf" || Constraint == "ws") {
11437     return C_RegisterClass; // VSX registers.
11438   }
11439   return TargetLowering::getConstraintType(Constraint);
11440 }
11441
11442 /// Examine constraint type and operand type and determine a weight value.
11443 /// This object must already have been set up with the operand type
11444 /// and the current alternative constraint selected.
11445 TargetLowering::ConstraintWeight
11446 PPCTargetLowering::getSingleConstraintMatchWeight(
11447     AsmOperandInfo &info, const char *constraint) const {
11448   ConstraintWeight weight = CW_Invalid;
11449   Value *CallOperandVal = info.CallOperandVal;
11450     // If we don't have a value, we can't do a match,
11451     // but allow it at the lowest weight.
11452   if (!CallOperandVal)
11453     return CW_Default;
11454   Type *type = CallOperandVal->getType();
11455
11456   // Look at the constraint type.
11457   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11458     return CW_Register; // an individual CR bit.
11459   else if ((StringRef(constraint) == "wa" ||
11460             StringRef(constraint) == "wd" ||
11461             StringRef(constraint) == "wf") &&
11462            type->isVectorTy())
11463     return CW_Register;
11464   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11465     return CW_Register;
11466
11467   switch (*constraint) {
11468   default:
11469     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11470     break;
11471   case 'b':
11472     if (type->isIntegerTy())
11473       weight = CW_Register;
11474     break;
11475   case 'f':
11476     if (type->isFloatTy())
11477       weight = CW_Register;
11478     break;
11479   case 'd':
11480     if (type->isDoubleTy())
11481       weight = CW_Register;
11482     break;
11483   case 'v':
11484     if (type->isVectorTy())
11485       weight = CW_Register;
11486     break;
11487   case 'y':
11488     weight = CW_Register;
11489     break;
11490   case 'Z':
11491     weight = CW_Memory;
11492     break;
11493   }
11494   return weight;
11495 }
11496
11497 std::pair<unsigned, const TargetRegisterClass *>
11498 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11499                                                 StringRef Constraint,
11500                                                 MVT VT) const {
11501   if (Constraint.size() == 1) {
11502     // GCC RS6000 Constraint Letters
11503     switch (Constraint[0]) {
11504     case 'b':   // R1-R31
11505       if (VT == MVT::i64 && Subtarget.isPPC64())
11506         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11507       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11508     case 'r':   // R0-R31
11509       if (VT == MVT::i64 && Subtarget.isPPC64())
11510         return std::make_pair(0U, &PPC::G8RCRegClass);
11511       return std::make_pair(0U, &PPC::GPRCRegClass);
11512     // 'd' and 'f' constraints are both defined to be "the floating point
11513     // registers", where one is for 32-bit and the other for 64-bit. We don't
11514     // really care overly much here so just give them all the same reg classes.
11515     case 'd':
11516     case 'f':
11517       if (VT == MVT::f32 || VT == MVT::i32)
11518         return std::make_pair(0U, &PPC::F4RCRegClass);
11519       if (VT == MVT::f64 || VT == MVT::i64)
11520         return std::make_pair(0U, &PPC::F8RCRegClass);
11521       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11522         return std::make_pair(0U, &PPC::QFRCRegClass);
11523       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11524         return std::make_pair(0U, &PPC::QSRCRegClass);
11525       break;
11526     case 'v':
11527       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11528         return std::make_pair(0U, &PPC::QFRCRegClass);
11529       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11530         return std::make_pair(0U, &PPC::QSRCRegClass);
11531       if (Subtarget.hasAltivec())
11532         return std::make_pair(0U, &PPC::VRRCRegClass);
11533     case 'y':   // crrc
11534       return std::make_pair(0U, &PPC::CRRCRegClass);
11535     }
11536   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11537     // An individual CR bit.
11538     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11539   } else if ((Constraint == "wa" || Constraint == "wd" ||
11540              Constraint == "wf") && Subtarget.hasVSX()) {
11541     return std::make_pair(0U, &PPC::VSRCRegClass);
11542   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11543     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11544       return std::make_pair(0U, &PPC::VSSRCRegClass);
11545     else
11546       return std::make_pair(0U, &PPC::VSFRCRegClass);
11547   }
11548
11549   std::pair<unsigned, const TargetRegisterClass *> R =
11550       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11551
11552   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11553   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11554   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11555   // register.
11556   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11557   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11558   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11559       PPC::GPRCRegClass.contains(R.first))
11560     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11561                             PPC::sub_32, &PPC::G8RCRegClass),
11562                           &PPC::G8RCRegClass);
11563
11564   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11565   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11566     R.first = PPC::CR0;
11567     R.second = &PPC::CRRCRegClass;
11568   }
11569
11570   return R;
11571 }
11572
11573 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11574 /// vector.  If it is invalid, don't add anything to Ops.
11575 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11576                                                      std::string &Constraint,
11577                                                      std::vector<SDValue>&Ops,
11578                                                      SelectionDAG &DAG) const {
11579   SDValue Result;
11580
11581   // Only support length 1 constraints.
11582   if (Constraint.length() > 1) return;
11583
11584   char Letter = Constraint[0];
11585   switch (Letter) {
11586   default: break;
11587   case 'I':
11588   case 'J':
11589   case 'K':
11590   case 'L':
11591   case 'M':
11592   case 'N':
11593   case 'O':
11594   case 'P': {
11595     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11596     if (!CST) return; // Must be an immediate to match.
11597     SDLoc dl(Op);
11598     int64_t Value = CST->getSExtValue();
11599     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11600                          // numbers are printed as such.
11601     switch (Letter) {
11602     default: llvm_unreachable("Unknown constraint letter!");
11603     case 'I':  // "I" is a signed 16-bit constant.
11604       if (isInt<16>(Value))
11605         Result = DAG.getTargetConstant(Value, dl, TCVT);
11606       break;
11607     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11608       if (isShiftedUInt<16, 16>(Value))
11609         Result = DAG.getTargetConstant(Value, dl, TCVT);
11610       break;
11611     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11612       if (isShiftedInt<16, 16>(Value))
11613         Result = DAG.getTargetConstant(Value, dl, TCVT);
11614       break;
11615     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11616       if (isUInt<16>(Value))
11617         Result = DAG.getTargetConstant(Value, dl, TCVT);
11618       break;
11619     case 'M':  // "M" is a constant that is greater than 31.
11620       if (Value > 31)
11621         Result = DAG.getTargetConstant(Value, dl, TCVT);
11622       break;
11623     case 'N':  // "N" is a positive constant that is an exact power of two.
11624       if (Value > 0 && isPowerOf2_64(Value))
11625         Result = DAG.getTargetConstant(Value, dl, TCVT);
11626       break;
11627     case 'O':  // "O" is the constant zero.
11628       if (Value == 0)
11629         Result = DAG.getTargetConstant(Value, dl, TCVT);
11630       break;
11631     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11632       if (isInt<16>(-Value))
11633         Result = DAG.getTargetConstant(Value, dl, TCVT);
11634       break;
11635     }
11636     break;
11637   }
11638   }
11639
11640   if (Result.getNode()) {
11641     Ops.push_back(Result);
11642     return;
11643   }
11644
11645   // Handle standard constraint letters.
11646   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11647 }
11648
11649 // isLegalAddressingMode - Return true if the addressing mode represented
11650 // by AM is legal for this target, for a load/store of the specified type.
11651 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11652                                               const AddrMode &AM, Type *Ty,
11653                                               unsigned AS) const {
11654   // PPC does not allow r+i addressing modes for vectors!
11655   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11656     return false;
11657
11658   // PPC allows a sign-extended 16-bit immediate field.
11659   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11660     return false;
11661
11662   // No global is ever allowed as a base.
11663   if (AM.BaseGV)
11664     return false;
11665
11666   // PPC only support r+r,
11667   switch (AM.Scale) {
11668   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11669     break;
11670   case 1:
11671     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11672       return false;
11673     // Otherwise we have r+r or r+i.
11674     break;
11675   case 2:
11676     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11677       return false;
11678     // Allow 2*r as r+r.
11679     break;
11680   default:
11681     // No other scales are supported.
11682     return false;
11683   }
11684
11685   return true;
11686 }
11687
11688 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11689                                            SelectionDAG &DAG) const {
11690   MachineFunction &MF = DAG.getMachineFunction();
11691   MachineFrameInfo *MFI = MF.getFrameInfo();
11692   MFI->setReturnAddressIsTaken(true);
11693
11694   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11695     return SDValue();
11696
11697   SDLoc dl(Op);
11698   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11699
11700   // Make sure the function does not optimize away the store of the RA to
11701   // the stack.
11702   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11703   FuncInfo->setLRStoreRequired();
11704   bool isPPC64 = Subtarget.isPPC64();
11705   auto PtrVT = getPointerTy(MF.getDataLayout());
11706
11707   if (Depth > 0) {
11708     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11709     SDValue Offset =
11710         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11711                         isPPC64 ? MVT::i64 : MVT::i32);
11712     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11713                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11714                        MachinePointerInfo());
11715   }
11716
11717   // Just load the return address off the stack.
11718   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11719   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11720                      MachinePointerInfo());
11721 }
11722
11723 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11724                                           SelectionDAG &DAG) const {
11725   SDLoc dl(Op);
11726   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11727
11728   MachineFunction &MF = DAG.getMachineFunction();
11729   MachineFrameInfo *MFI = MF.getFrameInfo();
11730   MFI->setFrameAddressIsTaken(true);
11731
11732   EVT PtrVT = getPointerTy(MF.getDataLayout());
11733   bool isPPC64 = PtrVT == MVT::i64;
11734
11735   // Naked functions never have a frame pointer, and so we use r1. For all
11736   // other functions, this decision must be delayed until during PEI.
11737   unsigned FrameReg;
11738   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11739     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11740   else
11741     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11742
11743   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11744                                          PtrVT);
11745   while (Depth--)
11746     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11747                             FrameAddr, MachinePointerInfo());
11748   return FrameAddr;
11749 }
11750
11751 // FIXME? Maybe this could be a TableGen attribute on some registers and
11752 // this table could be generated automatically from RegInfo.
11753 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11754                                               SelectionDAG &DAG) const {
11755   bool isPPC64 = Subtarget.isPPC64();
11756   bool isDarwinABI = Subtarget.isDarwinABI();
11757
11758   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11759       (!isPPC64 && VT != MVT::i32))
11760     report_fatal_error("Invalid register global variable type");
11761
11762   bool is64Bit = isPPC64 && VT == MVT::i64;
11763   unsigned Reg = StringSwitch<unsigned>(RegName)
11764                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11765                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11766                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11767                                   (is64Bit ? PPC::X13 : PPC::R13))
11768                    .Default(0);
11769
11770   if (Reg)
11771     return Reg;
11772   report_fatal_error("Invalid register name global variable");
11773 }
11774
11775 bool
11776 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11777   // The PowerPC target isn't yet aware of offsets.
11778   return false;
11779 }
11780
11781 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11782                                            const CallInst &I,
11783                                            unsigned Intrinsic) const {
11784
11785   switch (Intrinsic) {
11786   case Intrinsic::ppc_qpx_qvlfd:
11787   case Intrinsic::ppc_qpx_qvlfs:
11788   case Intrinsic::ppc_qpx_qvlfcd:
11789   case Intrinsic::ppc_qpx_qvlfcs:
11790   case Intrinsic::ppc_qpx_qvlfiwa:
11791   case Intrinsic::ppc_qpx_qvlfiwz:
11792   case Intrinsic::ppc_altivec_lvx:
11793   case Intrinsic::ppc_altivec_lvxl:
11794   case Intrinsic::ppc_altivec_lvebx:
11795   case Intrinsic::ppc_altivec_lvehx:
11796   case Intrinsic::ppc_altivec_lvewx:
11797   case Intrinsic::ppc_vsx_lxvd2x:
11798   case Intrinsic::ppc_vsx_lxvw4x: {
11799     EVT VT;
11800     switch (Intrinsic) {
11801     case Intrinsic::ppc_altivec_lvebx:
11802       VT = MVT::i8;
11803       break;
11804     case Intrinsic::ppc_altivec_lvehx:
11805       VT = MVT::i16;
11806       break;
11807     case Intrinsic::ppc_altivec_lvewx:
11808       VT = MVT::i32;
11809       break;
11810     case Intrinsic::ppc_vsx_lxvd2x:
11811       VT = MVT::v2f64;
11812       break;
11813     case Intrinsic::ppc_qpx_qvlfd:
11814       VT = MVT::v4f64;
11815       break;
11816     case Intrinsic::ppc_qpx_qvlfs:
11817       VT = MVT::v4f32;
11818       break;
11819     case Intrinsic::ppc_qpx_qvlfcd:
11820       VT = MVT::v2f64;
11821       break;
11822     case Intrinsic::ppc_qpx_qvlfcs:
11823       VT = MVT::v2f32;
11824       break;
11825     default:
11826       VT = MVT::v4i32;
11827       break;
11828     }
11829
11830     Info.opc = ISD::INTRINSIC_W_CHAIN;
11831     Info.memVT = VT;
11832     Info.ptrVal = I.getArgOperand(0);
11833     Info.offset = -VT.getStoreSize()+1;
11834     Info.size = 2*VT.getStoreSize()-1;
11835     Info.align = 1;
11836     Info.vol = false;
11837     Info.readMem = true;
11838     Info.writeMem = false;
11839     return true;
11840   }
11841   case Intrinsic::ppc_qpx_qvlfda:
11842   case Intrinsic::ppc_qpx_qvlfsa:
11843   case Intrinsic::ppc_qpx_qvlfcda:
11844   case Intrinsic::ppc_qpx_qvlfcsa:
11845   case Intrinsic::ppc_qpx_qvlfiwaa:
11846   case Intrinsic::ppc_qpx_qvlfiwza: {
11847     EVT VT;
11848     switch (Intrinsic) {
11849     case Intrinsic::ppc_qpx_qvlfda:
11850       VT = MVT::v4f64;
11851       break;
11852     case Intrinsic::ppc_qpx_qvlfsa:
11853       VT = MVT::v4f32;
11854       break;
11855     case Intrinsic::ppc_qpx_qvlfcda:
11856       VT = MVT::v2f64;
11857       break;
11858     case Intrinsic::ppc_qpx_qvlfcsa:
11859       VT = MVT::v2f32;
11860       break;
11861     default:
11862       VT = MVT::v4i32;
11863       break;
11864     }
11865
11866     Info.opc = ISD::INTRINSIC_W_CHAIN;
11867     Info.memVT = VT;
11868     Info.ptrVal = I.getArgOperand(0);
11869     Info.offset = 0;
11870     Info.size = VT.getStoreSize();
11871     Info.align = 1;
11872     Info.vol = false;
11873     Info.readMem = true;
11874     Info.writeMem = false;
11875     return true;
11876   }
11877   case Intrinsic::ppc_qpx_qvstfd:
11878   case Intrinsic::ppc_qpx_qvstfs:
11879   case Intrinsic::ppc_qpx_qvstfcd:
11880   case Intrinsic::ppc_qpx_qvstfcs:
11881   case Intrinsic::ppc_qpx_qvstfiw:
11882   case Intrinsic::ppc_altivec_stvx:
11883   case Intrinsic::ppc_altivec_stvxl:
11884   case Intrinsic::ppc_altivec_stvebx:
11885   case Intrinsic::ppc_altivec_stvehx:
11886   case Intrinsic::ppc_altivec_stvewx:
11887   case Intrinsic::ppc_vsx_stxvd2x:
11888   case Intrinsic::ppc_vsx_stxvw4x: {
11889     EVT VT;
11890     switch (Intrinsic) {
11891     case Intrinsic::ppc_altivec_stvebx:
11892       VT = MVT::i8;
11893       break;
11894     case Intrinsic::ppc_altivec_stvehx:
11895       VT = MVT::i16;
11896       break;
11897     case Intrinsic::ppc_altivec_stvewx:
11898       VT = MVT::i32;
11899       break;
11900     case Intrinsic::ppc_vsx_stxvd2x:
11901       VT = MVT::v2f64;
11902       break;
11903     case Intrinsic::ppc_qpx_qvstfd:
11904       VT = MVT::v4f64;
11905       break;
11906     case Intrinsic::ppc_qpx_qvstfs:
11907       VT = MVT::v4f32;
11908       break;
11909     case Intrinsic::ppc_qpx_qvstfcd:
11910       VT = MVT::v2f64;
11911       break;
11912     case Intrinsic::ppc_qpx_qvstfcs:
11913       VT = MVT::v2f32;
11914       break;
11915     default:
11916       VT = MVT::v4i32;
11917       break;
11918     }
11919
11920     Info.opc = ISD::INTRINSIC_VOID;
11921     Info.memVT = VT;
11922     Info.ptrVal = I.getArgOperand(1);
11923     Info.offset = -VT.getStoreSize()+1;
11924     Info.size = 2*VT.getStoreSize()-1;
11925     Info.align = 1;
11926     Info.vol = false;
11927     Info.readMem = false;
11928     Info.writeMem = true;
11929     return true;
11930   }
11931   case Intrinsic::ppc_qpx_qvstfda:
11932   case Intrinsic::ppc_qpx_qvstfsa:
11933   case Intrinsic::ppc_qpx_qvstfcda:
11934   case Intrinsic::ppc_qpx_qvstfcsa:
11935   case Intrinsic::ppc_qpx_qvstfiwa: {
11936     EVT VT;
11937     switch (Intrinsic) {
11938     case Intrinsic::ppc_qpx_qvstfda:
11939       VT = MVT::v4f64;
11940       break;
11941     case Intrinsic::ppc_qpx_qvstfsa:
11942       VT = MVT::v4f32;
11943       break;
11944     case Intrinsic::ppc_qpx_qvstfcda:
11945       VT = MVT::v2f64;
11946       break;
11947     case Intrinsic::ppc_qpx_qvstfcsa:
11948       VT = MVT::v2f32;
11949       break;
11950     default:
11951       VT = MVT::v4i32;
11952       break;
11953     }
11954
11955     Info.opc = ISD::INTRINSIC_VOID;
11956     Info.memVT = VT;
11957     Info.ptrVal = I.getArgOperand(1);
11958     Info.offset = 0;
11959     Info.size = VT.getStoreSize();
11960     Info.align = 1;
11961     Info.vol = false;
11962     Info.readMem = false;
11963     Info.writeMem = true;
11964     return true;
11965   }
11966   default:
11967     break;
11968   }
11969
11970   return false;
11971 }
11972
11973 /// getOptimalMemOpType - Returns the target specific optimal type for load
11974 /// and store operations as a result of memset, memcpy, and memmove
11975 /// lowering. If DstAlign is zero that means it's safe to destination
11976 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11977 /// means there isn't a need to check it against alignment requirement,
11978 /// probably because the source does not need to be loaded. If 'IsMemset' is
11979 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11980 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11981 /// source is constant so it does not need to be loaded.
11982 /// It returns EVT::Other if the type should be determined using generic
11983 /// target-independent logic.
11984 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11985                                            unsigned DstAlign, unsigned SrcAlign,
11986                                            bool IsMemset, bool ZeroMemset,
11987                                            bool MemcpyStrSrc,
11988                                            MachineFunction &MF) const {
11989   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11990     const Function *F = MF.getFunction();
11991     // When expanding a memset, require at least two QPX instructions to cover
11992     // the cost of loading the value to be stored from the constant pool.
11993     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11994        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11995         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11996       return MVT::v4f64;
11997     }
11998
11999     // We should use Altivec/VSX loads and stores when available. For unaligned
12000     // addresses, unaligned VSX loads are only fast starting with the P8.
12001     if (Subtarget.hasAltivec() && Size >= 16 &&
12002         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12003          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12004       return MVT::v4i32;
12005   }
12006
12007   if (Subtarget.isPPC64()) {
12008     return MVT::i64;
12009   }
12010
12011   return MVT::i32;
12012 }
12013
12014 /// \brief Returns true if it is beneficial to convert a load of a constant
12015 /// to just the constant itself.
12016 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12017                                                           Type *Ty) const {
12018   assert(Ty->isIntegerTy());
12019
12020   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12021   return !(BitSize == 0 || BitSize > 64);
12022 }
12023
12024 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12025   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12026     return false;
12027   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12028   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12029   return NumBits1 == 64 && NumBits2 == 32;
12030 }
12031
12032 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12033   if (!VT1.isInteger() || !VT2.isInteger())
12034     return false;
12035   unsigned NumBits1 = VT1.getSizeInBits();
12036   unsigned NumBits2 = VT2.getSizeInBits();
12037   return NumBits1 == 64 && NumBits2 == 32;
12038 }
12039
12040 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12041   // Generally speaking, zexts are not free, but they are free when they can be
12042   // folded with other operations.
12043   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12044     EVT MemVT = LD->getMemoryVT();
12045     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12046          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12047         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12048          LD->getExtensionType() == ISD::ZEXTLOAD))
12049       return true;
12050   }
12051
12052   // FIXME: Add other cases...
12053   //  - 32-bit shifts with a zext to i64
12054   //  - zext after ctlz, bswap, etc.
12055   //  - zext after and by a constant mask
12056
12057   return TargetLowering::isZExtFree(Val, VT2);
12058 }
12059
12060 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12061   assert(VT.isFloatingPoint());
12062   return true;
12063 }
12064
12065 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12066   return isInt<16>(Imm) || isUInt<16>(Imm);
12067 }
12068
12069 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12070   return isInt<16>(Imm) || isUInt<16>(Imm);
12071 }
12072
12073 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12074                                                        unsigned,
12075                                                        unsigned,
12076                                                        bool *Fast) const {
12077   if (DisablePPCUnaligned)
12078     return false;
12079
12080   // PowerPC supports unaligned memory access for simple non-vector types.
12081   // Although accessing unaligned addresses is not as efficient as accessing
12082   // aligned addresses, it is generally more efficient than manual expansion,
12083   // and generally only traps for software emulation when crossing page
12084   // boundaries.
12085
12086   if (!VT.isSimple())
12087     return false;
12088
12089   if (VT.getSimpleVT().isVector()) {
12090     if (Subtarget.hasVSX()) {
12091       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12092           VT != MVT::v4f32 && VT != MVT::v4i32)
12093         return false;
12094     } else {
12095       return false;
12096     }
12097   }
12098
12099   if (VT == MVT::ppcf128)
12100     return false;
12101
12102   if (Fast)
12103     *Fast = true;
12104
12105   return true;
12106 }
12107
12108 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12109   VT = VT.getScalarType();
12110
12111   if (!VT.isSimple())
12112     return false;
12113
12114   switch (VT.getSimpleVT().SimpleTy) {
12115   case MVT::f32:
12116   case MVT::f64:
12117     return true;
12118   default:
12119     break;
12120   }
12121
12122   return false;
12123 }
12124
12125 const MCPhysReg *
12126 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12127   // LR is a callee-save register, but we must treat it as clobbered by any call
12128   // site. Hence we include LR in the scratch registers, which are in turn added
12129   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12130   // to CTR, which is used by any indirect call.
12131   static const MCPhysReg ScratchRegs[] = {
12132     PPC::X12, PPC::LR8, PPC::CTR8, 0
12133   };
12134
12135   return ScratchRegs;
12136 }
12137
12138 unsigned PPCTargetLowering::getExceptionPointerRegister(
12139     const Constant *PersonalityFn) const {
12140   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12141 }
12142
12143 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12144     const Constant *PersonalityFn) const {
12145   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12146 }
12147
12148 bool
12149 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12150                      EVT VT , unsigned DefinedValues) const {
12151   if (VT == MVT::v2i64)
12152     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12153
12154   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12155     return true;
12156
12157   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12158 }
12159
12160 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12161   if (DisableILPPref || Subtarget.enableMachineScheduler())
12162     return TargetLowering::getSchedulingPreference(N);
12163
12164   return Sched::ILP;
12165 }
12166
12167 // Create a fast isel object.
12168 FastISel *
12169 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12170                                   const TargetLibraryInfo *LibInfo) const {
12171   return PPC::createFastISel(FuncInfo, LibInfo);
12172 }
12173
12174 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12175   if (Subtarget.isDarwinABI()) return;
12176   if (!Subtarget.isPPC64()) return;
12177
12178   // Update IsSplitCSR in PPCFunctionInfo
12179   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12180   PFI->setIsSplitCSR(true);
12181 }
12182
12183 void PPCTargetLowering::insertCopiesSplitCSR(
12184   MachineBasicBlock *Entry,
12185   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12186   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12187   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12188   if (!IStart)
12189     return;
12190
12191   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12192   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12193   MachineBasicBlock::iterator MBBI = Entry->begin();
12194   for (const MCPhysReg *I = IStart; *I; ++I) {
12195     const TargetRegisterClass *RC = nullptr;
12196     if (PPC::G8RCRegClass.contains(*I))
12197       RC = &PPC::G8RCRegClass;
12198     else if (PPC::F8RCRegClass.contains(*I))
12199       RC = &PPC::F8RCRegClass;
12200     else if (PPC::CRRCRegClass.contains(*I))
12201       RC = &PPC::CRRCRegClass;
12202     else if (PPC::VRRCRegClass.contains(*I))
12203       RC = &PPC::VRRCRegClass;
12204     else
12205       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12206
12207     unsigned NewVR = MRI->createVirtualRegister(RC);
12208     // Create copy from CSR to a virtual register.
12209     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12210     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12211     // nounwind. If we want to generalize this later, we may need to emit
12212     // CFI pseudo-instructions.
12213     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12214              Attribute::NoUnwind) &&
12215            "Function should be nounwind in insertCopiesSplitCSR!");
12216     Entry->addLiveIn(*I);
12217     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12218       .addReg(*I);
12219
12220     // Insert the copy-back instructions right before the terminator
12221     for (auto *Exit : Exits)
12222       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12223               TII->get(TargetOpcode::COPY), *I)
12224         .addReg(NewVR);
12225   }
12226 }
12227
12228 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12229 bool PPCTargetLowering::useLoadStackGuardNode() const {
12230   if (!Subtarget.isTargetLinux())
12231     return TargetLowering::useLoadStackGuardNode();
12232   return true;
12233 }
12234
12235 // Override to disable global variable loading on Linux.
12236 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12237   if (!Subtarget.isTargetLinux())
12238     return TargetLowering::insertSSPDeclarations(M);
12239 }