OSDN Git Service

Rename argument for consistency.
[android-x86/external-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "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 (!Subtarget.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
348   // We want to custom lower some of our intrinsics.
349   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
350
351   // To handle counter-based loop conditions.
352   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
353
354   // Comparisons that require checking two conditions.
355   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
356   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
357   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
358   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
359   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
360   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
361   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
362   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
363   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
364   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
365   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
366   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
367
368   if (Subtarget.has64BitSupport()) {
369     // They also have instructions for converting between i64 and fp.
370     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
371     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
372     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
373     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
374     // This is just the low 32 bits of a (signed) fp->i64 conversion.
375     // We cannot do this with Promote because i64 is not a legal type.
376     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
377
378     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
379       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
380   } else {
381     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
382     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
383   }
384
385   // With the instructions enabled under FPCVT, we can do everything.
386   if (Subtarget.hasFPCVT()) {
387     if (Subtarget.has64BitSupport()) {
388       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
389       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
390       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
391       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
392     }
393
394     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
395     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
396     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
397     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
398   }
399
400   if (Subtarget.use64BitRegs()) {
401     // 64-bit PowerPC implementations can support i64 types directly
402     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
403     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
404     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
405     // 64-bit PowerPC wants to expand i128 shifts itself.
406     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
407     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
408     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
409   } else {
410     // 32-bit PowerPC wants to expand i64 shifts itself.
411     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
412     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
413     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
414   }
415
416   if (Subtarget.hasAltivec()) {
417     // First set operation action for all vector types to expand. Then we
418     // will selectively turn on ones that can be effectively codegen'd.
419     for (MVT VT : MVT::vector_valuetypes()) {
420       // add/sub are legal for all supported vector VT's.
421       setOperationAction(ISD::ADD, VT, Legal);
422       setOperationAction(ISD::SUB, VT, Legal);
423
424       // Vector instructions introduced in P8
425       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
426         setOperationAction(ISD::CTPOP, VT, Legal);
427         setOperationAction(ISD::CTLZ, VT, Legal);
428       }
429       else {
430         setOperationAction(ISD::CTPOP, VT, Expand);
431         setOperationAction(ISD::CTLZ, VT, Expand);
432       }
433
434       // We promote all shuffles to v16i8.
435       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
436       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
437
438       // We promote all non-typed operations to v4i32.
439       setOperationAction(ISD::AND   , VT, Promote);
440       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
441       setOperationAction(ISD::OR    , VT, Promote);
442       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
443       setOperationAction(ISD::XOR   , VT, Promote);
444       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
445       setOperationAction(ISD::LOAD  , VT, Promote);
446       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
447       setOperationAction(ISD::SELECT, VT, Promote);
448       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
449       setOperationAction(ISD::SELECT_CC, VT, Promote);
450       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
451       setOperationAction(ISD::STORE, VT, Promote);
452       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
453
454       // No other operations are legal.
455       setOperationAction(ISD::MUL , VT, Expand);
456       setOperationAction(ISD::SDIV, VT, Expand);
457       setOperationAction(ISD::SREM, VT, Expand);
458       setOperationAction(ISD::UDIV, VT, Expand);
459       setOperationAction(ISD::UREM, VT, Expand);
460       setOperationAction(ISD::FDIV, VT, Expand);
461       setOperationAction(ISD::FREM, VT, Expand);
462       setOperationAction(ISD::FNEG, VT, Expand);
463       setOperationAction(ISD::FSQRT, VT, Expand);
464       setOperationAction(ISD::FLOG, VT, Expand);
465       setOperationAction(ISD::FLOG10, VT, Expand);
466       setOperationAction(ISD::FLOG2, VT, Expand);
467       setOperationAction(ISD::FEXP, VT, Expand);
468       setOperationAction(ISD::FEXP2, VT, Expand);
469       setOperationAction(ISD::FSIN, VT, Expand);
470       setOperationAction(ISD::FCOS, VT, Expand);
471       setOperationAction(ISD::FABS, VT, Expand);
472       setOperationAction(ISD::FPOWI, VT, Expand);
473       setOperationAction(ISD::FFLOOR, VT, Expand);
474       setOperationAction(ISD::FCEIL,  VT, Expand);
475       setOperationAction(ISD::FTRUNC, VT, Expand);
476       setOperationAction(ISD::FRINT,  VT, Expand);
477       setOperationAction(ISD::FNEARBYINT, VT, Expand);
478       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
479       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
480       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
481       setOperationAction(ISD::MULHU, VT, Expand);
482       setOperationAction(ISD::MULHS, VT, Expand);
483       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
484       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
485       setOperationAction(ISD::UDIVREM, VT, Expand);
486       setOperationAction(ISD::SDIVREM, VT, Expand);
487       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
488       setOperationAction(ISD::FPOW, VT, Expand);
489       setOperationAction(ISD::BSWAP, VT, Expand);
490       setOperationAction(ISD::CTTZ, VT, Expand);
491       setOperationAction(ISD::VSELECT, VT, Expand);
492       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
493       setOperationAction(ISD::ROTL, VT, Expand);
494       setOperationAction(ISD::ROTR, VT, Expand);
495
496       for (MVT InnerVT : MVT::vector_valuetypes()) {
497         setTruncStoreAction(VT, InnerVT, Expand);
498         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
499         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
500         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
501       }
502     }
503
504     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
505     // with merges, splats, etc.
506     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
507
508     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
509     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
510     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
511     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
512     setOperationAction(ISD::SELECT, MVT::v4i32,
513                        Subtarget.useCRBits() ? Legal : Expand);
514     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
515     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
516     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
517     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
518     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
519     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
520     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
521     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
523
524     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
525     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
526     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
527     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
528
529     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
530     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
531
532     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
533       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
534       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
535     }
536
537     if (Subtarget.hasP8Altivec())
538       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
539     else
540       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
541
542     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
543     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
544
545     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
546     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
547
548     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
549     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
550     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
551     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
552
553     // Altivec does not contain unordered floating-point compare instructions
554     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
555     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
556     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
557     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
558
559     if (Subtarget.hasVSX()) {
560       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
561       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
562       if (Subtarget.hasP8Vector()) {
563         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
564         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
565       }
566       if (Subtarget.hasDirectMove() && isPPC64) {
567         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
568         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
569         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
570         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
571         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
572         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
573         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
574         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
575       }
576       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
577
578       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
579       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
580       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
581       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
582       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
583
584       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
585
586       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
587       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
588
589       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
590       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
591
592       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
593       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
594       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
595       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
596       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
597
598       // Share the Altivec comparison restrictions.
599       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
600       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
601       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
602       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
603
604       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
605       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
606
607       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
608
609       if (Subtarget.hasP8Vector())
610         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
611
612       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
613
614       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
615       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
616       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
617
618       if (Subtarget.hasP8Altivec()) {
619         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
620         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
621         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
622
623         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
624       }
625       else {
626         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
627         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
628         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
629
630         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
631
632         // VSX v2i64 only supports non-arithmetic operations.
633         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
634         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
635       }
636
637       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
638       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
639       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
640       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
641
642       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
643
644       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
645       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
646       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
647       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
648
649       // Vector operation legalization checks the result type of
650       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
651       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
652       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
653       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
654       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
655
656       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
657       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
658       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
659       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
660
661       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
662     }
663
664     if (Subtarget.hasP8Altivec()) {
665       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
666       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
667     }
668   }
669
670   if (Subtarget.hasQPX()) {
671     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
672     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
673     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
674     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
675
676     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
677     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
678
679     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
680     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
681
682     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
683     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
684
685     if (!Subtarget.useCRBits())
686       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
687     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
688
689     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
690     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
691     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
692     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
693     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
694     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
695     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
696
697     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
698     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
699
700     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
701     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
702     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
703
704     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
705     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
706     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
707     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
708     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
709     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
710     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
711     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
712     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
713     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
714     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
715
716     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
717     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
718
719     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
720     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
721
722     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
723
724     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
725     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
726     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
727     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
728
729     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
730     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
731
732     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
733     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
734
735     if (!Subtarget.useCRBits())
736       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
737     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
738
739     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
740     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
741     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
742     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
743     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
744     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
745     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
746
747     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
748     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
749
750     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
751     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
752     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
753     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
754     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
755     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
756     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
757     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
758     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
759     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
760     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
761
762     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
763     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
764
765     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
766     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
767
768     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
769
770     setOperationAction(ISD::AND , MVT::v4i1, Legal);
771     setOperationAction(ISD::OR , MVT::v4i1, Legal);
772     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
773
774     if (!Subtarget.useCRBits())
775       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
776     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
777
778     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
779     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
780
781     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
782     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
783     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
784     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
785     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
786     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
787     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
788
789     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
790     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
791
792     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
793
794     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
795     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
796     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
797     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
798
799     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
800     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
801     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
802     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
803
804     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
805     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
806
807     // These need to set FE_INEXACT, and so cannot be vectorized here.
808     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
809     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
810
811     if (TM.Options.UnsafeFPMath) {
812       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
813       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
814
815       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
816       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
817     } else {
818       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
819       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
820
821       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
822       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
823     }
824   }
825
826   if (Subtarget.has64BitSupport())
827     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
828
829   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
830
831   if (!isPPC64) {
832     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
833     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
834   }
835
836   setBooleanContents(ZeroOrOneBooleanContent);
837
838   if (Subtarget.hasAltivec()) {
839     // Altivec instructions set fields to all zeros or all ones.
840     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
841   }
842
843   if (!isPPC64) {
844     // These libcalls are not available in 32-bit.
845     setLibcallName(RTLIB::SHL_I128, nullptr);
846     setLibcallName(RTLIB::SRL_I128, nullptr);
847     setLibcallName(RTLIB::SRA_I128, nullptr);
848   }
849
850   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
851
852   // We have target-specific dag combine patterns for the following nodes:
853   setTargetDAGCombine(ISD::SINT_TO_FP);
854   setTargetDAGCombine(ISD::BUILD_VECTOR);
855   if (Subtarget.hasFPCVT())
856     setTargetDAGCombine(ISD::UINT_TO_FP);
857   setTargetDAGCombine(ISD::LOAD);
858   setTargetDAGCombine(ISD::STORE);
859   setTargetDAGCombine(ISD::BR_CC);
860   if (Subtarget.useCRBits())
861     setTargetDAGCombine(ISD::BRCOND);
862   setTargetDAGCombine(ISD::BSWAP);
863   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
864   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
865   setTargetDAGCombine(ISD::INTRINSIC_VOID);
866
867   setTargetDAGCombine(ISD::SIGN_EXTEND);
868   setTargetDAGCombine(ISD::ZERO_EXTEND);
869   setTargetDAGCombine(ISD::ANY_EXTEND);
870
871   if (Subtarget.useCRBits()) {
872     setTargetDAGCombine(ISD::TRUNCATE);
873     setTargetDAGCombine(ISD::SETCC);
874     setTargetDAGCombine(ISD::SELECT_CC);
875   }
876
877   // Use reciprocal estimates.
878   if (TM.Options.UnsafeFPMath) {
879     setTargetDAGCombine(ISD::FDIV);
880     setTargetDAGCombine(ISD::FSQRT);
881   }
882
883   // Darwin long double math library functions have $LDBL128 appended.
884   if (Subtarget.isDarwin()) {
885     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
886     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
887     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
888     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
889     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
890     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
891     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
892     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
893     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
894     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
895   }
896
897   // With 32 condition bits, we don't need to sink (and duplicate) compares
898   // aggressively in CodeGenPrep.
899   if (Subtarget.useCRBits()) {
900     setHasMultipleConditionRegisters();
901     setJumpIsExpensive();
902   }
903
904   setMinFunctionAlignment(2);
905   if (Subtarget.isDarwin())
906     setPrefFunctionAlignment(4);
907
908   switch (Subtarget.getDarwinDirective()) {
909   default: break;
910   case PPC::DIR_970:
911   case PPC::DIR_A2:
912   case PPC::DIR_E500mc:
913   case PPC::DIR_E5500:
914   case PPC::DIR_PWR4:
915   case PPC::DIR_PWR5:
916   case PPC::DIR_PWR5X:
917   case PPC::DIR_PWR6:
918   case PPC::DIR_PWR6X:
919   case PPC::DIR_PWR7:
920   case PPC::DIR_PWR8:
921   case PPC::DIR_PWR9:
922     setPrefFunctionAlignment(4);
923     setPrefLoopAlignment(4);
924     break;
925   }
926
927   if (Subtarget.enableMachineScheduler())
928     setSchedulingPreference(Sched::Source);
929   else
930     setSchedulingPreference(Sched::Hybrid);
931
932   computeRegisterProperties(STI.getRegisterInfo());
933
934   // The Freescale cores do better with aggressive inlining of memcpy and
935   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
936   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
937       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
938     MaxStoresPerMemset = 32;
939     MaxStoresPerMemsetOptSize = 16;
940     MaxStoresPerMemcpy = 32;
941     MaxStoresPerMemcpyOptSize = 8;
942     MaxStoresPerMemmove = 32;
943     MaxStoresPerMemmoveOptSize = 8;
944   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
945     // The A2 also benefits from (very) aggressive inlining of memcpy and
946     // friends. The overhead of a the function call, even when warm, can be
947     // over one hundred cycles.
948     MaxStoresPerMemset = 128;
949     MaxStoresPerMemcpy = 128;
950     MaxStoresPerMemmove = 128;
951   }
952 }
953
954 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
955 /// the desired ByVal argument alignment.
956 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
957                              unsigned MaxMaxAlign) {
958   if (MaxAlign == MaxMaxAlign)
959     return;
960   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
961     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
962       MaxAlign = 32;
963     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
964       MaxAlign = 16;
965   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
966     unsigned EltAlign = 0;
967     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
968     if (EltAlign > MaxAlign)
969       MaxAlign = EltAlign;
970   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
971     for (auto *EltTy : STy->elements()) {
972       unsigned EltAlign = 0;
973       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
974       if (EltAlign > MaxAlign)
975         MaxAlign = EltAlign;
976       if (MaxAlign == MaxMaxAlign)
977         break;
978     }
979   }
980 }
981
982 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
983 /// function arguments in the caller parameter area.
984 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
985                                                   const DataLayout &DL) const {
986   // Darwin passes everything on 4 byte boundary.
987   if (Subtarget.isDarwin())
988     return 4;
989
990   // 16byte and wider vectors are passed on 16byte boundary.
991   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
992   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
993   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
994     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
995   return Align;
996 }
997
998 bool PPCTargetLowering::useSoftFloat() const {
999   return Subtarget.useSoftFloat();
1000 }
1001
1002 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1003   switch ((PPCISD::NodeType)Opcode) {
1004   case PPCISD::FIRST_NUMBER:    break;
1005   case PPCISD::FSEL:            return "PPCISD::FSEL";
1006   case PPCISD::FCFID:           return "PPCISD::FCFID";
1007   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1008   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1009   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1010   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1011   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1012   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1013   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1014   case PPCISD::FRE:             return "PPCISD::FRE";
1015   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1016   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1017   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1018   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1019   case PPCISD::VPERM:           return "PPCISD::VPERM";
1020   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1021   case PPCISD::CMPB:            return "PPCISD::CMPB";
1022   case PPCISD::Hi:              return "PPCISD::Hi";
1023   case PPCISD::Lo:              return "PPCISD::Lo";
1024   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1025   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1026   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1027   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1028   case PPCISD::SRL:             return "PPCISD::SRL";
1029   case PPCISD::SRA:             return "PPCISD::SRA";
1030   case PPCISD::SHL:             return "PPCISD::SHL";
1031   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1032   case PPCISD::CALL:            return "PPCISD::CALL";
1033   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1034   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1035   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1036   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1037   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1038   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1039   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1040   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1041   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1042   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1043   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1044   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1045   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1046   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1047   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1048   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1049   case PPCISD::VCMP:            return "PPCISD::VCMP";
1050   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1051   case PPCISD::LBRX:            return "PPCISD::LBRX";
1052   case PPCISD::STBRX:           return "PPCISD::STBRX";
1053   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1054   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1055   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1056   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1057   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1058   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1059   case PPCISD::BDZ:             return "PPCISD::BDZ";
1060   case PPCISD::MFFS:            return "PPCISD::MFFS";
1061   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1062   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1063   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1064   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1065   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1066   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1067   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1068   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1069   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1070   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1071   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1072   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1073   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1074   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1075   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1076   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1077   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1078   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1079   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1080   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1081   case PPCISD::SC:              return "PPCISD::SC";
1082   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1083   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1084   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1085   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1086   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1087   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1088   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1089   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1090   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1091   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1092   }
1093   return nullptr;
1094 }
1095
1096 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1097                                           EVT VT) const {
1098   if (!VT.isVector())
1099     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1100
1101   if (Subtarget.hasQPX())
1102     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1103
1104   return VT.changeVectorElementTypeToInteger();
1105 }
1106
1107 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1108   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1109   return true;
1110 }
1111
1112 //===----------------------------------------------------------------------===//
1113 // Node matching predicates, for use by the tblgen matching code.
1114 //===----------------------------------------------------------------------===//
1115
1116 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1117 static bool isFloatingPointZero(SDValue Op) {
1118   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1119     return CFP->getValueAPF().isZero();
1120   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1121     // Maybe this has already been legalized into the constant pool?
1122     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1123       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1124         return CFP->getValueAPF().isZero();
1125   }
1126   return false;
1127 }
1128
1129 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1130 /// true if Op is undef or if it matches the specified value.
1131 static bool isConstantOrUndef(int Op, int Val) {
1132   return Op < 0 || Op == Val;
1133 }
1134
1135 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1136 /// VPKUHUM instruction.
1137 /// The ShuffleKind distinguishes between big-endian operations with
1138 /// two different inputs (0), either-endian operations with two identical
1139 /// inputs (1), and little-endian operations with two different inputs (2).
1140 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1141 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1142                                SelectionDAG &DAG) {
1143   bool IsLE = DAG.getDataLayout().isLittleEndian();
1144   if (ShuffleKind == 0) {
1145     if (IsLE)
1146       return false;
1147     for (unsigned i = 0; i != 16; ++i)
1148       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1149         return false;
1150   } else if (ShuffleKind == 2) {
1151     if (!IsLE)
1152       return false;
1153     for (unsigned i = 0; i != 16; ++i)
1154       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1155         return false;
1156   } else if (ShuffleKind == 1) {
1157     unsigned j = IsLE ? 0 : 1;
1158     for (unsigned i = 0; i != 8; ++i)
1159       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1160           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1161         return false;
1162   }
1163   return true;
1164 }
1165
1166 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1167 /// VPKUWUM instruction.
1168 /// The ShuffleKind distinguishes between big-endian operations with
1169 /// two different inputs (0), either-endian operations with two identical
1170 /// inputs (1), and little-endian operations with two different inputs (2).
1171 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1172 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1173                                SelectionDAG &DAG) {
1174   bool IsLE = DAG.getDataLayout().isLittleEndian();
1175   if (ShuffleKind == 0) {
1176     if (IsLE)
1177       return false;
1178     for (unsigned i = 0; i != 16; i += 2)
1179       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1180           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1181         return false;
1182   } else if (ShuffleKind == 2) {
1183     if (!IsLE)
1184       return false;
1185     for (unsigned i = 0; i != 16; i += 2)
1186       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1187           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1188         return false;
1189   } else if (ShuffleKind == 1) {
1190     unsigned j = IsLE ? 0 : 2;
1191     for (unsigned i = 0; i != 8; i += 2)
1192       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1193           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1194           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1195           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1196         return false;
1197   }
1198   return true;
1199 }
1200
1201 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1202 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1203 /// current subtarget.
1204 ///
1205 /// The ShuffleKind distinguishes between big-endian operations with
1206 /// two different inputs (0), either-endian operations with two identical
1207 /// inputs (1), and little-endian operations with two different inputs (2).
1208 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1209 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1210                                SelectionDAG &DAG) {
1211   const PPCSubtarget& Subtarget =
1212     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1213   if (!Subtarget.hasP8Vector())
1214     return false;
1215
1216   bool IsLE = DAG.getDataLayout().isLittleEndian();
1217   if (ShuffleKind == 0) {
1218     if (IsLE)
1219       return false;
1220     for (unsigned i = 0; i != 16; i += 4)
1221       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1222           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1223           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1224           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1225         return false;
1226   } else if (ShuffleKind == 2) {
1227     if (!IsLE)
1228       return false;
1229     for (unsigned i = 0; i != 16; i += 4)
1230       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1231           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1232           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1233           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1234         return false;
1235   } else if (ShuffleKind == 1) {
1236     unsigned j = IsLE ? 0 : 4;
1237     for (unsigned i = 0; i != 8; i += 4)
1238       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1239           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1240           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1241           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1242           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1243           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1244           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1245           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1246         return false;
1247   }
1248   return true;
1249 }
1250
1251 /// isVMerge - Common function, used to match vmrg* shuffles.
1252 ///
1253 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1254                      unsigned LHSStart, unsigned RHSStart) {
1255   if (N->getValueType(0) != MVT::v16i8)
1256     return false;
1257   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1258          "Unsupported merge size!");
1259
1260   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1261     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1262       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1263                              LHSStart+j+i*UnitSize) ||
1264           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1265                              RHSStart+j+i*UnitSize))
1266         return false;
1267     }
1268   return true;
1269 }
1270
1271 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1272 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1273 /// The ShuffleKind distinguishes between big-endian merges with two
1274 /// different inputs (0), either-endian merges with two identical inputs (1),
1275 /// and little-endian merges with two different inputs (2).  For the latter,
1276 /// the input operands are swapped (see PPCInstrAltivec.td).
1277 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1278                              unsigned ShuffleKind, SelectionDAG &DAG) {
1279   if (DAG.getDataLayout().isLittleEndian()) {
1280     if (ShuffleKind == 1) // unary
1281       return isVMerge(N, UnitSize, 0, 0);
1282     else if (ShuffleKind == 2) // swapped
1283       return isVMerge(N, UnitSize, 0, 16);
1284     else
1285       return false;
1286   } else {
1287     if (ShuffleKind == 1) // unary
1288       return isVMerge(N, UnitSize, 8, 8);
1289     else if (ShuffleKind == 0) // normal
1290       return isVMerge(N, UnitSize, 8, 24);
1291     else
1292       return false;
1293   }
1294 }
1295
1296 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1297 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1298 /// The ShuffleKind distinguishes between big-endian merges with two
1299 /// different inputs (0), either-endian merges with two identical inputs (1),
1300 /// and little-endian merges with two different inputs (2).  For the latter,
1301 /// the input operands are swapped (see PPCInstrAltivec.td).
1302 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1303                              unsigned ShuffleKind, SelectionDAG &DAG) {
1304   if (DAG.getDataLayout().isLittleEndian()) {
1305     if (ShuffleKind == 1) // unary
1306       return isVMerge(N, UnitSize, 8, 8);
1307     else if (ShuffleKind == 2) // swapped
1308       return isVMerge(N, UnitSize, 8, 24);
1309     else
1310       return false;
1311   } else {
1312     if (ShuffleKind == 1) // unary
1313       return isVMerge(N, UnitSize, 0, 0);
1314     else if (ShuffleKind == 0) // normal
1315       return isVMerge(N, UnitSize, 0, 16);
1316     else
1317       return false;
1318   }
1319 }
1320
1321 /**
1322  * \brief Common function used to match vmrgew and vmrgow shuffles
1323  *
1324  * The indexOffset determines whether to look for even or odd words in
1325  * the shuffle mask. This is based on the of the endianness of the target
1326  * machine.
1327  *   - Little Endian:
1328  *     - Use offset of 0 to check for odd elements
1329  *     - Use offset of 4 to check for even elements
1330  *   - Big Endian:
1331  *     - Use offset of 0 to check for even elements
1332  *     - Use offset of 4 to check for odd elements
1333  * A detailed description of the vector element ordering for little endian and
1334  * big endian can be found at
1335  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1336  * Targeting your applications - what little endian and big endian IBM XL C/C++
1337  * compiler differences mean to you
1338  *
1339  * The mask to the shuffle vector instruction specifies the indices of the
1340  * elements from the two input vectors to place in the result. The elements are
1341  * numbered in array-access order, starting with the first vector. These vectors
1342  * are always of type v16i8, thus each vector will contain 16 elements of size
1343  * 8. More info on the shuffle vector can be found in the
1344  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1345  * Language Reference.
1346  *
1347  * The RHSStartValue indicates whether the same input vectors are used (unary)
1348  * or two different input vectors are used, based on the following:
1349  *   - If the instruction uses the same vector for both inputs, the range of the
1350  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1351  *     be 0.
1352  *   - If the instruction has two different vectors then the range of the
1353  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1354  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1355  *     to 31 specify elements in the second vector).
1356  *
1357  * \param[in] N The shuffle vector SD Node to analyze
1358  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1359  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1360  * vector to the shuffle_vector instruction
1361  * \return true iff this shuffle vector represents an even or odd word merge
1362  */
1363 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1364                      unsigned RHSStartValue) {
1365   if (N->getValueType(0) != MVT::v16i8)
1366     return false;
1367
1368   for (unsigned i = 0; i < 2; ++i)
1369     for (unsigned j = 0; j < 4; ++j)
1370       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1371                              i*RHSStartValue+j+IndexOffset) ||
1372           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1373                              i*RHSStartValue+j+IndexOffset+8))
1374         return false;
1375   return true;
1376 }
1377
1378 /**
1379  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1380  * vmrgow instructions.
1381  *
1382  * \param[in] N The shuffle vector SD Node to analyze
1383  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1384  * \param[in] ShuffleKind Identify the type of merge:
1385  *   - 0 = big-endian merge with two different inputs;
1386  *   - 1 = either-endian merge with two identical inputs;
1387  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1388  *     little-endian merges).
1389  * \param[in] DAG The current SelectionDAG
1390  * \return true iff this shuffle mask
1391  */
1392 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1393                               unsigned ShuffleKind, SelectionDAG &DAG) {
1394   if (DAG.getDataLayout().isLittleEndian()) {
1395     unsigned indexOffset = CheckEven ? 4 : 0;
1396     if (ShuffleKind == 1) // Unary
1397       return isVMerge(N, indexOffset, 0);
1398     else if (ShuffleKind == 2) // swapped
1399       return isVMerge(N, indexOffset, 16);
1400     else
1401       return false;
1402   }
1403   else {
1404     unsigned indexOffset = CheckEven ? 0 : 4;
1405     if (ShuffleKind == 1) // Unary
1406       return isVMerge(N, indexOffset, 0);
1407     else if (ShuffleKind == 0) // Normal
1408       return isVMerge(N, indexOffset, 16);
1409     else
1410       return false;
1411   }
1412   return false;
1413 }
1414
1415 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1416 /// amount, otherwise return -1.
1417 /// The ShuffleKind distinguishes between big-endian operations with two
1418 /// different inputs (0), either-endian operations with two identical inputs
1419 /// (1), and little-endian operations with two different inputs (2).  For the
1420 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1421 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1422                              SelectionDAG &DAG) {
1423   if (N->getValueType(0) != MVT::v16i8)
1424     return -1;
1425
1426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1427
1428   // Find the first non-undef value in the shuffle mask.
1429   unsigned i;
1430   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1431     /*search*/;
1432
1433   if (i == 16) return -1;  // all undef.
1434
1435   // Otherwise, check to see if the rest of the elements are consecutively
1436   // numbered from this value.
1437   unsigned ShiftAmt = SVOp->getMaskElt(i);
1438   if (ShiftAmt < i) return -1;
1439
1440   ShiftAmt -= i;
1441   bool isLE = DAG.getDataLayout().isLittleEndian();
1442
1443   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1444     // Check the rest of the elements to see if they are consecutive.
1445     for (++i; i != 16; ++i)
1446       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1447         return -1;
1448   } else if (ShuffleKind == 1) {
1449     // Check the rest of the elements to see if they are consecutive.
1450     for (++i; i != 16; ++i)
1451       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1452         return -1;
1453   } else
1454     return -1;
1455
1456   if (isLE)
1457     ShiftAmt = 16 - ShiftAmt;
1458
1459   return ShiftAmt;
1460 }
1461
1462 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1463 /// specifies a splat of a single element that is suitable for input to
1464 /// VSPLTB/VSPLTH/VSPLTW.
1465 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1466   assert(N->getValueType(0) == MVT::v16i8 &&
1467          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1468
1469   // The consecutive indices need to specify an element, not part of two
1470   // different elements.  So abandon ship early if this isn't the case.
1471   if (N->getMaskElt(0) % EltSize != 0)
1472     return false;
1473
1474   // This is a splat operation if each element of the permute is the same, and
1475   // if the value doesn't reference the second vector.
1476   unsigned ElementBase = N->getMaskElt(0);
1477
1478   // FIXME: Handle UNDEF elements too!
1479   if (ElementBase >= 16)
1480     return false;
1481
1482   // Check that the indices are consecutive, in the case of a multi-byte element
1483   // splatted with a v16i8 mask.
1484   for (unsigned i = 1; i != EltSize; ++i)
1485     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1486       return false;
1487
1488   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1489     if (N->getMaskElt(i) < 0) continue;
1490     for (unsigned j = 0; j != EltSize; ++j)
1491       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1492         return false;
1493   }
1494   return true;
1495 }
1496
1497 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1498 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1499 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1500                                 SelectionDAG &DAG) {
1501   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1502   assert(isSplatShuffleMask(SVOp, EltSize));
1503   if (DAG.getDataLayout().isLittleEndian())
1504     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1505   else
1506     return SVOp->getMaskElt(0) / EltSize;
1507 }
1508
1509 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1510 /// by using a vspltis[bhw] instruction of the specified element size, return
1511 /// the constant being splatted.  The ByteSize field indicates the number of
1512 /// bytes of each element [124] -> [bhw].
1513 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1514   SDValue OpVal(nullptr, 0);
1515
1516   // If ByteSize of the splat is bigger than the element size of the
1517   // build_vector, then we have a case where we are checking for a splat where
1518   // multiple elements of the buildvector are folded together into a single
1519   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1520   unsigned EltSize = 16/N->getNumOperands();
1521   if (EltSize < ByteSize) {
1522     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1523     SDValue UniquedVals[4];
1524     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1525
1526     // See if all of the elements in the buildvector agree across.
1527     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1528       if (N->getOperand(i).isUndef()) continue;
1529       // If the element isn't a constant, bail fully out.
1530       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1531
1532
1533       if (!UniquedVals[i&(Multiple-1)].getNode())
1534         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1535       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1536         return SDValue();  // no match.
1537     }
1538
1539     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1540     // either constant or undef values that are identical for each chunk.  See
1541     // if these chunks can form into a larger vspltis*.
1542
1543     // Check to see if all of the leading entries are either 0 or -1.  If
1544     // neither, then this won't fit into the immediate field.
1545     bool LeadingZero = true;
1546     bool LeadingOnes = true;
1547     for (unsigned i = 0; i != Multiple-1; ++i) {
1548       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1549
1550       LeadingZero &= isNullConstant(UniquedVals[i]);
1551       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1552     }
1553     // Finally, check the least significant entry.
1554     if (LeadingZero) {
1555       if (!UniquedVals[Multiple-1].getNode())
1556         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1557       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1558       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1559         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1560     }
1561     if (LeadingOnes) {
1562       if (!UniquedVals[Multiple-1].getNode())
1563         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1564       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1565       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1566         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1567     }
1568
1569     return SDValue();
1570   }
1571
1572   // Check to see if this buildvec has a single non-undef value in its elements.
1573   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1574     if (N->getOperand(i).isUndef()) continue;
1575     if (!OpVal.getNode())
1576       OpVal = N->getOperand(i);
1577     else if (OpVal != N->getOperand(i))
1578       return SDValue();
1579   }
1580
1581   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1582
1583   unsigned ValSizeInBytes = EltSize;
1584   uint64_t Value = 0;
1585   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1586     Value = CN->getZExtValue();
1587   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1588     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1589     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1590   }
1591
1592   // If the splat value is larger than the element value, then we can never do
1593   // this splat.  The only case that we could fit the replicated bits into our
1594   // immediate field for would be zero, and we prefer to use vxor for it.
1595   if (ValSizeInBytes < ByteSize) return SDValue();
1596
1597   // If the element value is larger than the splat value, check if it consists
1598   // of a repeated bit pattern of size ByteSize.
1599   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1600     return SDValue();
1601
1602   // Properly sign extend the value.
1603   int MaskVal = SignExtend32(Value, ByteSize * 8);
1604
1605   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1606   if (MaskVal == 0) return SDValue();
1607
1608   // Finally, if this value fits in a 5 bit sext field, return it
1609   if (SignExtend32<5>(MaskVal) == MaskVal)
1610     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1611   return SDValue();
1612 }
1613
1614 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1615 /// amount, otherwise return -1.
1616 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1617   EVT VT = N->getValueType(0);
1618   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1619     return -1;
1620
1621   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1622
1623   // Find the first non-undef value in the shuffle mask.
1624   unsigned i;
1625   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1626     /*search*/;
1627
1628   if (i == 4) return -1;  // all undef.
1629
1630   // Otherwise, check to see if the rest of the elements are consecutively
1631   // numbered from this value.
1632   unsigned ShiftAmt = SVOp->getMaskElt(i);
1633   if (ShiftAmt < i) return -1;
1634   ShiftAmt -= i;
1635
1636   // Check the rest of the elements to see if they are consecutive.
1637   for (++i; i != 4; ++i)
1638     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1639       return -1;
1640
1641   return ShiftAmt;
1642 }
1643
1644 //===----------------------------------------------------------------------===//
1645 //  Addressing Mode Selection
1646 //===----------------------------------------------------------------------===//
1647
1648 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1649 /// or 64-bit immediate, and if the value can be accurately represented as a
1650 /// sign extension from a 16-bit value.  If so, this returns true and the
1651 /// immediate.
1652 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1653   if (!isa<ConstantSDNode>(N))
1654     return false;
1655
1656   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1657   if (N->getValueType(0) == MVT::i32)
1658     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1659   else
1660     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1661 }
1662 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1663   return isIntS16Immediate(Op.getNode(), Imm);
1664 }
1665
1666 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1667 /// can be represented as an indexed [r+r] operation.  Returns false if it
1668 /// can be more efficiently represented with [r+imm].
1669 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1670                                             SDValue &Index,
1671                                             SelectionDAG &DAG) const {
1672   short imm = 0;
1673   if (N.getOpcode() == ISD::ADD) {
1674     if (isIntS16Immediate(N.getOperand(1), imm))
1675       return false;    // r+i
1676     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1677       return false;    // r+i
1678
1679     Base = N.getOperand(0);
1680     Index = N.getOperand(1);
1681     return true;
1682   } else if (N.getOpcode() == ISD::OR) {
1683     if (isIntS16Immediate(N.getOperand(1), imm))
1684       return false;    // r+i can fold it if we can.
1685
1686     // If this is an or of disjoint bitfields, we can codegen this as an add
1687     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1688     // disjoint.
1689     APInt LHSKnownZero, LHSKnownOne;
1690     APInt RHSKnownZero, RHSKnownOne;
1691     DAG.computeKnownBits(N.getOperand(0),
1692                          LHSKnownZero, LHSKnownOne);
1693
1694     if (LHSKnownZero.getBoolValue()) {
1695       DAG.computeKnownBits(N.getOperand(1),
1696                            RHSKnownZero, RHSKnownOne);
1697       // If all of the bits are known zero on the LHS or RHS, the add won't
1698       // carry.
1699       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1700         Base = N.getOperand(0);
1701         Index = N.getOperand(1);
1702         return true;
1703       }
1704     }
1705   }
1706
1707   return false;
1708 }
1709
1710 // If we happen to be doing an i64 load or store into a stack slot that has
1711 // less than a 4-byte alignment, then the frame-index elimination may need to
1712 // use an indexed load or store instruction (because the offset may not be a
1713 // multiple of 4). The extra register needed to hold the offset comes from the
1714 // register scavenger, and it is possible that the scavenger will need to use
1715 // an emergency spill slot. As a result, we need to make sure that a spill slot
1716 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1717 // stack slot.
1718 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1719   // FIXME: This does not handle the LWA case.
1720   if (VT != MVT::i64)
1721     return;
1722
1723   // NOTE: We'll exclude negative FIs here, which come from argument
1724   // lowering, because there are no known test cases triggering this problem
1725   // using packed structures (or similar). We can remove this exclusion if
1726   // we find such a test case. The reason why this is so test-case driven is
1727   // because this entire 'fixup' is only to prevent crashes (from the
1728   // register scavenger) on not-really-valid inputs. For example, if we have:
1729   //   %a = alloca i1
1730   //   %b = bitcast i1* %a to i64*
1731   //   store i64* a, i64 b
1732   // then the store should really be marked as 'align 1', but is not. If it
1733   // were marked as 'align 1' then the indexed form would have been
1734   // instruction-selected initially, and the problem this 'fixup' is preventing
1735   // won't happen regardless.
1736   if (FrameIdx < 0)
1737     return;
1738
1739   MachineFunction &MF = DAG.getMachineFunction();
1740   MachineFrameInfo *MFI = MF.getFrameInfo();
1741
1742   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1743   if (Align >= 4)
1744     return;
1745
1746   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1747   FuncInfo->setHasNonRISpills();
1748 }
1749
1750 /// Returns true if the address N can be represented by a base register plus
1751 /// a signed 16-bit displacement [r+imm], and if it is not better
1752 /// represented as reg+reg.  If Aligned is true, only accept displacements
1753 /// suitable for STD and friends, i.e. multiples of 4.
1754 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1755                                             SDValue &Base,
1756                                             SelectionDAG &DAG,
1757                                             bool Aligned) const {
1758   // FIXME dl should come from parent load or store, not from address
1759   SDLoc dl(N);
1760   // If this can be more profitably realized as r+r, fail.
1761   if (SelectAddressRegReg(N, Disp, Base, DAG))
1762     return false;
1763
1764   if (N.getOpcode() == ISD::ADD) {
1765     short imm = 0;
1766     if (isIntS16Immediate(N.getOperand(1), imm) &&
1767         (!Aligned || (imm & 3) == 0)) {
1768       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1769       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1770         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1771         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1772       } else {
1773         Base = N.getOperand(0);
1774       }
1775       return true; // [r+i]
1776     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1777       // Match LOAD (ADD (X, Lo(G))).
1778       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1779              && "Cannot handle constant offsets yet!");
1780       Disp = N.getOperand(1).getOperand(0);  // The global address.
1781       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1782              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1783              Disp.getOpcode() == ISD::TargetConstantPool ||
1784              Disp.getOpcode() == ISD::TargetJumpTable);
1785       Base = N.getOperand(0);
1786       return true;  // [&g+r]
1787     }
1788   } else if (N.getOpcode() == ISD::OR) {
1789     short imm = 0;
1790     if (isIntS16Immediate(N.getOperand(1), imm) &&
1791         (!Aligned || (imm & 3) == 0)) {
1792       // If this is an or of disjoint bitfields, we can codegen this as an add
1793       // (for better address arithmetic) if the LHS and RHS of the OR are
1794       // provably disjoint.
1795       APInt LHSKnownZero, LHSKnownOne;
1796       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1797
1798       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1799         // If all of the bits are known zero on the LHS or RHS, the add won't
1800         // carry.
1801         if (FrameIndexSDNode *FI =
1802               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1803           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1804           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1805         } else {
1806           Base = N.getOperand(0);
1807         }
1808         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1809         return true;
1810       }
1811     }
1812   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1813     // Loading from a constant address.
1814
1815     // If this address fits entirely in a 16-bit sext immediate field, codegen
1816     // this as "d, 0"
1817     short Imm;
1818     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1819       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1820       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1821                              CN->getValueType(0));
1822       return true;
1823     }
1824
1825     // Handle 32-bit sext immediates with LIS + addr mode.
1826     if ((CN->getValueType(0) == MVT::i32 ||
1827          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1828         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1829       int Addr = (int)CN->getZExtValue();
1830
1831       // Otherwise, break this down into an LIS + disp.
1832       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1833
1834       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1835                                    MVT::i32);
1836       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1837       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1838       return true;
1839     }
1840   }
1841
1842   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1843   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1844     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1845     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1846   } else
1847     Base = N;
1848   return true;      // [r+0]
1849 }
1850
1851 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1852 /// represented as an indexed [r+r] operation.
1853 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1854                                                 SDValue &Index,
1855                                                 SelectionDAG &DAG) const {
1856   // Check to see if we can easily represent this as an [r+r] address.  This
1857   // will fail if it thinks that the address is more profitably represented as
1858   // reg+imm, e.g. where imm = 0.
1859   if (SelectAddressRegReg(N, Base, Index, DAG))
1860     return true;
1861
1862   // If the operand is an addition, always emit this as [r+r], since this is
1863   // better (for code size, and execution, as the memop does the add for free)
1864   // than emitting an explicit add.
1865   if (N.getOpcode() == ISD::ADD) {
1866     Base = N.getOperand(0);
1867     Index = N.getOperand(1);
1868     return true;
1869   }
1870
1871   // Otherwise, do it the hard way, using R0 as the base register.
1872   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1873                          N.getValueType());
1874   Index = N;
1875   return true;
1876 }
1877
1878 /// getPreIndexedAddressParts - returns true by value, base pointer and
1879 /// offset pointer and addressing mode by reference if the node's address
1880 /// can be legally represented as pre-indexed load / store address.
1881 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1882                                                   SDValue &Offset,
1883                                                   ISD::MemIndexedMode &AM,
1884                                                   SelectionDAG &DAG) const {
1885   if (DisablePPCPreinc) return false;
1886
1887   bool isLoad = true;
1888   SDValue Ptr;
1889   EVT VT;
1890   unsigned Alignment;
1891   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1892     Ptr = LD->getBasePtr();
1893     VT = LD->getMemoryVT();
1894     Alignment = LD->getAlignment();
1895   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1896     Ptr = ST->getBasePtr();
1897     VT  = ST->getMemoryVT();
1898     Alignment = ST->getAlignment();
1899     isLoad = false;
1900   } else
1901     return false;
1902
1903   // PowerPC doesn't have preinc load/store instructions for vectors (except
1904   // for QPX, which does have preinc r+r forms).
1905   if (VT.isVector()) {
1906     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1907       return false;
1908     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1909       AM = ISD::PRE_INC;
1910       return true;
1911     }
1912   }
1913
1914   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1915
1916     // Common code will reject creating a pre-inc form if the base pointer
1917     // is a frame index, or if N is a store and the base pointer is either
1918     // the same as or a predecessor of the value being stored.  Check for
1919     // those situations here, and try with swapped Base/Offset instead.
1920     bool Swap = false;
1921
1922     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1923       Swap = true;
1924     else if (!isLoad) {
1925       SDValue Val = cast<StoreSDNode>(N)->getValue();
1926       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1927         Swap = true;
1928     }
1929
1930     if (Swap)
1931       std::swap(Base, Offset);
1932
1933     AM = ISD::PRE_INC;
1934     return true;
1935   }
1936
1937   // LDU/STU can only handle immediates that are a multiple of 4.
1938   if (VT != MVT::i64) {
1939     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1940       return false;
1941   } else {
1942     // LDU/STU need an address with at least 4-byte alignment.
1943     if (Alignment < 4)
1944       return false;
1945
1946     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1947       return false;
1948   }
1949
1950   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1951     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1952     // sext i32 to i64 when addr mode is r+i.
1953     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1954         LD->getExtensionType() == ISD::SEXTLOAD &&
1955         isa<ConstantSDNode>(Offset))
1956       return false;
1957   }
1958
1959   AM = ISD::PRE_INC;
1960   return true;
1961 }
1962
1963 //===----------------------------------------------------------------------===//
1964 //  LowerOperation implementation
1965 //===----------------------------------------------------------------------===//
1966
1967 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
1968 /// and LoOpFlags to the target MO flags.
1969 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
1970                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1971                                const GlobalValue *GV = nullptr) {
1972   HiOpFlags = PPCII::MO_HA;
1973   LoOpFlags = PPCII::MO_LO;
1974
1975   // Don't use the pic base if not in PIC relocation model.
1976   if (IsPIC) {
1977     HiOpFlags |= PPCII::MO_PIC_FLAG;
1978     LoOpFlags |= PPCII::MO_PIC_FLAG;
1979   }
1980
1981   // If this is a reference to a global value that requires a non-lazy-ptr, make
1982   // sure that instruction lowering adds it.
1983   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1984     HiOpFlags |= PPCII::MO_NLP_FLAG;
1985     LoOpFlags |= PPCII::MO_NLP_FLAG;
1986
1987     if (GV->hasHiddenVisibility()) {
1988       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1989       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1990     }
1991   }
1992 }
1993
1994 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1995                              SelectionDAG &DAG) {
1996   SDLoc DL(HiPart);
1997   EVT PtrVT = HiPart.getValueType();
1998   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1999
2000   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2001   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2002
2003   // With PIC, the first instruction is actually "GR+hi(&G)".
2004   if (isPIC)
2005     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2006                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2007
2008   // Generate non-pic code that has direct accesses to the constant pool.
2009   // The address of the global is just (hi(&g)+lo(&g)).
2010   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2011 }
2012
2013 static void setUsesTOCBasePtr(MachineFunction &MF) {
2014   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2015   FuncInfo->setUsesTOCBasePtr();
2016 }
2017
2018 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2019   setUsesTOCBasePtr(DAG.getMachineFunction());
2020 }
2021
2022 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2023                            SDValue GA) {
2024   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2025   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2026                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2027
2028   SDValue Ops[] = { GA, Reg };
2029   return DAG.getMemIntrinsicNode(
2030       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2031       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2032       false, 0);
2033 }
2034
2035 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2036                                              SelectionDAG &DAG) const {
2037   EVT PtrVT = Op.getValueType();
2038   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2039   const Constant *C = CP->getConstVal();
2040
2041   // 64-bit SVR4 ABI code is always position-independent.
2042   // The actual address of the GlobalValue is stored in the TOC.
2043   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2044     setUsesTOCBasePtr(DAG);
2045     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2046     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2047   }
2048
2049   unsigned MOHiFlag, MOLoFlag;
2050   bool IsPIC = isPositionIndependent();
2051   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2052
2053   if (IsPIC && Subtarget.isSVR4ABI()) {
2054     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2055                                            PPCII::MO_PIC_FLAG);
2056     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2057   }
2058
2059   SDValue CPIHi =
2060     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2061   SDValue CPILo =
2062     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2063   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2064 }
2065
2066 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2067   EVT PtrVT = Op.getValueType();
2068   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2069
2070   // 64-bit SVR4 ABI code is always position-independent.
2071   // The actual address of the GlobalValue is stored in the TOC.
2072   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2073     setUsesTOCBasePtr(DAG);
2074     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2075     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2076   }
2077
2078   unsigned MOHiFlag, MOLoFlag;
2079   bool IsPIC = isPositionIndependent();
2080   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2081
2082   if (IsPIC && Subtarget.isSVR4ABI()) {
2083     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2084                                         PPCII::MO_PIC_FLAG);
2085     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2086   }
2087
2088   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2089   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2090   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2091 }
2092
2093 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2094                                              SelectionDAG &DAG) const {
2095   EVT PtrVT = Op.getValueType();
2096   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2097   const BlockAddress *BA = BASDN->getBlockAddress();
2098
2099   // 64-bit SVR4 ABI code is always position-independent.
2100   // The actual BlockAddress is stored in the TOC.
2101   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2102     setUsesTOCBasePtr(DAG);
2103     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2104     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2105   }
2106
2107   unsigned MOHiFlag, MOLoFlag;
2108   bool IsPIC = isPositionIndependent();
2109   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2110   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2111   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2112   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2113 }
2114
2115 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2116                                               SelectionDAG &DAG) const {
2117
2118   // FIXME: TLS addresses currently use medium model code sequences,
2119   // which is the most useful form.  Eventually support for small and
2120   // large models could be added if users need it, at the cost of
2121   // additional complexity.
2122   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2123   if (DAG.getTarget().Options.EmulatedTLS)
2124     return LowerToTLSEmulatedModel(GA, DAG);
2125
2126   SDLoc dl(GA);
2127   const GlobalValue *GV = GA->getGlobal();
2128   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2129   bool is64bit = Subtarget.isPPC64();
2130   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2131   PICLevel::Level picLevel = M->getPICLevel();
2132
2133   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2134
2135   if (Model == TLSModel::LocalExec) {
2136     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2137                                                PPCII::MO_TPREL_HA);
2138     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2139                                                PPCII::MO_TPREL_LO);
2140     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2141                                      is64bit ? MVT::i64 : MVT::i32);
2142     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2143     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2144   }
2145
2146   if (Model == TLSModel::InitialExec) {
2147     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2148     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2149                                                 PPCII::MO_TLS);
2150     SDValue GOTPtr;
2151     if (is64bit) {
2152       setUsesTOCBasePtr(DAG);
2153       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2154       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2155                            PtrVT, GOTReg, TGA);
2156     } else
2157       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2158     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2159                                    PtrVT, TGA, GOTPtr);
2160     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2161   }
2162
2163   if (Model == TLSModel::GeneralDynamic) {
2164     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2165     SDValue GOTPtr;
2166     if (is64bit) {
2167       setUsesTOCBasePtr(DAG);
2168       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2169       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2170                                    GOTReg, TGA);
2171     } else {
2172       if (picLevel == PICLevel::SmallPIC)
2173         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2174       else
2175         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2176     }
2177     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2178                        GOTPtr, TGA, TGA);
2179   }
2180
2181   if (Model == TLSModel::LocalDynamic) {
2182     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2183     SDValue GOTPtr;
2184     if (is64bit) {
2185       setUsesTOCBasePtr(DAG);
2186       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2187       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2188                            GOTReg, TGA);
2189     } else {
2190       if (picLevel == PICLevel::SmallPIC)
2191         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2192       else
2193         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2194     }
2195     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2196                                   PtrVT, GOTPtr, TGA, TGA);
2197     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2198                                       PtrVT, TLSAddr, TGA);
2199     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2200   }
2201
2202   llvm_unreachable("Unknown TLS model!");
2203 }
2204
2205 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2206                                               SelectionDAG &DAG) const {
2207   EVT PtrVT = Op.getValueType();
2208   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2209   SDLoc DL(GSDN);
2210   const GlobalValue *GV = GSDN->getGlobal();
2211
2212   // 64-bit SVR4 ABI code is always position-independent.
2213   // The actual address of the GlobalValue is stored in the TOC.
2214   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2215     setUsesTOCBasePtr(DAG);
2216     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2217     return getTOCEntry(DAG, DL, true, GA);
2218   }
2219
2220   unsigned MOHiFlag, MOLoFlag;
2221   bool IsPIC = isPositionIndependent();
2222   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2223
2224   if (IsPIC && Subtarget.isSVR4ABI()) {
2225     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2226                                             GSDN->getOffset(),
2227                                             PPCII::MO_PIC_FLAG);
2228     return getTOCEntry(DAG, DL, false, GA);
2229   }
2230
2231   SDValue GAHi =
2232     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2233   SDValue GALo =
2234     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2235
2236   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2237
2238   // If the global reference is actually to a non-lazy-pointer, we have to do an
2239   // extra load to get the address of the global.
2240   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2241     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2242                       false, false, false, 0);
2243   return Ptr;
2244 }
2245
2246 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2247   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2248   SDLoc dl(Op);
2249
2250   if (Op.getValueType() == MVT::v2i64) {
2251     // When the operands themselves are v2i64 values, we need to do something
2252     // special because VSX has no underlying comparison operations for these.
2253     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2254       // Equality can be handled by casting to the legal type for Altivec
2255       // comparisons, everything else needs to be expanded.
2256       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2257         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2258                  DAG.getSetCC(dl, MVT::v4i32,
2259                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2260                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2261                    CC));
2262       }
2263
2264       return SDValue();
2265     }
2266
2267     // We handle most of these in the usual way.
2268     return Op;
2269   }
2270
2271   // If we're comparing for equality to zero, expose the fact that this is
2272   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2273   // fold the new nodes.
2274   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2275     if (C->isNullValue() && CC == ISD::SETEQ) {
2276       EVT VT = Op.getOperand(0).getValueType();
2277       SDValue Zext = Op.getOperand(0);
2278       if (VT.bitsLT(MVT::i32)) {
2279         VT = MVT::i32;
2280         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2281       }
2282       unsigned Log2b = Log2_32(VT.getSizeInBits());
2283       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2284       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2285                                 DAG.getConstant(Log2b, dl, MVT::i32));
2286       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2287     }
2288     // Leave comparisons against 0 and -1 alone for now, since they're usually
2289     // optimized.  FIXME: revisit this when we can custom lower all setcc
2290     // optimizations.
2291     if (C->isAllOnesValue() || C->isNullValue())
2292       return SDValue();
2293   }
2294
2295   // If we have an integer seteq/setne, turn it into a compare against zero
2296   // by xor'ing the rhs with the lhs, which is faster than setting a
2297   // condition register, reading it back out, and masking the correct bit.  The
2298   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2299   // the result to other bit-twiddling opportunities.
2300   EVT LHSVT = Op.getOperand(0).getValueType();
2301   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2302     EVT VT = Op.getValueType();
2303     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2304                                 Op.getOperand(1));
2305     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2306   }
2307   return SDValue();
2308 }
2309
2310 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2311   SDNode *Node = Op.getNode();
2312   EVT VT = Node->getValueType(0);
2313   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2314   SDValue InChain = Node->getOperand(0);
2315   SDValue VAListPtr = Node->getOperand(1);
2316   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2317   SDLoc dl(Node);
2318
2319   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2320
2321   // gpr_index
2322   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2323                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2324                                     false, false, false, 0);
2325   InChain = GprIndex.getValue(1);
2326
2327   if (VT == MVT::i64) {
2328     // Check if GprIndex is even
2329     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2330                                  DAG.getConstant(1, dl, MVT::i32));
2331     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2332                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2333     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2334                                           DAG.getConstant(1, dl, MVT::i32));
2335     // Align GprIndex to be even if it isn't
2336     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2337                            GprIndex);
2338   }
2339
2340   // fpr index is 1 byte after gpr
2341   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2342                                DAG.getConstant(1, dl, MVT::i32));
2343
2344   // fpr
2345   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2346                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2347                                     false, false, false, 0);
2348   InChain = FprIndex.getValue(1);
2349
2350   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2351                                        DAG.getConstant(8, dl, MVT::i32));
2352
2353   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2354                                         DAG.getConstant(4, dl, MVT::i32));
2355
2356   // areas
2357   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2358                                      MachinePointerInfo(), false, false,
2359                                      false, 0);
2360   InChain = OverflowArea.getValue(1);
2361
2362   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2363                                     MachinePointerInfo(), false, false,
2364                                     false, 0);
2365   InChain = RegSaveArea.getValue(1);
2366
2367   // select overflow_area if index > 8
2368   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2369                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2370
2371   // adjustment constant gpr_index * 4/8
2372   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2373                                     VT.isInteger() ? GprIndex : FprIndex,
2374                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2375                                                     MVT::i32));
2376
2377   // OurReg = RegSaveArea + RegConstant
2378   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2379                                RegConstant);
2380
2381   // Floating types are 32 bytes into RegSaveArea
2382   if (VT.isFloatingPoint())
2383     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2384                          DAG.getConstant(32, dl, MVT::i32));
2385
2386   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2387   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2388                                    VT.isInteger() ? GprIndex : FprIndex,
2389                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2390                                                    MVT::i32));
2391
2392   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2393                               VT.isInteger() ? VAListPtr : FprPtr,
2394                               MachinePointerInfo(SV),
2395                               MVT::i8, false, false, 0);
2396
2397   // determine if we should load from reg_save_area or overflow_area
2398   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2399
2400   // increase overflow_area by 4/8 if gpr/fpr > 8
2401   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2402                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2403                                           dl, MVT::i32));
2404
2405   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2406                              OverflowAreaPlusN);
2407
2408   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2409                               OverflowAreaPtr,
2410                               MachinePointerInfo(),
2411                               MVT::i32, false, false, 0);
2412
2413   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2414                      false, false, false, 0);
2415 }
2416
2417 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2418   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2419
2420   // We have to copy the entire va_list struct:
2421   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2422   return DAG.getMemcpy(Op.getOperand(0), Op,
2423                        Op.getOperand(1), Op.getOperand(2),
2424                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2425                        false, MachinePointerInfo(), MachinePointerInfo());
2426 }
2427
2428 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2429                                                   SelectionDAG &DAG) const {
2430   return Op.getOperand(0);
2431 }
2432
2433 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2434                                                 SelectionDAG &DAG) const {
2435   SDValue Chain = Op.getOperand(0);
2436   SDValue Trmp = Op.getOperand(1); // trampoline
2437   SDValue FPtr = Op.getOperand(2); // nested function
2438   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2439   SDLoc dl(Op);
2440
2441   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2442   bool isPPC64 = (PtrVT == MVT::i64);
2443   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2444
2445   TargetLowering::ArgListTy Args;
2446   TargetLowering::ArgListEntry Entry;
2447
2448   Entry.Ty = IntPtrTy;
2449   Entry.Node = Trmp; Args.push_back(Entry);
2450
2451   // TrampSize == (isPPC64 ? 48 : 40);
2452   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2453                                isPPC64 ? MVT::i64 : MVT::i32);
2454   Args.push_back(Entry);
2455
2456   Entry.Node = FPtr; Args.push_back(Entry);
2457   Entry.Node = Nest; Args.push_back(Entry);
2458
2459   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2460   TargetLowering::CallLoweringInfo CLI(DAG);
2461   CLI.setDebugLoc(dl).setChain(Chain)
2462     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2463                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2464                std::move(Args));
2465
2466   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2467   return CallResult.second;
2468 }
2469
2470 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2471   MachineFunction &MF = DAG.getMachineFunction();
2472   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2473
2474   SDLoc dl(Op);
2475
2476   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2477     // vastart just stores the address of the VarArgsFrameIndex slot into the
2478     // memory location argument.
2479     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2480     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2481     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2482     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2483                         MachinePointerInfo(SV),
2484                         false, false, 0);
2485   }
2486
2487   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2488   // We suppose the given va_list is already allocated.
2489   //
2490   // typedef struct {
2491   //  char gpr;     /* index into the array of 8 GPRs
2492   //                 * stored in the register save area
2493   //                 * gpr=0 corresponds to r3,
2494   //                 * gpr=1 to r4, etc.
2495   //                 */
2496   //  char fpr;     /* index into the array of 8 FPRs
2497   //                 * stored in the register save area
2498   //                 * fpr=0 corresponds to f1,
2499   //                 * fpr=1 to f2, etc.
2500   //                 */
2501   //  char *overflow_arg_area;
2502   //                /* location on stack that holds
2503   //                 * the next overflow argument
2504   //                 */
2505   //  char *reg_save_area;
2506   //               /* where r3:r10 and f1:f8 (if saved)
2507   //                * are stored
2508   //                */
2509   // } va_list[1];
2510
2511   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2512   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2513
2514   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2515
2516   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2517                                             PtrVT);
2518   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2519                                  PtrVT);
2520
2521   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2522   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2523
2524   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2525   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2526
2527   uint64_t FPROffset = 1;
2528   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2529
2530   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2531
2532   // Store first byte : number of int regs
2533   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2534                                          Op.getOperand(1),
2535                                          MachinePointerInfo(SV),
2536                                          MVT::i8, false, false, 0);
2537   uint64_t nextOffset = FPROffset;
2538   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2539                                   ConstFPROffset);
2540
2541   // Store second byte : number of float regs
2542   SDValue secondStore =
2543     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2544                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2545                       false, false, 0);
2546   nextOffset += StackOffset;
2547   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2548
2549   // Store second word : arguments given on stack
2550   SDValue thirdStore =
2551     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2552                  MachinePointerInfo(SV, nextOffset),
2553                  false, false, 0);
2554   nextOffset += FrameOffset;
2555   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2556
2557   // Store third word : arguments given in registers
2558   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2559                       MachinePointerInfo(SV, nextOffset),
2560                       false, false, 0);
2561
2562 }
2563
2564 #include "PPCGenCallingConv.inc"
2565
2566 // Function whose sole purpose is to kill compiler warnings
2567 // stemming from unused functions included from PPCGenCallingConv.inc.
2568 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2569   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2570 }
2571
2572 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2573                                       CCValAssign::LocInfo &LocInfo,
2574                                       ISD::ArgFlagsTy &ArgFlags,
2575                                       CCState &State) {
2576   return true;
2577 }
2578
2579 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2580                                              MVT &LocVT,
2581                                              CCValAssign::LocInfo &LocInfo,
2582                                              ISD::ArgFlagsTy &ArgFlags,
2583                                              CCState &State) {
2584   static const MCPhysReg ArgRegs[] = {
2585     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2586     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2587   };
2588   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2589
2590   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2591
2592   // Skip one register if the first unallocated register has an even register
2593   // number and there are still argument registers available which have not been
2594   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2595   // need to skip a register if RegNum is odd.
2596   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2597     State.AllocateReg(ArgRegs[RegNum]);
2598   }
2599
2600   // Always return false here, as this function only makes sure that the first
2601   // unallocated register has an odd register number and does not actually
2602   // allocate a register for the current argument.
2603   return false;
2604 }
2605
2606 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2607                                                MVT &LocVT,
2608                                                CCValAssign::LocInfo &LocInfo,
2609                                                ISD::ArgFlagsTy &ArgFlags,
2610                                                CCState &State) {
2611   static const MCPhysReg ArgRegs[] = {
2612     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2613     PPC::F8
2614   };
2615
2616   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2617
2618   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2619
2620   // If there is only one Floating-point register left we need to put both f64
2621   // values of a split ppc_fp128 value on the stack.
2622   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2623     State.AllocateReg(ArgRegs[RegNum]);
2624   }
2625
2626   // Always return false here, as this function only makes sure that the two f64
2627   // values a ppc_fp128 value is split into are both passed in registers or both
2628   // passed on the stack and does not actually allocate a register for the
2629   // current argument.
2630   return false;
2631 }
2632
2633 /// FPR - The set of FP registers that should be allocated for arguments,
2634 /// on Darwin.
2635 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2636                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2637                                 PPC::F11, PPC::F12, PPC::F13};
2638
2639 /// QFPR - The set of QPX registers that should be allocated for arguments.
2640 static const MCPhysReg QFPR[] = {
2641     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2642     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2643
2644 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2645 /// the stack.
2646 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2647                                        unsigned PtrByteSize) {
2648   unsigned ArgSize = ArgVT.getStoreSize();
2649   if (Flags.isByVal())
2650     ArgSize = Flags.getByValSize();
2651
2652   // Round up to multiples of the pointer size, except for array members,
2653   // which are always packed.
2654   if (!Flags.isInConsecutiveRegs())
2655     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2656
2657   return ArgSize;
2658 }
2659
2660 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2661 /// on the stack.
2662 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2663                                             ISD::ArgFlagsTy Flags,
2664                                             unsigned PtrByteSize) {
2665   unsigned Align = PtrByteSize;
2666
2667   // Altivec parameters are padded to a 16 byte boundary.
2668   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2669       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2670       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2671       ArgVT == MVT::v1i128)
2672     Align = 16;
2673   // QPX vector types stored in double-precision are padded to a 32 byte
2674   // boundary.
2675   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2676     Align = 32;
2677
2678   // ByVal parameters are aligned as requested.
2679   if (Flags.isByVal()) {
2680     unsigned BVAlign = Flags.getByValAlign();
2681     if (BVAlign > PtrByteSize) {
2682       if (BVAlign % PtrByteSize != 0)
2683           llvm_unreachable(
2684             "ByVal alignment is not a multiple of the pointer size");
2685
2686       Align = BVAlign;
2687     }
2688   }
2689
2690   // Array members are always packed to their original alignment.
2691   if (Flags.isInConsecutiveRegs()) {
2692     // If the array member was split into multiple registers, the first
2693     // needs to be aligned to the size of the full type.  (Except for
2694     // ppcf128, which is only aligned as its f64 components.)
2695     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2696       Align = OrigVT.getStoreSize();
2697     else
2698       Align = ArgVT.getStoreSize();
2699   }
2700
2701   return Align;
2702 }
2703
2704 /// CalculateStackSlotUsed - Return whether this argument will use its
2705 /// stack slot (instead of being passed in registers).  ArgOffset,
2706 /// AvailableFPRs, and AvailableVRs must hold the current argument
2707 /// position, and will be updated to account for this argument.
2708 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2709                                    ISD::ArgFlagsTy Flags,
2710                                    unsigned PtrByteSize,
2711                                    unsigned LinkageSize,
2712                                    unsigned ParamAreaSize,
2713                                    unsigned &ArgOffset,
2714                                    unsigned &AvailableFPRs,
2715                                    unsigned &AvailableVRs, bool HasQPX) {
2716   bool UseMemory = false;
2717
2718   // Respect alignment of argument on the stack.
2719   unsigned Align =
2720     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2721   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2722   // If there's no space left in the argument save area, we must
2723   // use memory (this check also catches zero-sized arguments).
2724   if (ArgOffset >= LinkageSize + ParamAreaSize)
2725     UseMemory = true;
2726
2727   // Allocate argument on the stack.
2728   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2729   if (Flags.isInConsecutiveRegsLast())
2730     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2731   // If we overran the argument save area, we must use memory
2732   // (this check catches arguments passed partially in memory)
2733   if (ArgOffset > LinkageSize + ParamAreaSize)
2734     UseMemory = true;
2735
2736   // However, if the argument is actually passed in an FPR or a VR,
2737   // we don't use memory after all.
2738   if (!Flags.isByVal()) {
2739     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2740         // QPX registers overlap with the scalar FP registers.
2741         (HasQPX && (ArgVT == MVT::v4f32 ||
2742                     ArgVT == MVT::v4f64 ||
2743                     ArgVT == MVT::v4i1)))
2744       if (AvailableFPRs > 0) {
2745         --AvailableFPRs;
2746         return false;
2747       }
2748     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2749         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2750         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2751         ArgVT == MVT::v1i128)
2752       if (AvailableVRs > 0) {
2753         --AvailableVRs;
2754         return false;
2755       }
2756   }
2757
2758   return UseMemory;
2759 }
2760
2761 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2762 /// ensure minimum alignment required for target.
2763 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2764                                      unsigned NumBytes) {
2765   unsigned TargetAlign = Lowering->getStackAlignment();
2766   unsigned AlignMask = TargetAlign - 1;
2767   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2768   return NumBytes;
2769 }
2770
2771 SDValue PPCTargetLowering::LowerFormalArguments(
2772     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2773     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2774     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2775   if (Subtarget.isSVR4ABI()) {
2776     if (Subtarget.isPPC64())
2777       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2778                                          dl, DAG, InVals);
2779     else
2780       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2781                                          dl, DAG, InVals);
2782   } else {
2783     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2784                                        dl, DAG, InVals);
2785   }
2786 }
2787
2788 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2789     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2790     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2791     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2792
2793   // 32-bit SVR4 ABI Stack Frame Layout:
2794   //              +-----------------------------------+
2795   //        +-->  |            Back chain             |
2796   //        |     +-----------------------------------+
2797   //        |     | Floating-point register save area |
2798   //        |     +-----------------------------------+
2799   //        |     |    General register save area     |
2800   //        |     +-----------------------------------+
2801   //        |     |          CR save word             |
2802   //        |     +-----------------------------------+
2803   //        |     |         VRSAVE save word          |
2804   //        |     +-----------------------------------+
2805   //        |     |         Alignment padding         |
2806   //        |     +-----------------------------------+
2807   //        |     |     Vector register save area     |
2808   //        |     +-----------------------------------+
2809   //        |     |       Local variable space        |
2810   //        |     +-----------------------------------+
2811   //        |     |        Parameter list area        |
2812   //        |     +-----------------------------------+
2813   //        |     |           LR save word            |
2814   //        |     +-----------------------------------+
2815   // SP-->  +---  |            Back chain             |
2816   //              +-----------------------------------+
2817   //
2818   // Specifications:
2819   //   System V Application Binary Interface PowerPC Processor Supplement
2820   //   AltiVec Technology Programming Interface Manual
2821
2822   MachineFunction &MF = DAG.getMachineFunction();
2823   MachineFrameInfo *MFI = MF.getFrameInfo();
2824   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2825
2826   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2827   // Potential tail calls could cause overwriting of argument stack slots.
2828   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2829                        (CallConv == CallingConv::Fast));
2830   unsigned PtrByteSize = 4;
2831
2832   // Assign locations to all of the incoming arguments.
2833   SmallVector<CCValAssign, 16> ArgLocs;
2834   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2835                  *DAG.getContext());
2836
2837   // Reserve space for the linkage area on the stack.
2838   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2839   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2840   if (Subtarget.useSoftFloat())
2841     CCInfo.PreAnalyzeFormalArguments(Ins);
2842
2843   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2844   CCInfo.clearWasPPCF128();
2845
2846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847     CCValAssign &VA = ArgLocs[i];
2848
2849     // Arguments stored in registers.
2850     if (VA.isRegLoc()) {
2851       const TargetRegisterClass *RC;
2852       EVT ValVT = VA.getValVT();
2853
2854       switch (ValVT.getSimpleVT().SimpleTy) {
2855         default:
2856           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2857         case MVT::i1:
2858         case MVT::i32:
2859           RC = &PPC::GPRCRegClass;
2860           break;
2861         case MVT::f32:
2862           if (Subtarget.hasP8Vector())
2863             RC = &PPC::VSSRCRegClass;
2864           else
2865             RC = &PPC::F4RCRegClass;
2866           break;
2867         case MVT::f64:
2868           if (Subtarget.hasVSX())
2869             RC = &PPC::VSFRCRegClass;
2870           else
2871             RC = &PPC::F8RCRegClass;
2872           break;
2873         case MVT::v16i8:
2874         case MVT::v8i16:
2875         case MVT::v4i32:
2876           RC = &PPC::VRRCRegClass;
2877           break;
2878         case MVT::v4f32:
2879           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2880           break;
2881         case MVT::v2f64:
2882         case MVT::v2i64:
2883           RC = &PPC::VSHRCRegClass;
2884           break;
2885         case MVT::v4f64:
2886           RC = &PPC::QFRCRegClass;
2887           break;
2888         case MVT::v4i1:
2889           RC = &PPC::QBRCRegClass;
2890           break;
2891       }
2892
2893       // Transform the arguments stored in physical registers into virtual ones.
2894       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2895       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2896                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2897
2898       if (ValVT == MVT::i1)
2899         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2900
2901       InVals.push_back(ArgValue);
2902     } else {
2903       // Argument stored in memory.
2904       assert(VA.isMemLoc());
2905
2906       unsigned ArgSize = VA.getLocVT().getStoreSize();
2907       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2908                                       isImmutable);
2909
2910       // Create load nodes to retrieve arguments from the stack.
2911       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2912       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2913                                    MachinePointerInfo(),
2914                                    false, false, false, 0));
2915     }
2916   }
2917
2918   // Assign locations to all of the incoming aggregate by value arguments.
2919   // Aggregates passed by value are stored in the local variable space of the
2920   // caller's stack frame, right above the parameter list area.
2921   SmallVector<CCValAssign, 16> ByValArgLocs;
2922   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2923                       ByValArgLocs, *DAG.getContext());
2924
2925   // Reserve stack space for the allocations in CCInfo.
2926   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2927
2928   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2929
2930   // Area that is at least reserved in the caller of this function.
2931   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2932   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2933
2934   // Set the size that is at least reserved in caller of this function.  Tail
2935   // call optimized function's reserved stack space needs to be aligned so that
2936   // taking the difference between two stack areas will result in an aligned
2937   // stack.
2938   MinReservedArea =
2939       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2940   FuncInfo->setMinReservedArea(MinReservedArea);
2941
2942   SmallVector<SDValue, 8> MemOps;
2943
2944   // If the function takes variable number of arguments, make a frame index for
2945   // the start of the first vararg value... for expansion of llvm.va_start.
2946   if (isVarArg) {
2947     static const MCPhysReg GPArgRegs[] = {
2948       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2949       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2950     };
2951     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2952
2953     static const MCPhysReg FPArgRegs[] = {
2954       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2955       PPC::F8
2956     };
2957     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2958
2959     if (Subtarget.useSoftFloat())
2960        NumFPArgRegs = 0;
2961
2962     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2963     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2964
2965     // Make room for NumGPArgRegs and NumFPArgRegs.
2966     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2967                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2968
2969     FuncInfo->setVarArgsStackOffset(
2970       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2971                              CCInfo.getNextStackOffset(), true));
2972
2973     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2974     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2975
2976     // The fixed integer arguments of a variadic function are stored to the
2977     // VarArgsFrameIndex on the stack so that they may be loaded by
2978     // dereferencing the result of va_next.
2979     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2980       // Get an existing live-in vreg, or add a new one.
2981       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2982       if (!VReg)
2983         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2984
2985       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2986       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2987                                    MachinePointerInfo(), false, false, 0);
2988       MemOps.push_back(Store);
2989       // Increment the address by four for the next argument to store
2990       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2991       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2992     }
2993
2994     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2995     // is set.
2996     // The double arguments are stored to the VarArgsFrameIndex
2997     // on the stack.
2998     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2999       // Get an existing live-in vreg, or add a new one.
3000       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3001       if (!VReg)
3002         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3003
3004       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3005       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3006                                    MachinePointerInfo(), false, false, 0);
3007       MemOps.push_back(Store);
3008       // Increment the address by eight for the next argument to store
3009       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3010                                          PtrVT);
3011       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3012     }
3013   }
3014
3015   if (!MemOps.empty())
3016     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3017
3018   return Chain;
3019 }
3020
3021 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3022 // value to MVT::i64 and then truncate to the correct register size.
3023 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3024                                              EVT ObjectVT, SelectionDAG &DAG,
3025                                              SDValue ArgVal,
3026                                              const SDLoc &dl) const {
3027   if (Flags.isSExt())
3028     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3029                          DAG.getValueType(ObjectVT));
3030   else if (Flags.isZExt())
3031     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3032                          DAG.getValueType(ObjectVT));
3033
3034   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3035 }
3036
3037 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3038     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3039     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3040     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3041   // TODO: add description of PPC stack frame format, or at least some docs.
3042   //
3043   bool isELFv2ABI = Subtarget.isELFv2ABI();
3044   bool isLittleEndian = Subtarget.isLittleEndian();
3045   MachineFunction &MF = DAG.getMachineFunction();
3046   MachineFrameInfo *MFI = MF.getFrameInfo();
3047   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3048
3049   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3050          "fastcc not supported on varargs functions");
3051
3052   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3053   // Potential tail calls could cause overwriting of argument stack slots.
3054   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3055                        (CallConv == CallingConv::Fast));
3056   unsigned PtrByteSize = 8;
3057   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3058
3059   static const MCPhysReg GPR[] = {
3060     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3061     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3062   };
3063   static const MCPhysReg VR[] = {
3064     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3065     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3066   };
3067   static const MCPhysReg VSRH[] = {
3068     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3069     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3070   };
3071
3072   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3073   const unsigned Num_FPR_Regs = 13;
3074   const unsigned Num_VR_Regs  = array_lengthof(VR);
3075   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3076
3077   // Do a first pass over the arguments to determine whether the ABI
3078   // guarantees that our caller has allocated the parameter save area
3079   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3080   // in the ELFv2 ABI, it is true if this is a vararg function or if
3081   // any parameter is located in a stack slot.
3082
3083   bool HasParameterArea = !isELFv2ABI || isVarArg;
3084   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3085   unsigned NumBytes = LinkageSize;
3086   unsigned AvailableFPRs = Num_FPR_Regs;
3087   unsigned AvailableVRs = Num_VR_Regs;
3088   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3089     if (Ins[i].Flags.isNest())
3090       continue;
3091
3092     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3093                                PtrByteSize, LinkageSize, ParamAreaSize,
3094                                NumBytes, AvailableFPRs, AvailableVRs,
3095                                Subtarget.hasQPX()))
3096       HasParameterArea = true;
3097   }
3098
3099   // Add DAG nodes to load the arguments or copy them out of registers.  On
3100   // entry to a function on PPC, the arguments start after the linkage area,
3101   // although the first ones are often in registers.
3102
3103   unsigned ArgOffset = LinkageSize;
3104   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3105   unsigned &QFPR_idx = FPR_idx;
3106   SmallVector<SDValue, 8> MemOps;
3107   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3108   unsigned CurArgIdx = 0;
3109   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3110     SDValue ArgVal;
3111     bool needsLoad = false;
3112     EVT ObjectVT = Ins[ArgNo].VT;
3113     EVT OrigVT = Ins[ArgNo].ArgVT;
3114     unsigned ObjSize = ObjectVT.getStoreSize();
3115     unsigned ArgSize = ObjSize;
3116     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3117     if (Ins[ArgNo].isOrigArg()) {
3118       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3119       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3120     }
3121     // We re-align the argument offset for each argument, except when using the
3122     // fast calling convention, when we need to make sure we do that only when
3123     // we'll actually use a stack slot.
3124     unsigned CurArgOffset, Align;
3125     auto ComputeArgOffset = [&]() {
3126       /* Respect alignment of argument on the stack.  */
3127       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3128       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3129       CurArgOffset = ArgOffset;
3130     };
3131
3132     if (CallConv != CallingConv::Fast) {
3133       ComputeArgOffset();
3134
3135       /* Compute GPR index associated with argument offset.  */
3136       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3137       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3138     }
3139
3140     // FIXME the codegen can be much improved in some cases.
3141     // We do not have to keep everything in memory.
3142     if (Flags.isByVal()) {
3143       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3144
3145       if (CallConv == CallingConv::Fast)
3146         ComputeArgOffset();
3147
3148       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3149       ObjSize = Flags.getByValSize();
3150       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3151       // Empty aggregate parameters do not take up registers.  Examples:
3152       //   struct { } a;
3153       //   union  { } b;
3154       //   int c[0];
3155       // etc.  However, we have to provide a place-holder in InVals, so
3156       // pretend we have an 8-byte item at the current address for that
3157       // purpose.
3158       if (!ObjSize) {
3159         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3160         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3161         InVals.push_back(FIN);
3162         continue;
3163       }
3164
3165       // Create a stack object covering all stack doublewords occupied
3166       // by the argument.  If the argument is (fully or partially) on
3167       // the stack, or if the argument is fully in registers but the
3168       // caller has allocated the parameter save anyway, we can refer
3169       // directly to the caller's stack frame.  Otherwise, create a
3170       // local copy in our own frame.
3171       int FI;
3172       if (HasParameterArea ||
3173           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3174         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3175       else
3176         FI = MFI->CreateStackObject(ArgSize, Align, false);
3177       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3178
3179       // Handle aggregates smaller than 8 bytes.
3180       if (ObjSize < PtrByteSize) {
3181         // The value of the object is its address, which differs from the
3182         // address of the enclosing doubleword on big-endian systems.
3183         SDValue Arg = FIN;
3184         if (!isLittleEndian) {
3185           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3186           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3187         }
3188         InVals.push_back(Arg);
3189
3190         if (GPR_idx != Num_GPR_Regs) {
3191           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3192           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3193           SDValue Store;
3194
3195           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3196             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3197                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3198             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3199                                       MachinePointerInfo(&*FuncArg), ObjType,
3200                                       false, false, 0);
3201           } else {
3202             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3203             // store the whole register as-is to the parameter save area
3204             // slot.
3205             Store =
3206                 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3207                              MachinePointerInfo(&*FuncArg), false, false, 0);
3208           }
3209
3210           MemOps.push_back(Store);
3211         }
3212         // Whether we copied from a register or not, advance the offset
3213         // into the parameter save area by a full doubleword.
3214         ArgOffset += PtrByteSize;
3215         continue;
3216       }
3217
3218       // The value of the object is its address, which is the address of
3219       // its first stack doubleword.
3220       InVals.push_back(FIN);
3221
3222       // Store whatever pieces of the object are in registers to memory.
3223       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3224         if (GPR_idx == Num_GPR_Regs)
3225           break;
3226
3227         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3228         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3229         SDValue Addr = FIN;
3230         if (j) {
3231           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3232           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3233         }
3234         SDValue Store =
3235             DAG.getStore(Val.getValue(1), dl, Val, Addr,
3236                          MachinePointerInfo(&*FuncArg, j), false, false, 0);
3237         MemOps.push_back(Store);
3238         ++GPR_idx;
3239       }
3240       ArgOffset += ArgSize;
3241       continue;
3242     }
3243
3244     switch (ObjectVT.getSimpleVT().SimpleTy) {
3245     default: llvm_unreachable("Unhandled argument type!");
3246     case MVT::i1:
3247     case MVT::i32:
3248     case MVT::i64:
3249       if (Flags.isNest()) {
3250         // The 'nest' parameter, if any, is passed in R11.
3251         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3252         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3253
3254         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3255           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3256
3257         break;
3258       }
3259
3260       // These can be scalar arguments or elements of an integer array type
3261       // passed directly.  Clang may use those instead of "byval" aggregate
3262       // types to avoid forcing arguments to memory unnecessarily.
3263       if (GPR_idx != Num_GPR_Regs) {
3264         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3265         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3266
3267         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3268           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3269           // value to MVT::i64 and then truncate to the correct register size.
3270           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3271       } else {
3272         if (CallConv == CallingConv::Fast)
3273           ComputeArgOffset();
3274
3275         needsLoad = true;
3276         ArgSize = PtrByteSize;
3277       }
3278       if (CallConv != CallingConv::Fast || needsLoad)
3279         ArgOffset += 8;
3280       break;
3281
3282     case MVT::f32:
3283     case MVT::f64:
3284       // These can be scalar arguments or elements of a float array type
3285       // passed directly.  The latter are used to implement ELFv2 homogenous
3286       // float aggregates.
3287       if (FPR_idx != Num_FPR_Regs) {
3288         unsigned VReg;
3289
3290         if (ObjectVT == MVT::f32)
3291           VReg = MF.addLiveIn(FPR[FPR_idx],
3292                               Subtarget.hasP8Vector()
3293                                   ? &PPC::VSSRCRegClass
3294                                   : &PPC::F4RCRegClass);
3295         else
3296           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3297                                                 ? &PPC::VSFRCRegClass
3298                                                 : &PPC::F8RCRegClass);
3299
3300         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3301         ++FPR_idx;
3302       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3303         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3304         // once we support fp <-> gpr moves.
3305
3306         // This can only ever happen in the presence of f32 array types,
3307         // since otherwise we never run out of FPRs before running out
3308         // of GPRs.
3309         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3310         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3311
3312         if (ObjectVT == MVT::f32) {
3313           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3314             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3315                                  DAG.getConstant(32, dl, MVT::i32));
3316           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3317         }
3318
3319         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3320       } else {
3321         if (CallConv == CallingConv::Fast)
3322           ComputeArgOffset();
3323
3324         needsLoad = true;
3325       }
3326
3327       // When passing an array of floats, the array occupies consecutive
3328       // space in the argument area; only round up to the next doubleword
3329       // at the end of the array.  Otherwise, each float takes 8 bytes.
3330       if (CallConv != CallingConv::Fast || needsLoad) {
3331         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3332         ArgOffset += ArgSize;
3333         if (Flags.isInConsecutiveRegsLast())
3334           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3335       }
3336       break;
3337     case MVT::v4f32:
3338     case MVT::v4i32:
3339     case MVT::v8i16:
3340     case MVT::v16i8:
3341     case MVT::v2f64:
3342     case MVT::v2i64:
3343     case MVT::v1i128:
3344       if (!Subtarget.hasQPX()) {
3345       // These can be scalar arguments or elements of a vector array type
3346       // passed directly.  The latter are used to implement ELFv2 homogenous
3347       // vector aggregates.
3348       if (VR_idx != Num_VR_Regs) {
3349         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3350                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3351                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3352         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3353         ++VR_idx;
3354       } else {
3355         if (CallConv == CallingConv::Fast)
3356           ComputeArgOffset();
3357
3358         needsLoad = true;
3359       }
3360       if (CallConv != CallingConv::Fast || needsLoad)
3361         ArgOffset += 16;
3362       break;
3363       } // not QPX
3364
3365       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3366              "Invalid QPX parameter type");
3367       /* fall through */
3368
3369     case MVT::v4f64:
3370     case MVT::v4i1:
3371       // QPX vectors are treated like their scalar floating-point subregisters
3372       // (except that they're larger).
3373       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3374       if (QFPR_idx != Num_QFPR_Regs) {
3375         const TargetRegisterClass *RC;
3376         switch (ObjectVT.getSimpleVT().SimpleTy) {
3377         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3378         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3379         default:         RC = &PPC::QBRCRegClass; break;
3380         }
3381
3382         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3383         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3384         ++QFPR_idx;
3385       } else {
3386         if (CallConv == CallingConv::Fast)
3387           ComputeArgOffset();
3388         needsLoad = true;
3389       }
3390       if (CallConv != CallingConv::Fast || needsLoad)
3391         ArgOffset += Sz;
3392       break;
3393     }
3394
3395     // We need to load the argument to a virtual register if we determined
3396     // above that we ran out of physical registers of the appropriate type.
3397     if (needsLoad) {
3398       if (ObjSize < ArgSize && !isLittleEndian)
3399         CurArgOffset += ArgSize - ObjSize;
3400       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3401       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3402       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3403                            false, false, false, 0);
3404     }
3405
3406     InVals.push_back(ArgVal);
3407   }
3408
3409   // Area that is at least reserved in the caller of this function.
3410   unsigned MinReservedArea;
3411   if (HasParameterArea)
3412     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3413   else
3414     MinReservedArea = LinkageSize;
3415
3416   // Set the size that is at least reserved in caller of this function.  Tail
3417   // call optimized functions' reserved stack space needs to be aligned so that
3418   // taking the difference between two stack areas will result in an aligned
3419   // stack.
3420   MinReservedArea =
3421       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3422   FuncInfo->setMinReservedArea(MinReservedArea);
3423
3424   // If the function takes variable number of arguments, make a frame index for
3425   // the start of the first vararg value... for expansion of llvm.va_start.
3426   if (isVarArg) {
3427     int Depth = ArgOffset;
3428
3429     FuncInfo->setVarArgsFrameIndex(
3430       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3431     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3432
3433     // If this function is vararg, store any remaining integer argument regs
3434     // to their spots on the stack so that they may be loaded by dereferencing
3435     // the result of va_next.
3436     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3437          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3438       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3439       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3440       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3441                                    MachinePointerInfo(), false, false, 0);
3442       MemOps.push_back(Store);
3443       // Increment the address by four for the next argument to store
3444       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3445       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3446     }
3447   }
3448
3449   if (!MemOps.empty())
3450     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3451
3452   return Chain;
3453 }
3454
3455 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3456     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3457     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3458     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3459   // TODO: add description of PPC stack frame format, or at least some docs.
3460   //
3461   MachineFunction &MF = DAG.getMachineFunction();
3462   MachineFrameInfo *MFI = MF.getFrameInfo();
3463   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3464
3465   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3466   bool isPPC64 = PtrVT == MVT::i64;
3467   // Potential tail calls could cause overwriting of argument stack slots.
3468   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3469                        (CallConv == CallingConv::Fast));
3470   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3471   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3472   unsigned ArgOffset = LinkageSize;
3473   // Area that is at least reserved in caller of this function.
3474   unsigned MinReservedArea = ArgOffset;
3475
3476   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3477     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3478     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3479   };
3480   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3481     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3482     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3483   };
3484   static const MCPhysReg VR[] = {
3485     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3486     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3487   };
3488
3489   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3490   const unsigned Num_FPR_Regs = 13;
3491   const unsigned Num_VR_Regs  = array_lengthof( VR);
3492
3493   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3494
3495   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3496
3497   // In 32-bit non-varargs functions, the stack space for vectors is after the
3498   // stack space for non-vectors.  We do not use this space unless we have
3499   // too many vectors to fit in registers, something that only occurs in
3500   // constructed examples:), but we have to walk the arglist to figure
3501   // that out...for the pathological case, compute VecArgOffset as the
3502   // start of the vector parameter area.  Computing VecArgOffset is the
3503   // entire point of the following loop.
3504   unsigned VecArgOffset = ArgOffset;
3505   if (!isVarArg && !isPPC64) {
3506     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3507          ++ArgNo) {
3508       EVT ObjectVT = Ins[ArgNo].VT;
3509       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3510
3511       if (Flags.isByVal()) {
3512         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3513         unsigned ObjSize = Flags.getByValSize();
3514         unsigned ArgSize =
3515                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3516         VecArgOffset += ArgSize;
3517         continue;
3518       }
3519
3520       switch(ObjectVT.getSimpleVT().SimpleTy) {
3521       default: llvm_unreachable("Unhandled argument type!");
3522       case MVT::i1:
3523       case MVT::i32:
3524       case MVT::f32:
3525         VecArgOffset += 4;
3526         break;
3527       case MVT::i64:  // PPC64
3528       case MVT::f64:
3529         // FIXME: We are guaranteed to be !isPPC64 at this point.
3530         // Does MVT::i64 apply?
3531         VecArgOffset += 8;
3532         break;
3533       case MVT::v4f32:
3534       case MVT::v4i32:
3535       case MVT::v8i16:
3536       case MVT::v16i8:
3537         // Nothing to do, we're only looking at Nonvector args here.
3538         break;
3539       }
3540     }
3541   }
3542   // We've found where the vector parameter area in memory is.  Skip the
3543   // first 12 parameters; these don't use that memory.
3544   VecArgOffset = ((VecArgOffset+15)/16)*16;
3545   VecArgOffset += 12*16;
3546
3547   // Add DAG nodes to load the arguments or copy them out of registers.  On
3548   // entry to a function on PPC, the arguments start after the linkage area,
3549   // although the first ones are often in registers.
3550
3551   SmallVector<SDValue, 8> MemOps;
3552   unsigned nAltivecParamsAtEnd = 0;
3553   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3554   unsigned CurArgIdx = 0;
3555   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3556     SDValue ArgVal;
3557     bool needsLoad = false;
3558     EVT ObjectVT = Ins[ArgNo].VT;
3559     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3560     unsigned ArgSize = ObjSize;
3561     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3562     if (Ins[ArgNo].isOrigArg()) {
3563       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3564       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3565     }
3566     unsigned CurArgOffset = ArgOffset;
3567
3568     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3569     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3570         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3571       if (isVarArg || isPPC64) {
3572         MinReservedArea = ((MinReservedArea+15)/16)*16;
3573         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3574                                                   Flags,
3575                                                   PtrByteSize);
3576       } else  nAltivecParamsAtEnd++;
3577     } else
3578       // Calculate min reserved area.
3579       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3580                                                 Flags,
3581                                                 PtrByteSize);
3582
3583     // FIXME the codegen can be much improved in some cases.
3584     // We do not have to keep everything in memory.
3585     if (Flags.isByVal()) {
3586       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3587
3588       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3589       ObjSize = Flags.getByValSize();
3590       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3591       // Objects of size 1 and 2 are right justified, everything else is
3592       // left justified.  This means the memory address is adjusted forwards.
3593       if (ObjSize==1 || ObjSize==2) {
3594         CurArgOffset = CurArgOffset + (4 - ObjSize);
3595       }
3596       // The value of the object is its address.
3597       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3598       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3599       InVals.push_back(FIN);
3600       if (ObjSize==1 || ObjSize==2) {
3601         if (GPR_idx != Num_GPR_Regs) {
3602           unsigned VReg;
3603           if (isPPC64)
3604             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3605           else
3606             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3607           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3608           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3609           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3610                                             MachinePointerInfo(&*FuncArg),
3611                                             ObjType, false, false, 0);
3612           MemOps.push_back(Store);
3613           ++GPR_idx;
3614         }
3615
3616         ArgOffset += PtrByteSize;
3617
3618         continue;
3619       }
3620       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3621         // Store whatever pieces of the object are in registers
3622         // to memory.  ArgOffset will be the address of the beginning
3623         // of the object.
3624         if (GPR_idx != Num_GPR_Regs) {
3625           unsigned VReg;
3626           if (isPPC64)
3627             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3628           else
3629             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3630           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3631           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3632           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3633           SDValue Store =
3634               DAG.getStore(Val.getValue(1), dl, Val, FIN,
3635                            MachinePointerInfo(&*FuncArg, j), false, false, 0);
3636           MemOps.push_back(Store);
3637           ++GPR_idx;
3638           ArgOffset += PtrByteSize;
3639         } else {
3640           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3641           break;
3642         }
3643       }
3644       continue;
3645     }
3646
3647     switch (ObjectVT.getSimpleVT().SimpleTy) {
3648     default: llvm_unreachable("Unhandled argument type!");
3649     case MVT::i1:
3650     case MVT::i32:
3651       if (!isPPC64) {
3652         if (GPR_idx != Num_GPR_Regs) {
3653           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3654           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3655
3656           if (ObjectVT == MVT::i1)
3657             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3658
3659           ++GPR_idx;
3660         } else {
3661           needsLoad = true;
3662           ArgSize = PtrByteSize;
3663         }
3664         // All int arguments reserve stack space in the Darwin ABI.
3665         ArgOffset += PtrByteSize;
3666         break;
3667       }
3668       // FALLTHROUGH
3669     case MVT::i64:  // PPC64
3670       if (GPR_idx != Num_GPR_Regs) {
3671         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3672         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3673
3674         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3675           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3676           // value to MVT::i64 and then truncate to the correct register size.
3677           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3678
3679         ++GPR_idx;
3680       } else {
3681         needsLoad = true;
3682         ArgSize = PtrByteSize;
3683       }
3684       // All int arguments reserve stack space in the Darwin ABI.
3685       ArgOffset += 8;
3686       break;
3687
3688     case MVT::f32:
3689     case MVT::f64:
3690       // Every 4 bytes of argument space consumes one of the GPRs available for
3691       // argument passing.
3692       if (GPR_idx != Num_GPR_Regs) {
3693         ++GPR_idx;
3694         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3695           ++GPR_idx;
3696       }
3697       if (FPR_idx != Num_FPR_Regs) {
3698         unsigned VReg;
3699
3700         if (ObjectVT == MVT::f32)
3701           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3702         else
3703           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3704
3705         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3706         ++FPR_idx;
3707       } else {
3708         needsLoad = true;
3709       }
3710
3711       // All FP arguments reserve stack space in the Darwin ABI.
3712       ArgOffset += isPPC64 ? 8 : ObjSize;
3713       break;
3714     case MVT::v4f32:
3715     case MVT::v4i32:
3716     case MVT::v8i16:
3717     case MVT::v16i8:
3718       // Note that vector arguments in registers don't reserve stack space,
3719       // except in varargs functions.
3720       if (VR_idx != Num_VR_Regs) {
3721         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3722         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3723         if (isVarArg) {
3724           while ((ArgOffset % 16) != 0) {
3725             ArgOffset += PtrByteSize;
3726             if (GPR_idx != Num_GPR_Regs)
3727               GPR_idx++;
3728           }
3729           ArgOffset += 16;
3730           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3731         }
3732         ++VR_idx;
3733       } else {
3734         if (!isVarArg && !isPPC64) {
3735           // Vectors go after all the nonvectors.
3736           CurArgOffset = VecArgOffset;
3737           VecArgOffset += 16;
3738         } else {
3739           // Vectors are aligned.
3740           ArgOffset = ((ArgOffset+15)/16)*16;
3741           CurArgOffset = ArgOffset;
3742           ArgOffset += 16;
3743         }
3744         needsLoad = true;
3745       }
3746       break;
3747     }
3748
3749     // We need to load the argument to a virtual register if we determined above
3750     // that we ran out of physical registers of the appropriate type.
3751     if (needsLoad) {
3752       int FI = MFI->CreateFixedObject(ObjSize,
3753                                       CurArgOffset + (ArgSize - ObjSize),
3754                                       isImmutable);
3755       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3756       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3757                            false, false, false, 0);
3758     }
3759
3760     InVals.push_back(ArgVal);
3761   }
3762
3763   // Allow for Altivec parameters at the end, if needed.
3764   if (nAltivecParamsAtEnd) {
3765     MinReservedArea = ((MinReservedArea+15)/16)*16;
3766     MinReservedArea += 16*nAltivecParamsAtEnd;
3767   }
3768
3769   // Area that is at least reserved in the caller of this function.
3770   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3771
3772   // Set the size that is at least reserved in caller of this function.  Tail
3773   // call optimized functions' reserved stack space needs to be aligned so that
3774   // taking the difference between two stack areas will result in an aligned
3775   // stack.
3776   MinReservedArea =
3777       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3778   FuncInfo->setMinReservedArea(MinReservedArea);
3779
3780   // If the function takes variable number of arguments, make a frame index for
3781   // the start of the first vararg value... for expansion of llvm.va_start.
3782   if (isVarArg) {
3783     int Depth = ArgOffset;
3784
3785     FuncInfo->setVarArgsFrameIndex(
3786       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3787                              Depth, true));
3788     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3789
3790     // If this function is vararg, store any remaining integer argument regs
3791     // to their spots on the stack so that they may be loaded by dereferencing
3792     // the result of va_next.
3793     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3794       unsigned VReg;
3795
3796       if (isPPC64)
3797         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3798       else
3799         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3800
3801       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3802       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3803                                    MachinePointerInfo(), false, false, 0);
3804       MemOps.push_back(Store);
3805       // Increment the address by four for the next argument to store
3806       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3807       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3808     }
3809   }
3810
3811   if (!MemOps.empty())
3812     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3813
3814   return Chain;
3815 }
3816
3817 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3818 /// adjusted to accommodate the arguments for the tailcall.
3819 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3820                                    unsigned ParamSize) {
3821
3822   if (!isTailCall) return 0;
3823
3824   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3825   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3826   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3827   // Remember only if the new adjustement is bigger.
3828   if (SPDiff < FI->getTailCallSPDelta())
3829     FI->setTailCallSPDelta(SPDiff);
3830
3831   return SPDiff;
3832 }
3833
3834 static bool isFunctionGlobalAddress(SDValue Callee);
3835
3836 static bool
3837 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3838   // If !G, Callee can be an external symbol.
3839   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3840   if (!G) return false;
3841
3842   const GlobalValue *GV = G->getGlobal();
3843
3844   if (GV->isDeclaration()) return false;
3845
3846   switch(GV->getLinkage()) {
3847   default: llvm_unreachable("unknow linkage type");
3848   case GlobalValue::AvailableExternallyLinkage:
3849   case GlobalValue::ExternalWeakLinkage:
3850     return false;
3851
3852   // Callee with weak linkage is allowed if it has hidden or protected
3853   // visibility
3854   case GlobalValue::LinkOnceAnyLinkage:
3855   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3856   case GlobalValue::WeakAnyLinkage:
3857   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3858     if (GV->hasDefaultVisibility())
3859       return false;
3860
3861   case GlobalValue::ExternalLinkage:
3862   case GlobalValue::InternalLinkage:
3863   case GlobalValue::PrivateLinkage:
3864     break;
3865   }
3866
3867   // With '-fPIC', calling default visiblity function need insert 'nop' after
3868   // function call, no matter that function resides in same module or not, so
3869   // we treat it as in different module.
3870   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3871     return false;
3872
3873   return true;
3874 }
3875
3876 static bool
3877 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3878                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3879   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3880
3881   const unsigned PtrByteSize = 8;
3882   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3883
3884   static const MCPhysReg GPR[] = {
3885     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3886     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3887   };
3888   static const MCPhysReg VR[] = {
3889     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3890     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3891   };
3892
3893   const unsigned NumGPRs = array_lengthof(GPR);
3894   const unsigned NumFPRs = 13;
3895   const unsigned NumVRs = array_lengthof(VR);
3896   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3897
3898   unsigned NumBytes = LinkageSize;
3899   unsigned AvailableFPRs = NumFPRs;
3900   unsigned AvailableVRs = NumVRs;
3901
3902   for (const ISD::OutputArg& Param : Outs) {
3903     if (Param.Flags.isNest()) continue;
3904
3905     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3906                                PtrByteSize, LinkageSize, ParamAreaSize,
3907                                NumBytes, AvailableFPRs, AvailableVRs,
3908                                Subtarget.hasQPX()))
3909       return true;
3910   }
3911   return false;
3912 }
3913
3914 static bool
3915 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
3916   if (CS->arg_size() != CallerFn->getArgumentList().size())
3917     return false;
3918
3919   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
3920   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
3921   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
3922
3923   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
3924     const Value* CalleeArg = *CalleeArgIter;
3925     const Value* CallerArg = &(*CallerArgIter);
3926     if (CalleeArg == CallerArg)
3927       continue;
3928
3929     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
3930     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
3931     //      }
3932     // 1st argument of callee is undef and has the same type as caller.
3933     if (CalleeArg->getType() == CallerArg->getType() &&
3934         isa<UndefValue>(CalleeArg))
3935       continue;
3936
3937     return false;
3938   }
3939
3940   return true;
3941 }
3942
3943 bool
3944 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
3945                                     SDValue Callee,
3946                                     CallingConv::ID CalleeCC,
3947                                     ImmutableCallSite *CS,
3948                                     bool isVarArg,
3949                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3950                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3951                                     SelectionDAG& DAG) const {
3952   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
3953
3954   if (DisableSCO && !TailCallOpt) return false;
3955
3956   // Variadic argument functions are not supported.
3957   if (isVarArg) return false;
3958
3959   MachineFunction &MF = DAG.getMachineFunction();
3960   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3961
3962   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
3963   // the same calling convention
3964   if (CallerCC != CalleeCC) return false;
3965
3966   // SCO support C calling convention
3967   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
3968     return false;
3969
3970   // Functions containing by val parameters are not supported.
3971   if (std::any_of(Ins.begin(), Ins.end(),
3972                   [](const ISD::InputArg& IA) { return IA.Flags.isByVal(); }))
3973     return false;
3974
3975   // No TCO/SCO on indirect call because Caller have to restore its TOC
3976   if (!isFunctionGlobalAddress(Callee) &&
3977       !isa<ExternalSymbolSDNode>(Callee))
3978     return false;
3979
3980   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
3981   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
3982   // module.
3983   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
3984   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
3985     return false;
3986
3987   // TCO allows altering callee ABI, so we don't have to check further.
3988   if (CalleeCC == CallingConv::Fast && TailCallOpt)
3989     return true;
3990
3991   if (DisableSCO) return false;
3992
3993   // If callee use the same argument list that caller is using, then we can
3994   // apply SCO on this case. If it is not, then we need to check if callee needs
3995   // stack for passing arguments.
3996   if (!hasSameArgumentList(MF.getFunction(), CS) &&
3997       needStackSlotPassParameters(Subtarget, Outs)) {
3998     return false;
3999   }
4000
4001   return true;
4002 }
4003
4004 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4005 /// for tail call optimization. Targets which want to do tail call
4006 /// optimization should implement this function.
4007 bool
4008 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4009                                                      CallingConv::ID CalleeCC,
4010                                                      bool isVarArg,
4011                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4012                                                      SelectionDAG& DAG) const {
4013   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4014     return false;
4015
4016   // Variable argument functions are not supported.
4017   if (isVarArg)
4018     return false;
4019
4020   MachineFunction &MF = DAG.getMachineFunction();
4021   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4022   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4023     // Functions containing by val parameters are not supported.
4024     for (unsigned i = 0; i != Ins.size(); i++) {
4025        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4026        if (Flags.isByVal()) return false;
4027     }
4028
4029     // Non-PIC/GOT tail calls are supported.
4030     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4031       return true;
4032
4033     // At the moment we can only do local tail calls (in same module, hidden
4034     // or protected) if we are generating PIC.
4035     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4036       return G->getGlobal()->hasHiddenVisibility()
4037           || G->getGlobal()->hasProtectedVisibility();
4038   }
4039
4040   return false;
4041 }
4042
4043 /// isCallCompatibleAddress - Return the immediate to use if the specified
4044 /// 32-bit value is representable in the immediate field of a BxA instruction.
4045 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4046   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4047   if (!C) return nullptr;
4048
4049   int Addr = C->getZExtValue();
4050   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4051       SignExtend32<26>(Addr) != Addr)
4052     return nullptr;  // Top 6 bits have to be sext of immediate.
4053
4054   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
4055                          DAG.getTargetLoweringInfo().getPointerTy(
4056                              DAG.getDataLayout())).getNode();
4057 }
4058
4059 namespace {
4060
4061 struct TailCallArgumentInfo {
4062   SDValue Arg;
4063   SDValue FrameIdxOp;
4064   int       FrameIdx;
4065
4066   TailCallArgumentInfo() : FrameIdx(0) {}
4067 };
4068 }
4069
4070 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4071 static void StoreTailCallArgumentsToStackSlot(
4072     SelectionDAG &DAG, SDValue Chain,
4073     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4074     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4075   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4076     SDValue Arg = TailCallArgs[i].Arg;
4077     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4078     int FI = TailCallArgs[i].FrameIdx;
4079     // Store relative to framepointer.
4080     MemOpChains.push_back(DAG.getStore(
4081         Chain, dl, Arg, FIN,
4082         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
4083         false, 0));
4084   }
4085 }
4086
4087 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4088 /// the appropriate stack slot for the tail call optimized function call.
4089 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4090                                              SDValue OldRetAddr, SDValue OldFP,
4091                                              int SPDiff, const SDLoc &dl) {
4092   if (SPDiff) {
4093     // Calculate the new stack slot for the return address.
4094     MachineFunction &MF = DAG.getMachineFunction();
4095     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4096     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4097     bool isPPC64 = Subtarget.isPPC64();
4098     int SlotSize = isPPC64 ? 8 : 4;
4099     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4100     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
4101                                                           NewRetAddrLoc, true);
4102     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4103     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4104     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4105                          MachinePointerInfo::getFixedStack(MF, NewRetAddr),
4106                          false, false, 0);
4107
4108     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4109     // slot as the FP is never overwritten.
4110     if (Subtarget.isDarwinABI()) {
4111       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4112       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
4113                                                           true);
4114       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4115       Chain = DAG.getStore(
4116           Chain, dl, OldFP, NewFramePtrIdx,
4117           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx),
4118           false, false, 0);
4119     }
4120   }
4121   return Chain;
4122 }
4123
4124 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4125 /// the position of the argument.
4126 static void
4127 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4128                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4129                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4130   int Offset = ArgOffset + SPDiff;
4131   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4132   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
4133   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4134   SDValue FIN = DAG.getFrameIndex(FI, VT);
4135   TailCallArgumentInfo Info;
4136   Info.Arg = Arg;
4137   Info.FrameIdxOp = FIN;
4138   Info.FrameIdx = FI;
4139   TailCallArguments.push_back(Info);
4140 }
4141
4142 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4143 /// stack slot. Returns the chain as result and the loaded frame pointers in
4144 /// LROpOut/FPOpout. Used when tail calling.
4145 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4146     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4147     SDValue &FPOpOut, const SDLoc &dl) const {
4148   if (SPDiff) {
4149     // Load the LR and FP stack slot for later adjusting.
4150     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4151     LROpOut = getReturnAddrFrameIndex(DAG);
4152     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
4153                           false, false, false, 0);
4154     Chain = SDValue(LROpOut.getNode(), 1);
4155
4156     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4157     // slot as the FP is never overwritten.
4158     if (Subtarget.isDarwinABI()) {
4159       FPOpOut = getFramePointerFrameIndex(DAG);
4160       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
4161                             false, false, false, 0);
4162       Chain = SDValue(FPOpOut.getNode(), 1);
4163     }
4164   }
4165   return Chain;
4166 }
4167
4168 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4169 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4170 /// specified by the specific parameter attribute. The copy will be passed as
4171 /// a byval function parameter.
4172 /// Sometimes what we are copying is the end of a larger object, the part that
4173 /// does not fit in registers.
4174 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4175                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4176                                          SelectionDAG &DAG, const SDLoc &dl) {
4177   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4178   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4179                        false, false, false, MachinePointerInfo(),
4180                        MachinePointerInfo());
4181 }
4182
4183 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4184 /// tail calls.
4185 static void LowerMemOpCallTo(
4186     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4187     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4188     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4189     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4190   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4191   if (!isTailCall) {
4192     if (isVector) {
4193       SDValue StackPtr;
4194       if (isPPC64)
4195         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4196       else
4197         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4198       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4199                            DAG.getConstant(ArgOffset, dl, PtrVT));
4200     }
4201     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4202                                        MachinePointerInfo(), false, false, 0));
4203   // Calculate and remember argument location.
4204   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4205                                   TailCallArguments);
4206 }
4207
4208 static void
4209 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4210                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4211                 SDValue FPOp,
4212                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4213   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4214   // might overwrite each other in case of tail call optimization.
4215   SmallVector<SDValue, 8> MemOpChains2;
4216   // Do not flag preceding copytoreg stuff together with the following stuff.
4217   InFlag = SDValue();
4218   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4219                                     MemOpChains2, dl);
4220   if (!MemOpChains2.empty())
4221     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4222
4223   // Store the return address to the appropriate stack slot.
4224   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4225
4226   // Emit callseq_end just before tailcall node.
4227   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4228                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4229   InFlag = Chain.getValue(1);
4230 }
4231
4232 // Is this global address that of a function that can be called by name? (as
4233 // opposed to something that must hold a descriptor for an indirect call).
4234 static bool isFunctionGlobalAddress(SDValue Callee) {
4235   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4236     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4237         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4238       return false;
4239
4240     return G->getGlobal()->getValueType()->isFunctionTy();
4241   }
4242
4243   return false;
4244 }
4245
4246 static unsigned
4247 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4248             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4249             bool isPatchPoint, bool hasNest,
4250             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4251             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4252             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4253
4254   bool isPPC64 = Subtarget.isPPC64();
4255   bool isSVR4ABI = Subtarget.isSVR4ABI();
4256   bool isELFv2ABI = Subtarget.isELFv2ABI();
4257
4258   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4259   NodeTys.push_back(MVT::Other);   // Returns a chain
4260   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4261
4262   unsigned CallOpc = PPCISD::CALL;
4263
4264   bool needIndirectCall = true;
4265   if (!isSVR4ABI || !isPPC64)
4266     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4267       // If this is an absolute destination address, use the munged value.
4268       Callee = SDValue(Dest, 0);
4269       needIndirectCall = false;
4270     }
4271
4272   // PC-relative references to external symbols should go through $stub, unless
4273   // we're building with the leopard linker or later, which automatically
4274   // synthesizes these stubs.
4275   const TargetMachine &TM = DAG.getTarget();
4276   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4277   const GlobalValue *GV = nullptr;
4278   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4279     GV = G->getGlobal();
4280   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4281   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4282
4283   if (isFunctionGlobalAddress(Callee)) {
4284     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4285     // A call to a TLS address is actually an indirect call to a
4286     // thread-specific pointer.
4287     unsigned OpFlags = 0;
4288     if (UsePlt)
4289       OpFlags = PPCII::MO_PLT;
4290
4291     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4292     // every direct call is) turn it into a TargetGlobalAddress /
4293     // TargetExternalSymbol node so that legalize doesn't hack it.
4294     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4295                                         Callee.getValueType(), 0, OpFlags);
4296     needIndirectCall = false;
4297   }
4298
4299   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4300     unsigned char OpFlags = 0;
4301
4302     if (UsePlt)
4303       OpFlags = PPCII::MO_PLT;
4304
4305     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4306                                          OpFlags);
4307     needIndirectCall = false;
4308   }
4309
4310   if (isPatchPoint) {
4311     // We'll form an invalid direct call when lowering a patchpoint; the full
4312     // sequence for an indirect call is complicated, and many of the
4313     // instructions introduced might have side effects (and, thus, can't be
4314     // removed later). The call itself will be removed as soon as the
4315     // argument/return lowering is complete, so the fact that it has the wrong
4316     // kind of operands should not really matter.
4317     needIndirectCall = false;
4318   }
4319
4320   if (needIndirectCall) {
4321     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4322     // to do the call, we can't use PPCISD::CALL.
4323     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4324
4325     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4326       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4327       // entry point, but to the function descriptor (the function entry point
4328       // address is part of the function descriptor though).
4329       // The function descriptor is a three doubleword structure with the
4330       // following fields: function entry point, TOC base address and
4331       // environment pointer.
4332       // Thus for a call through a function pointer, the following actions need
4333       // to be performed:
4334       //   1. Save the TOC of the caller in the TOC save area of its stack
4335       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4336       //   2. Load the address of the function entry point from the function
4337       //      descriptor.
4338       //   3. Load the TOC of the callee from the function descriptor into r2.
4339       //   4. Load the environment pointer from the function descriptor into
4340       //      r11.
4341       //   5. Branch to the function entry point address.
4342       //   6. On return of the callee, the TOC of the caller needs to be
4343       //      restored (this is done in FinishCall()).
4344       //
4345       // The loads are scheduled at the beginning of the call sequence, and the
4346       // register copies are flagged together to ensure that no other
4347       // operations can be scheduled in between. E.g. without flagging the
4348       // copies together, a TOC access in the caller could be scheduled between
4349       // the assignment of the callee TOC and the branch to the callee, which
4350       // results in the TOC access going through the TOC of the callee instead
4351       // of going through the TOC of the caller, which leads to incorrect code.
4352
4353       // Load the address of the function entry point from the function
4354       // descriptor.
4355       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4356       if (LDChain.getValueType() == MVT::Glue)
4357         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4358
4359       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4360
4361       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4362       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4363                                         false, false, LoadsInv, 8);
4364
4365       // Load environment pointer into r11.
4366       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4367       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4368       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4369                                        MPI.getWithOffset(16), false, false,
4370                                        LoadsInv, 8);
4371
4372       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4373       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4374       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4375                                    MPI.getWithOffset(8), false, false,
4376                                    LoadsInv, 8);
4377
4378       setUsesTOCBasePtr(DAG);
4379       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4380                                         InFlag);
4381       Chain = TOCVal.getValue(0);
4382       InFlag = TOCVal.getValue(1);
4383
4384       // If the function call has an explicit 'nest' parameter, it takes the
4385       // place of the environment pointer.
4386       if (!hasNest) {
4387         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4388                                           InFlag);
4389
4390         Chain = EnvVal.getValue(0);
4391         InFlag = EnvVal.getValue(1);
4392       }
4393
4394       MTCTROps[0] = Chain;
4395       MTCTROps[1] = LoadFuncPtr;
4396       MTCTROps[2] = InFlag;
4397     }
4398
4399     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4400                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4401     InFlag = Chain.getValue(1);
4402
4403     NodeTys.clear();
4404     NodeTys.push_back(MVT::Other);
4405     NodeTys.push_back(MVT::Glue);
4406     Ops.push_back(Chain);
4407     CallOpc = PPCISD::BCTRL;
4408     Callee.setNode(nullptr);
4409     // Add use of X11 (holding environment pointer)
4410     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4411       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4412     // Add CTR register as callee so a bctr can be emitted later.
4413     if (isTailCall)
4414       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4415   }
4416
4417   // If this is a direct call, pass the chain and the callee.
4418   if (Callee.getNode()) {
4419     Ops.push_back(Chain);
4420     Ops.push_back(Callee);
4421   }
4422   // If this is a tail call add stack pointer delta.
4423   if (isTailCall)
4424     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4425
4426   // Add argument registers to the end of the list so that they are known live
4427   // into the call.
4428   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4429     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4430                                   RegsToPass[i].second.getValueType()));
4431
4432   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4433   // into the call.
4434   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4435     setUsesTOCBasePtr(DAG);
4436     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4437   }
4438
4439   return CallOpc;
4440 }
4441
4442 static
4443 bool isLocalCall(const SDValue &Callee)
4444 {
4445   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4446     return G->getGlobal()->isStrongDefinitionForLinker();
4447   return false;
4448 }
4449
4450 SDValue PPCTargetLowering::LowerCallResult(
4451     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4452     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4453     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4454
4455   SmallVector<CCValAssign, 16> RVLocs;
4456   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4457                     *DAG.getContext());
4458   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4459
4460   // Copy all of the result registers out of their specified physreg.
4461   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4462     CCValAssign &VA = RVLocs[i];
4463     assert(VA.isRegLoc() && "Can only return in registers!");
4464
4465     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4466                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4467     Chain = Val.getValue(1);
4468     InFlag = Val.getValue(2);
4469
4470     switch (VA.getLocInfo()) {
4471     default: llvm_unreachable("Unknown loc info!");
4472     case CCValAssign::Full: break;
4473     case CCValAssign::AExt:
4474       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4475       break;
4476     case CCValAssign::ZExt:
4477       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4478                         DAG.getValueType(VA.getValVT()));
4479       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4480       break;
4481     case CCValAssign::SExt:
4482       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4483                         DAG.getValueType(VA.getValVT()));
4484       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4485       break;
4486     }
4487
4488     InVals.push_back(Val);
4489   }
4490
4491   return Chain;
4492 }
4493
4494 SDValue PPCTargetLowering::FinishCall(
4495     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4496     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4497     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4498     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4499     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4500     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4501
4502   std::vector<EVT> NodeTys;
4503   SmallVector<SDValue, 8> Ops;
4504   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4505                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4506                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4507
4508   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4509   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4510     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4511
4512   // When performing tail call optimization the callee pops its arguments off
4513   // the stack. Account for this here so these bytes can be pushed back on in
4514   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4515   int BytesCalleePops =
4516     (CallConv == CallingConv::Fast &&
4517      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4518
4519   // Add a register mask operand representing the call-preserved registers.
4520   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4521   const uint32_t *Mask =
4522       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4523   assert(Mask && "Missing call preserved mask for calling convention");
4524   Ops.push_back(DAG.getRegisterMask(Mask));
4525
4526   if (InFlag.getNode())
4527     Ops.push_back(InFlag);
4528
4529   // Emit tail call.
4530   if (isTailCall) {
4531     assert(((Callee.getOpcode() == ISD::Register &&
4532              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4533             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4534             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4535             isa<ConstantSDNode>(Callee)) &&
4536     "Expecting an global address, external symbol, absolute value or register");
4537
4538     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4539     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4540   }
4541
4542   // Add a NOP immediately after the branch instruction when using the 64-bit
4543   // SVR4 ABI. At link time, if caller and callee are in a different module and
4544   // thus have a different TOC, the call will be replaced with a call to a stub
4545   // function which saves the current TOC, loads the TOC of the callee and
4546   // branches to the callee. The NOP will be replaced with a load instruction
4547   // which restores the TOC of the caller from the TOC save slot of the current
4548   // stack frame. If caller and callee belong to the same module (and have the
4549   // same TOC), the NOP will remain unchanged.
4550
4551   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4552       !isPatchPoint) {
4553     if (CallOpc == PPCISD::BCTRL) {
4554       // This is a call through a function pointer.
4555       // Restore the caller TOC from the save area into R2.
4556       // See PrepareCall() for more information about calls through function
4557       // pointers in the 64-bit SVR4 ABI.
4558       // We are using a target-specific load with r2 hard coded, because the
4559       // result of a target-independent load would never go directly into r2,
4560       // since r2 is a reserved register (which prevents the register allocator
4561       // from allocating it), resulting in an additional register being
4562       // allocated and an unnecessary move instruction being generated.
4563       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4564
4565       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4566       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4567       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4568       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4569       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4570
4571       // The address needs to go after the chain input but before the flag (or
4572       // any other variadic arguments).
4573       Ops.insert(std::next(Ops.begin()), AddTOC);
4574     } else if ((CallOpc == PPCISD::CALL) &&
4575                (!isLocalCall(Callee) ||
4576                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4577       // Otherwise insert NOP for non-local calls.
4578       CallOpc = PPCISD::CALL_NOP;
4579   }
4580
4581   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4582   InFlag = Chain.getValue(1);
4583
4584   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4585                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4586                              InFlag, dl);
4587   if (!Ins.empty())
4588     InFlag = Chain.getValue(1);
4589
4590   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4591                          Ins, dl, DAG, InVals);
4592 }
4593
4594 SDValue
4595 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4596                              SmallVectorImpl<SDValue> &InVals) const {
4597   SelectionDAG &DAG                     = CLI.DAG;
4598   SDLoc &dl                             = CLI.DL;
4599   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4600   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4601   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4602   SDValue Chain                         = CLI.Chain;
4603   SDValue Callee                        = CLI.Callee;
4604   bool &isTailCall                      = CLI.IsTailCall;
4605   CallingConv::ID CallConv              = CLI.CallConv;
4606   bool isVarArg                         = CLI.IsVarArg;
4607   bool isPatchPoint                     = CLI.IsPatchPoint;
4608   ImmutableCallSite *CS                 = CLI.CS;
4609
4610   if (isTailCall) {
4611     if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4612       isTailCall =
4613         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4614                                                  isVarArg, Outs, Ins, DAG);
4615     else
4616       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4617                                                      Ins, DAG);
4618     if (isTailCall) {
4619       ++NumTailCalls;
4620       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4621         ++NumSiblingCalls;
4622
4623       assert(isa<GlobalAddressSDNode>(Callee) &&
4624              "Callee should be an llvm::Function object.");
4625       DEBUG(
4626         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4627         const unsigned Width = 80 - strlen("TCO caller: ")
4628                                   - strlen(", callee linkage: 0, 0");
4629         dbgs() << "TCO caller: "
4630                << left_justify(DAG.getMachineFunction().getName(), Width)
4631                << ", callee linkage: "
4632                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4633       );
4634     }
4635   }
4636
4637   if (!isTailCall && CS && CS->isMustTailCall())
4638     report_fatal_error("failed to perform tail call elimination on a call "
4639                        "site marked musttail");
4640
4641   if (Subtarget.isSVR4ABI()) {
4642     if (Subtarget.isPPC64())
4643       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4644                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4645                               dl, DAG, InVals, CS);
4646     else
4647       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4648                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4649                               dl, DAG, InVals, CS);
4650   }
4651
4652   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4653                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4654                           dl, DAG, InVals, CS);
4655 }
4656
4657 SDValue PPCTargetLowering::LowerCall_32SVR4(
4658     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4659     bool isTailCall, bool isPatchPoint,
4660     const SmallVectorImpl<ISD::OutputArg> &Outs,
4661     const SmallVectorImpl<SDValue> &OutVals,
4662     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4663     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4664     ImmutableCallSite *CS) const {
4665   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4666   // of the 32-bit SVR4 ABI stack frame layout.
4667
4668   assert((CallConv == CallingConv::C ||
4669           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4670
4671   unsigned PtrByteSize = 4;
4672
4673   MachineFunction &MF = DAG.getMachineFunction();
4674
4675   // Mark this function as potentially containing a function that contains a
4676   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4677   // and restoring the callers stack pointer in this functions epilog. This is
4678   // done because by tail calling the called function might overwrite the value
4679   // in this function's (MF) stack pointer stack slot 0(SP).
4680   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4681       CallConv == CallingConv::Fast)
4682     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4683
4684   // Count how many bytes are to be pushed on the stack, including the linkage
4685   // area, parameter list area and the part of the local variable space which
4686   // contains copies of aggregates which are passed by value.
4687
4688   // Assign locations to all of the outgoing arguments.
4689   SmallVector<CCValAssign, 16> ArgLocs;
4690   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4691
4692   // Reserve space for the linkage area on the stack.
4693   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4694                        PtrByteSize);
4695   if (Subtarget.useSoftFloat())
4696     CCInfo.PreAnalyzeCallOperands(Outs);
4697
4698   if (isVarArg) {
4699     // Handle fixed and variable vector arguments differently.
4700     // Fixed vector arguments go into registers as long as registers are
4701     // available. Variable vector arguments always go into memory.
4702     unsigned NumArgs = Outs.size();
4703
4704     for (unsigned i = 0; i != NumArgs; ++i) {
4705       MVT ArgVT = Outs[i].VT;
4706       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4707       bool Result;
4708
4709       if (Outs[i].IsFixed) {
4710         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4711                                CCInfo);
4712       } else {
4713         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4714                                       ArgFlags, CCInfo);
4715       }
4716
4717       if (Result) {
4718 #ifndef NDEBUG
4719         errs() << "Call operand #" << i << " has unhandled type "
4720              << EVT(ArgVT).getEVTString() << "\n";
4721 #endif
4722         llvm_unreachable(nullptr);
4723       }
4724     }
4725   } else {
4726     // All arguments are treated the same.
4727     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4728   }
4729   CCInfo.clearWasPPCF128();
4730
4731   // Assign locations to all of the outgoing aggregate by value arguments.
4732   SmallVector<CCValAssign, 16> ByValArgLocs;
4733   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4734
4735   // Reserve stack space for the allocations in CCInfo.
4736   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4737
4738   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4739
4740   // Size of the linkage area, parameter list area and the part of the local
4741   // space variable where copies of aggregates which are passed by value are
4742   // stored.
4743   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4744
4745   // Calculate by how many bytes the stack has to be adjusted in case of tail
4746   // call optimization.
4747   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4748
4749   // Adjust the stack pointer for the new arguments...
4750   // These operations are automatically eliminated by the prolog/epilog pass
4751   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4752                                dl);
4753   SDValue CallSeqStart = Chain;
4754
4755   // Load the return address and frame pointer so it can be moved somewhere else
4756   // later.
4757   SDValue LROp, FPOp;
4758   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4759
4760   // Set up a copy of the stack pointer for use loading and storing any
4761   // arguments that may not fit in the registers available for argument
4762   // passing.
4763   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4764
4765   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4766   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4767   SmallVector<SDValue, 8> MemOpChains;
4768
4769   bool seenFloatArg = false;
4770   // Walk the register/memloc assignments, inserting copies/loads.
4771   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4772        i != e;
4773        ++i) {
4774     CCValAssign &VA = ArgLocs[i];
4775     SDValue Arg = OutVals[i];
4776     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4777
4778     if (Flags.isByVal()) {
4779       // Argument is an aggregate which is passed by value, thus we need to
4780       // create a copy of it in the local variable space of the current stack
4781       // frame (which is the stack frame of the caller) and pass the address of
4782       // this copy to the callee.
4783       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4784       CCValAssign &ByValVA = ByValArgLocs[j++];
4785       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4786
4787       // Memory reserved in the local variable space of the callers stack frame.
4788       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4789
4790       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4791       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4792                            StackPtr, PtrOff);
4793
4794       // Create a copy of the argument in the local area of the current
4795       // stack frame.
4796       SDValue MemcpyCall =
4797         CreateCopyOfByValArgument(Arg, PtrOff,
4798                                   CallSeqStart.getNode()->getOperand(0),
4799                                   Flags, DAG, dl);
4800
4801       // This must go outside the CALLSEQ_START..END.
4802       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4803                            CallSeqStart.getNode()->getOperand(1),
4804                            SDLoc(MemcpyCall));
4805       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4806                              NewCallSeqStart.getNode());
4807       Chain = CallSeqStart = NewCallSeqStart;
4808
4809       // Pass the address of the aggregate copy on the stack either in a
4810       // physical register or in the parameter list area of the current stack
4811       // frame to the callee.
4812       Arg = PtrOff;
4813     }
4814
4815     if (VA.isRegLoc()) {
4816       if (Arg.getValueType() == MVT::i1)
4817         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4818
4819       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4820       // Put argument in a physical register.
4821       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4822     } else {
4823       // Put argument in the parameter list area of the current stack frame.
4824       assert(VA.isMemLoc());
4825       unsigned LocMemOffset = VA.getLocMemOffset();
4826
4827       if (!isTailCall) {
4828         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4829         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4830                              StackPtr, PtrOff);
4831
4832         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4833                                            MachinePointerInfo(),
4834                                            false, false, 0));
4835       } else {
4836         // Calculate and remember argument location.
4837         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4838                                  TailCallArguments);
4839       }
4840     }
4841   }
4842
4843   if (!MemOpChains.empty())
4844     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4845
4846   // Build a sequence of copy-to-reg nodes chained together with token chain
4847   // and flag operands which copy the outgoing args into the appropriate regs.
4848   SDValue InFlag;
4849   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4850     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4851                              RegsToPass[i].second, InFlag);
4852     InFlag = Chain.getValue(1);
4853   }
4854
4855   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4856   // registers.
4857   if (isVarArg) {
4858     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4859     SDValue Ops[] = { Chain, InFlag };
4860
4861     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4862                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4863
4864     InFlag = Chain.getValue(1);
4865   }
4866
4867   if (isTailCall)
4868     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
4869                     TailCallArguments);
4870
4871   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
4872                     /* unused except on PPC64 ELFv1 */ false, DAG,
4873                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4874                     NumBytes, Ins, InVals, CS);
4875 }
4876
4877 // Copy an argument into memory, being careful to do this outside the
4878 // call sequence for the call to which the argument belongs.
4879 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4880     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4881     SelectionDAG &DAG, const SDLoc &dl) const {
4882   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4883                         CallSeqStart.getNode()->getOperand(0),
4884                         Flags, DAG, dl);
4885   // The MEMCPY 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   return NewCallSeqStart;
4892 }
4893
4894 SDValue PPCTargetLowering::LowerCall_64SVR4(
4895     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4896     bool isTailCall, bool isPatchPoint,
4897     const SmallVectorImpl<ISD::OutputArg> &Outs,
4898     const SmallVectorImpl<SDValue> &OutVals,
4899     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4900     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4901     ImmutableCallSite *CS) const {
4902
4903   bool isELFv2ABI = Subtarget.isELFv2ABI();
4904   bool isLittleEndian = Subtarget.isLittleEndian();
4905   unsigned NumOps = Outs.size();
4906   bool hasNest = false;
4907   bool IsSibCall = false;
4908
4909   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4910   unsigned PtrByteSize = 8;
4911
4912   MachineFunction &MF = DAG.getMachineFunction();
4913
4914   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
4915     IsSibCall = true;
4916
4917   // Mark this function as potentially containing a function that contains a
4918   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4919   // and restoring the callers stack pointer in this functions epilog. This is
4920   // done because by tail calling the called function might overwrite the value
4921   // in this function's (MF) stack pointer stack slot 0(SP).
4922   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4923       CallConv == CallingConv::Fast)
4924     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4925
4926   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4927          "fastcc not supported on varargs functions");
4928
4929   // Count how many bytes are to be pushed on the stack, including the linkage
4930   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4931   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4932   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4933   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4934   unsigned NumBytes = LinkageSize;
4935   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4936   unsigned &QFPR_idx = FPR_idx;
4937
4938   static const MCPhysReg GPR[] = {
4939     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4940     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4941   };
4942   static const MCPhysReg VR[] = {
4943     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4944     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4945   };
4946   static const MCPhysReg VSRH[] = {
4947     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4948     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4949   };
4950
4951   const unsigned NumGPRs = array_lengthof(GPR);
4952   const unsigned NumFPRs = 13;
4953   const unsigned NumVRs  = array_lengthof(VR);
4954   const unsigned NumQFPRs = NumFPRs;
4955
4956   // When using the fast calling convention, we don't provide backing for
4957   // arguments that will be in registers.
4958   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4959
4960   // Add up all the space actually used.
4961   for (unsigned i = 0; i != NumOps; ++i) {
4962     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4963     EVT ArgVT = Outs[i].VT;
4964     EVT OrigVT = Outs[i].ArgVT;
4965
4966     if (Flags.isNest())
4967       continue;
4968
4969     if (CallConv == CallingConv::Fast) {
4970       if (Flags.isByVal())
4971         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4972       else
4973         switch (ArgVT.getSimpleVT().SimpleTy) {
4974         default: llvm_unreachable("Unexpected ValueType for argument!");
4975         case MVT::i1:
4976         case MVT::i32:
4977         case MVT::i64:
4978           if (++NumGPRsUsed <= NumGPRs)
4979             continue;
4980           break;
4981         case MVT::v4i32:
4982         case MVT::v8i16:
4983         case MVT::v16i8:
4984         case MVT::v2f64:
4985         case MVT::v2i64:
4986         case MVT::v1i128:
4987           if (++NumVRsUsed <= NumVRs)
4988             continue;
4989           break;
4990         case MVT::v4f32:
4991           // When using QPX, this is handled like a FP register, otherwise, it
4992           // is an Altivec register.
4993           if (Subtarget.hasQPX()) {
4994             if (++NumFPRsUsed <= NumFPRs)
4995               continue;
4996           } else {
4997             if (++NumVRsUsed <= NumVRs)
4998               continue;
4999           }
5000           break;
5001         case MVT::f32:
5002         case MVT::f64:
5003         case MVT::v4f64: // QPX
5004         case MVT::v4i1:  // QPX
5005           if (++NumFPRsUsed <= NumFPRs)
5006             continue;
5007           break;
5008         }
5009     }
5010
5011     /* Respect alignment of argument on the stack.  */
5012     unsigned Align =
5013       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5014     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5015
5016     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5017     if (Flags.isInConsecutiveRegsLast())
5018       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5019   }
5020
5021   unsigned NumBytesActuallyUsed = NumBytes;
5022
5023   // The prolog code of the callee may store up to 8 GPR argument registers to
5024   // the stack, allowing va_start to index over them in memory if its varargs.
5025   // Because we cannot tell if this is needed on the caller side, we have to
5026   // conservatively assume that it is needed.  As such, make sure we have at
5027   // least enough stack space for the caller to store the 8 GPRs.
5028   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5029   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5030
5031   // Tail call needs the stack to be aligned.
5032   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5033       CallConv == CallingConv::Fast)
5034     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5035
5036   int SPDiff = 0;
5037
5038   // Calculate by how many bytes the stack has to be adjusted in case of tail
5039   // call optimization.
5040   if (!IsSibCall)
5041     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5042
5043   // To protect arguments on the stack from being clobbered in a tail call,
5044   // force all the loads to happen before doing any other lowering.
5045   if (isTailCall)
5046     Chain = DAG.getStackArgumentTokenFactor(Chain);
5047
5048   // Adjust the stack pointer for the new arguments...
5049   // These operations are automatically eliminated by the prolog/epilog pass
5050   if (!IsSibCall)
5051     Chain = DAG.getCALLSEQ_START(Chain,
5052                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5053   SDValue CallSeqStart = Chain;
5054
5055   // Load the return address and frame pointer so it can be move somewhere else
5056   // later.
5057   SDValue LROp, FPOp;
5058   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5059
5060   // Set up a copy of the stack pointer for use loading and storing any
5061   // arguments that may not fit in the registers available for argument
5062   // passing.
5063   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5064
5065   // Figure out which arguments are going to go in registers, and which in
5066   // memory.  Also, if this is a vararg function, floating point operations
5067   // must be stored to our stack, and loaded into integer regs as well, if
5068   // any integer regs are available for argument passing.
5069   unsigned ArgOffset = LinkageSize;
5070
5071   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5072   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5073
5074   SmallVector<SDValue, 8> MemOpChains;
5075   for (unsigned i = 0; i != NumOps; ++i) {
5076     SDValue Arg = OutVals[i];
5077     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5078     EVT ArgVT = Outs[i].VT;
5079     EVT OrigVT = Outs[i].ArgVT;
5080
5081     // PtrOff will be used to store the current argument to the stack if a
5082     // register cannot be found for it.
5083     SDValue PtrOff;
5084
5085     // We re-align the argument offset for each argument, except when using the
5086     // fast calling convention, when we need to make sure we do that only when
5087     // we'll actually use a stack slot.
5088     auto ComputePtrOff = [&]() {
5089       /* Respect alignment of argument on the stack.  */
5090       unsigned Align =
5091         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5092       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5093
5094       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5095
5096       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5097     };
5098
5099     if (CallConv != CallingConv::Fast) {
5100       ComputePtrOff();
5101
5102       /* Compute GPR index associated with argument offset.  */
5103       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5104       GPR_idx = std::min(GPR_idx, NumGPRs);
5105     }
5106
5107     // Promote integers to 64-bit values.
5108     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5109       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5110       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5111       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5112     }
5113
5114     // FIXME memcpy is used way more than necessary.  Correctness first.
5115     // Note: "by value" is code for passing a structure by value, not
5116     // basic types.
5117     if (Flags.isByVal()) {
5118       // Note: Size includes alignment padding, so
5119       //   struct x { short a; char b; }
5120       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5121       // These are the proper values we need for right-justifying the
5122       // aggregate in a parameter register.
5123       unsigned Size = Flags.getByValSize();
5124
5125       // An empty aggregate parameter takes up no storage and no
5126       // registers.
5127       if (Size == 0)
5128         continue;
5129
5130       if (CallConv == CallingConv::Fast)
5131         ComputePtrOff();
5132
5133       // All aggregates smaller than 8 bytes must be passed right-justified.
5134       if (Size==1 || Size==2 || Size==4) {
5135         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5136         if (GPR_idx != NumGPRs) {
5137           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5138                                         MachinePointerInfo(), VT,
5139                                         false, false, false, 0);
5140           MemOpChains.push_back(Load.getValue(1));
5141           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5142
5143           ArgOffset += PtrByteSize;
5144           continue;
5145         }
5146       }
5147
5148       if (GPR_idx == NumGPRs && Size < 8) {
5149         SDValue AddPtr = PtrOff;
5150         if (!isLittleEndian) {
5151           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5152                                           PtrOff.getValueType());
5153           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5154         }
5155         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5156                                                           CallSeqStart,
5157                                                           Flags, DAG, dl);
5158         ArgOffset += PtrByteSize;
5159         continue;
5160       }
5161       // Copy entire object into memory.  There are cases where gcc-generated
5162       // code assumes it is there, even if it could be put entirely into
5163       // registers.  (This is not what the doc says.)
5164
5165       // FIXME: The above statement is likely due to a misunderstanding of the
5166       // documents.  All arguments must be copied into the parameter area BY
5167       // THE CALLEE in the event that the callee takes the address of any
5168       // formal argument.  That has not yet been implemented.  However, it is
5169       // reasonable to use the stack area as a staging area for the register
5170       // load.
5171
5172       // Skip this for small aggregates, as we will use the same slot for a
5173       // right-justified copy, below.
5174       if (Size >= 8)
5175         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5176                                                           CallSeqStart,
5177                                                           Flags, DAG, dl);
5178
5179       // When a register is available, pass a small aggregate right-justified.
5180       if (Size < 8 && GPR_idx != NumGPRs) {
5181         // The easiest way to get this right-justified in a register
5182         // is to copy the structure into the rightmost portion of a
5183         // local variable slot, then load the whole slot into the
5184         // register.
5185         // FIXME: The memcpy seems to produce pretty awful code for
5186         // small aggregates, particularly for packed ones.
5187         // FIXME: It would be preferable to use the slot in the
5188         // parameter save area instead of a new local variable.
5189         SDValue AddPtr = PtrOff;
5190         if (!isLittleEndian) {
5191           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5192           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5193         }
5194         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5195                                                           CallSeqStart,
5196                                                           Flags, DAG, dl);
5197
5198         // Load the slot into the register.
5199         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5200                                    MachinePointerInfo(),
5201                                    false, false, false, 0);
5202         MemOpChains.push_back(Load.getValue(1));
5203         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5204
5205         // Done with this argument.
5206         ArgOffset += PtrByteSize;
5207         continue;
5208       }
5209
5210       // For aggregates larger than PtrByteSize, copy the pieces of the
5211       // object that fit into registers from the parameter save area.
5212       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5213         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5214         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5215         if (GPR_idx != NumGPRs) {
5216           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5217                                      MachinePointerInfo(),
5218                                      false, false, false, 0);
5219           MemOpChains.push_back(Load.getValue(1));
5220           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5221           ArgOffset += PtrByteSize;
5222         } else {
5223           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5224           break;
5225         }
5226       }
5227       continue;
5228     }
5229
5230     switch (Arg.getSimpleValueType().SimpleTy) {
5231     default: llvm_unreachable("Unexpected ValueType for argument!");
5232     case MVT::i1:
5233     case MVT::i32:
5234     case MVT::i64:
5235       if (Flags.isNest()) {
5236         // The 'nest' parameter, if any, is passed in R11.
5237         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5238         hasNest = true;
5239         break;
5240       }
5241
5242       // These can be scalar arguments or elements of an integer array type
5243       // passed directly.  Clang may use those instead of "byval" aggregate
5244       // types to avoid forcing arguments to memory unnecessarily.
5245       if (GPR_idx != NumGPRs) {
5246         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5247       } else {
5248         if (CallConv == CallingConv::Fast)
5249           ComputePtrOff();
5250
5251         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5252                          true, isTailCall, false, MemOpChains,
5253                          TailCallArguments, dl);
5254         if (CallConv == CallingConv::Fast)
5255           ArgOffset += PtrByteSize;
5256       }
5257       if (CallConv != CallingConv::Fast)
5258         ArgOffset += PtrByteSize;
5259       break;
5260     case MVT::f32:
5261     case MVT::f64: {
5262       // These can be scalar arguments or elements of a float array type
5263       // passed directly.  The latter are used to implement ELFv2 homogenous
5264       // float aggregates.
5265
5266       // Named arguments go into FPRs first, and once they overflow, the
5267       // remaining arguments go into GPRs and then the parameter save area.
5268       // Unnamed arguments for vararg functions always go to GPRs and
5269       // then the parameter save area.  For now, put all arguments to vararg
5270       // routines always in both locations (FPR *and* GPR or stack slot).
5271       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5272       bool NeededLoad = false;
5273
5274       // First load the argument into the next available FPR.
5275       if (FPR_idx != NumFPRs)
5276         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5277
5278       // Next, load the argument into GPR or stack slot if needed.
5279       if (!NeedGPROrStack)
5280         ;
5281       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5282         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5283         // once we support fp <-> gpr moves.
5284
5285         // In the non-vararg case, this can only ever happen in the
5286         // presence of f32 array types, since otherwise we never run
5287         // out of FPRs before running out of GPRs.
5288         SDValue ArgVal;
5289
5290         // Double values are always passed in a single GPR.
5291         if (Arg.getValueType() != MVT::f32) {
5292           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5293
5294         // Non-array float values are extended and passed in a GPR.
5295         } else if (!Flags.isInConsecutiveRegs()) {
5296           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5297           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5298
5299         // If we have an array of floats, we collect every odd element
5300         // together with its predecessor into one GPR.
5301         } else if (ArgOffset % PtrByteSize != 0) {
5302           SDValue Lo, Hi;
5303           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5304           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5305           if (!isLittleEndian)
5306             std::swap(Lo, Hi);
5307           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5308
5309         // The final element, if even, goes into the first half of a GPR.
5310         } else if (Flags.isInConsecutiveRegsLast()) {
5311           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5312           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5313           if (!isLittleEndian)
5314             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5315                                  DAG.getConstant(32, dl, MVT::i32));
5316
5317         // Non-final even elements are skipped; they will be handled
5318         // together the with subsequent argument on the next go-around.
5319         } else
5320           ArgVal = SDValue();
5321
5322         if (ArgVal.getNode())
5323           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5324       } else {
5325         if (CallConv == CallingConv::Fast)
5326           ComputePtrOff();
5327
5328         // Single-precision floating-point values are mapped to the
5329         // second (rightmost) word of the stack doubleword.
5330         if (Arg.getValueType() == MVT::f32 &&
5331             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5332           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5333           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5334         }
5335
5336         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5337                          true, isTailCall, false, MemOpChains,
5338                          TailCallArguments, dl);
5339
5340         NeededLoad = true;
5341       }
5342       // When passing an array of floats, the array occupies consecutive
5343       // space in the argument area; only round up to the next doubleword
5344       // at the end of the array.  Otherwise, each float takes 8 bytes.
5345       if (CallConv != CallingConv::Fast || NeededLoad) {
5346         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5347                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5348         if (Flags.isInConsecutiveRegsLast())
5349           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5350       }
5351       break;
5352     }
5353     case MVT::v4f32:
5354     case MVT::v4i32:
5355     case MVT::v8i16:
5356     case MVT::v16i8:
5357     case MVT::v2f64:
5358     case MVT::v2i64:
5359     case MVT::v1i128:
5360       if (!Subtarget.hasQPX()) {
5361       // These can be scalar arguments or elements of a vector array type
5362       // passed directly.  The latter are used to implement ELFv2 homogenous
5363       // vector aggregates.
5364
5365       // For a varargs call, named arguments go into VRs or on the stack as
5366       // usual; unnamed arguments always go to the stack or the corresponding
5367       // GPRs when within range.  For now, we always put the value in both
5368       // locations (or even all three).
5369       if (isVarArg) {
5370         // We could elide this store in the case where the object fits
5371         // entirely in R registers.  Maybe later.
5372         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5373                                      MachinePointerInfo(), false, false, 0);
5374         MemOpChains.push_back(Store);
5375         if (VR_idx != NumVRs) {
5376           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5377                                      MachinePointerInfo(),
5378                                      false, false, false, 0);
5379           MemOpChains.push_back(Load.getValue(1));
5380
5381           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5382                            Arg.getSimpleValueType() == MVT::v2i64) ?
5383                           VSRH[VR_idx] : VR[VR_idx];
5384           ++VR_idx;
5385
5386           RegsToPass.push_back(std::make_pair(VReg, Load));
5387         }
5388         ArgOffset += 16;
5389         for (unsigned i=0; i<16; i+=PtrByteSize) {
5390           if (GPR_idx == NumGPRs)
5391             break;
5392           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5393                                    DAG.getConstant(i, dl, PtrVT));
5394           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5395                                      false, false, false, 0);
5396           MemOpChains.push_back(Load.getValue(1));
5397           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5398         }
5399         break;
5400       }
5401
5402       // Non-varargs Altivec params go into VRs or on the stack.
5403       if (VR_idx != NumVRs) {
5404         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5405                          Arg.getSimpleValueType() == MVT::v2i64) ?
5406                         VSRH[VR_idx] : VR[VR_idx];
5407         ++VR_idx;
5408
5409         RegsToPass.push_back(std::make_pair(VReg, Arg));
5410       } else {
5411         if (CallConv == CallingConv::Fast)
5412           ComputePtrOff();
5413
5414         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5415                          true, isTailCall, true, MemOpChains,
5416                          TailCallArguments, dl);
5417         if (CallConv == CallingConv::Fast)
5418           ArgOffset += 16;
5419       }
5420
5421       if (CallConv != CallingConv::Fast)
5422         ArgOffset += 16;
5423       break;
5424       } // not QPX
5425
5426       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5427              "Invalid QPX parameter type");
5428
5429       /* fall through */
5430     case MVT::v4f64:
5431     case MVT::v4i1: {
5432       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5433       if (isVarArg) {
5434         // We could elide this store in the case where the object fits
5435         // entirely in R registers.  Maybe later.
5436         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5437                                      MachinePointerInfo(), false, false, 0);
5438         MemOpChains.push_back(Store);
5439         if (QFPR_idx != NumQFPRs) {
5440           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5441                                      Store, PtrOff, MachinePointerInfo(),
5442                                      false, false, false, 0);
5443           MemOpChains.push_back(Load.getValue(1));
5444           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5445         }
5446         ArgOffset += (IsF32 ? 16 : 32);
5447         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5448           if (GPR_idx == NumGPRs)
5449             break;
5450           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5451                                    DAG.getConstant(i, dl, PtrVT));
5452           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5453                                      false, false, false, 0);
5454           MemOpChains.push_back(Load.getValue(1));
5455           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5456         }
5457         break;
5458       }
5459
5460       // Non-varargs QPX params go into registers or on the stack.
5461       if (QFPR_idx != NumQFPRs) {
5462         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5463       } else {
5464         if (CallConv == CallingConv::Fast)
5465           ComputePtrOff();
5466
5467         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5468                          true, isTailCall, true, MemOpChains,
5469                          TailCallArguments, dl);
5470         if (CallConv == CallingConv::Fast)
5471           ArgOffset += (IsF32 ? 16 : 32);
5472       }
5473
5474       if (CallConv != CallingConv::Fast)
5475         ArgOffset += (IsF32 ? 16 : 32);
5476       break;
5477       }
5478     }
5479   }
5480
5481   assert(NumBytesActuallyUsed == ArgOffset);
5482   (void)NumBytesActuallyUsed;
5483
5484   if (!MemOpChains.empty())
5485     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5486
5487   // Check if this is an indirect call (MTCTR/BCTRL).
5488   // See PrepareCall() for more information about calls through function
5489   // pointers in the 64-bit SVR4 ABI.
5490   if (!isTailCall && !isPatchPoint &&
5491       !isFunctionGlobalAddress(Callee) &&
5492       !isa<ExternalSymbolSDNode>(Callee)) {
5493     // Load r2 into a virtual register and store it to the TOC save area.
5494     setUsesTOCBasePtr(DAG);
5495     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5496     // TOC save area offset.
5497     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5498     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5499     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5500     Chain = DAG.getStore(
5501         Val.getValue(1), dl, Val, AddPtr,
5502         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset),
5503         false, false, 0);
5504     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5505     // This does not mean the MTCTR instruction must use R12; it's easier
5506     // to model this as an extra parameter, so do that.
5507     if (isELFv2ABI && !isPatchPoint)
5508       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5509   }
5510
5511   // Build a sequence of copy-to-reg nodes chained together with token chain
5512   // and flag operands which copy the outgoing args into the appropriate regs.
5513   SDValue InFlag;
5514   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5515     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5516                              RegsToPass[i].second, InFlag);
5517     InFlag = Chain.getValue(1);
5518   }
5519
5520   if (isTailCall && !IsSibCall)
5521     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5522                     TailCallArguments);
5523
5524   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5525                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5526                     SPDiff, NumBytes, Ins, InVals, CS);
5527 }
5528
5529 SDValue PPCTargetLowering::LowerCall_Darwin(
5530     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5531     bool isTailCall, bool isPatchPoint,
5532     const SmallVectorImpl<ISD::OutputArg> &Outs,
5533     const SmallVectorImpl<SDValue> &OutVals,
5534     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5535     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5536     ImmutableCallSite *CS) const {
5537
5538   unsigned NumOps = Outs.size();
5539
5540   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5541   bool isPPC64 = PtrVT == MVT::i64;
5542   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5543
5544   MachineFunction &MF = DAG.getMachineFunction();
5545
5546   // Mark this function as potentially containing a function that contains a
5547   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5548   // and restoring the callers stack pointer in this functions epilog. This is
5549   // done because by tail calling the called function might overwrite the value
5550   // in this function's (MF) stack pointer stack slot 0(SP).
5551   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5552       CallConv == CallingConv::Fast)
5553     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5554
5555   // Count how many bytes are to be pushed on the stack, including the linkage
5556   // area, and parameter passing area.  We start with 24/48 bytes, which is
5557   // prereserved space for [SP][CR][LR][3 x unused].
5558   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5559   unsigned NumBytes = LinkageSize;
5560
5561   // Add up all the space actually used.
5562   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5563   // they all go in registers, but we must reserve stack space for them for
5564   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5565   // assigned stack space in order, with padding so Altivec parameters are
5566   // 16-byte aligned.
5567   unsigned nAltivecParamsAtEnd = 0;
5568   for (unsigned i = 0; i != NumOps; ++i) {
5569     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5570     EVT ArgVT = Outs[i].VT;
5571     // Varargs Altivec parameters are padded to a 16 byte boundary.
5572     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5573         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5574         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5575       if (!isVarArg && !isPPC64) {
5576         // Non-varargs Altivec parameters go after all the non-Altivec
5577         // parameters; handle those later so we know how much padding we need.
5578         nAltivecParamsAtEnd++;
5579         continue;
5580       }
5581       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5582       NumBytes = ((NumBytes+15)/16)*16;
5583     }
5584     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5585   }
5586
5587   // Allow for Altivec parameters at the end, if needed.
5588   if (nAltivecParamsAtEnd) {
5589     NumBytes = ((NumBytes+15)/16)*16;
5590     NumBytes += 16*nAltivecParamsAtEnd;
5591   }
5592
5593   // The prolog code of the callee may store up to 8 GPR argument registers to
5594   // the stack, allowing va_start to index over them in memory if its varargs.
5595   // Because we cannot tell if this is needed on the caller side, we have to
5596   // conservatively assume that it is needed.  As such, make sure we have at
5597   // least enough stack space for the caller to store the 8 GPRs.
5598   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5599
5600   // Tail call needs the stack to be aligned.
5601   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5602       CallConv == CallingConv::Fast)
5603     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5604
5605   // Calculate by how many bytes the stack has to be adjusted in case of tail
5606   // call optimization.
5607   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5608
5609   // To protect arguments on the stack from being clobbered in a tail call,
5610   // force all the loads to happen before doing any other lowering.
5611   if (isTailCall)
5612     Chain = DAG.getStackArgumentTokenFactor(Chain);
5613
5614   // Adjust the stack pointer for the new arguments...
5615   // These operations are automatically eliminated by the prolog/epilog pass
5616   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5617                                dl);
5618   SDValue CallSeqStart = Chain;
5619
5620   // Load the return address and frame pointer so it can be move somewhere else
5621   // later.
5622   SDValue LROp, FPOp;
5623   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5624
5625   // Set up a copy of the stack pointer for use loading and storing any
5626   // arguments that may not fit in the registers available for argument
5627   // passing.
5628   SDValue StackPtr;
5629   if (isPPC64)
5630     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5631   else
5632     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5633
5634   // Figure out which arguments are going to go in registers, and which in
5635   // memory.  Also, if this is a vararg function, floating point operations
5636   // must be stored to our stack, and loaded into integer regs as well, if
5637   // any integer regs are available for argument passing.
5638   unsigned ArgOffset = LinkageSize;
5639   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5640
5641   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5642     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5643     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5644   };
5645   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5646     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5647     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5648   };
5649   static const MCPhysReg VR[] = {
5650     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5651     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5652   };
5653   const unsigned NumGPRs = array_lengthof(GPR_32);
5654   const unsigned NumFPRs = 13;
5655   const unsigned NumVRs  = array_lengthof(VR);
5656
5657   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5658
5659   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5660   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5661
5662   SmallVector<SDValue, 8> MemOpChains;
5663   for (unsigned i = 0; i != NumOps; ++i) {
5664     SDValue Arg = OutVals[i];
5665     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5666
5667     // PtrOff will be used to store the current argument to the stack if a
5668     // register cannot be found for it.
5669     SDValue PtrOff;
5670
5671     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5672
5673     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5674
5675     // On PPC64, promote integers to 64-bit values.
5676     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5677       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5678       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5679       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5680     }
5681
5682     // FIXME memcpy is used way more than necessary.  Correctness first.
5683     // Note: "by value" is code for passing a structure by value, not
5684     // basic types.
5685     if (Flags.isByVal()) {
5686       unsigned Size = Flags.getByValSize();
5687       // Very small objects are passed right-justified.  Everything else is
5688       // passed left-justified.
5689       if (Size==1 || Size==2) {
5690         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5691         if (GPR_idx != NumGPRs) {
5692           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5693                                         MachinePointerInfo(), VT,
5694                                         false, false, false, 0);
5695           MemOpChains.push_back(Load.getValue(1));
5696           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5697
5698           ArgOffset += PtrByteSize;
5699         } else {
5700           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5701                                           PtrOff.getValueType());
5702           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5703           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5704                                                             CallSeqStart,
5705                                                             Flags, DAG, dl);
5706           ArgOffset += PtrByteSize;
5707         }
5708         continue;
5709       }
5710       // Copy entire object into memory.  There are cases where gcc-generated
5711       // code assumes it is there, even if it could be put entirely into
5712       // registers.  (This is not what the doc says.)
5713       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5714                                                         CallSeqStart,
5715                                                         Flags, DAG, dl);
5716
5717       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5718       // copy the pieces of the object that fit into registers from the
5719       // parameter save area.
5720       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5721         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5722         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5723         if (GPR_idx != NumGPRs) {
5724           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5725                                      MachinePointerInfo(),
5726                                      false, false, false, 0);
5727           MemOpChains.push_back(Load.getValue(1));
5728           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5729           ArgOffset += PtrByteSize;
5730         } else {
5731           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5732           break;
5733         }
5734       }
5735       continue;
5736     }
5737
5738     switch (Arg.getSimpleValueType().SimpleTy) {
5739     default: llvm_unreachable("Unexpected ValueType for argument!");
5740     case MVT::i1:
5741     case MVT::i32:
5742     case MVT::i64:
5743       if (GPR_idx != NumGPRs) {
5744         if (Arg.getValueType() == MVT::i1)
5745           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5746
5747         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5748       } else {
5749         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5750                          isPPC64, isTailCall, false, MemOpChains,
5751                          TailCallArguments, dl);
5752       }
5753       ArgOffset += PtrByteSize;
5754       break;
5755     case MVT::f32:
5756     case MVT::f64:
5757       if (FPR_idx != NumFPRs) {
5758         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5759
5760         if (isVarArg) {
5761           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5762                                        MachinePointerInfo(), false, false, 0);
5763           MemOpChains.push_back(Store);
5764
5765           // Float varargs are always shadowed in available integer registers
5766           if (GPR_idx != NumGPRs) {
5767             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5768                                        MachinePointerInfo(), false, false,
5769                                        false, 0);
5770             MemOpChains.push_back(Load.getValue(1));
5771             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5772           }
5773           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5774             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5775             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5776             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5777                                        MachinePointerInfo(),
5778                                        false, false, false, 0);
5779             MemOpChains.push_back(Load.getValue(1));
5780             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5781           }
5782         } else {
5783           // If we have any FPRs remaining, we may also have GPRs remaining.
5784           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5785           // GPRs.
5786           if (GPR_idx != NumGPRs)
5787             ++GPR_idx;
5788           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5789               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5790             ++GPR_idx;
5791         }
5792       } else
5793         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5794                          isPPC64, isTailCall, false, MemOpChains,
5795                          TailCallArguments, dl);
5796       if (isPPC64)
5797         ArgOffset += 8;
5798       else
5799         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5800       break;
5801     case MVT::v4f32:
5802     case MVT::v4i32:
5803     case MVT::v8i16:
5804     case MVT::v16i8:
5805       if (isVarArg) {
5806         // These go aligned on the stack, or in the corresponding R registers
5807         // when within range.  The Darwin PPC ABI doc claims they also go in
5808         // V registers; in fact gcc does this only for arguments that are
5809         // prototyped, not for those that match the ...  We do it for all
5810         // arguments, seems to work.
5811         while (ArgOffset % 16 !=0) {
5812           ArgOffset += PtrByteSize;
5813           if (GPR_idx != NumGPRs)
5814             GPR_idx++;
5815         }
5816         // We could elide this store in the case where the object fits
5817         // entirely in R registers.  Maybe later.
5818         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5819                              DAG.getConstant(ArgOffset, dl, PtrVT));
5820         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5821                                      MachinePointerInfo(), false, false, 0);
5822         MemOpChains.push_back(Store);
5823         if (VR_idx != NumVRs) {
5824           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5825                                      MachinePointerInfo(),
5826                                      false, false, false, 0);
5827           MemOpChains.push_back(Load.getValue(1));
5828           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5829         }
5830         ArgOffset += 16;
5831         for (unsigned i=0; i<16; i+=PtrByteSize) {
5832           if (GPR_idx == NumGPRs)
5833             break;
5834           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5835                                    DAG.getConstant(i, dl, PtrVT));
5836           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5837                                      false, false, false, 0);
5838           MemOpChains.push_back(Load.getValue(1));
5839           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5840         }
5841         break;
5842       }
5843
5844       // Non-varargs Altivec params generally go in registers, but have
5845       // stack space allocated at the end.
5846       if (VR_idx != NumVRs) {
5847         // Doesn't have GPR space allocated.
5848         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5849       } else if (nAltivecParamsAtEnd==0) {
5850         // We are emitting Altivec params in order.
5851         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5852                          isPPC64, isTailCall, true, MemOpChains,
5853                          TailCallArguments, dl);
5854         ArgOffset += 16;
5855       }
5856       break;
5857     }
5858   }
5859   // If all Altivec parameters fit in registers, as they usually do,
5860   // they get stack space following the non-Altivec parameters.  We
5861   // don't track this here because nobody below needs it.
5862   // If there are more Altivec parameters than fit in registers emit
5863   // the stores here.
5864   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5865     unsigned j = 0;
5866     // Offset is aligned; skip 1st 12 params which go in V registers.
5867     ArgOffset = ((ArgOffset+15)/16)*16;
5868     ArgOffset += 12*16;
5869     for (unsigned i = 0; i != NumOps; ++i) {
5870       SDValue Arg = OutVals[i];
5871       EVT ArgType = Outs[i].VT;
5872       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5873           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5874         if (++j > NumVRs) {
5875           SDValue PtrOff;
5876           // We are emitting Altivec params in order.
5877           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5878                            isPPC64, isTailCall, true, MemOpChains,
5879                            TailCallArguments, dl);
5880           ArgOffset += 16;
5881         }
5882       }
5883     }
5884   }
5885
5886   if (!MemOpChains.empty())
5887     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5888
5889   // On Darwin, R12 must contain the address of an indirect callee.  This does
5890   // not mean the MTCTR instruction must use R12; it's easier to model this as
5891   // an extra parameter, so do that.
5892   if (!isTailCall &&
5893       !isFunctionGlobalAddress(Callee) &&
5894       !isa<ExternalSymbolSDNode>(Callee) &&
5895       !isBLACompatibleAddress(Callee, DAG))
5896     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5897                                                    PPC::R12), Callee));
5898
5899   // Build a sequence of copy-to-reg nodes chained together with token chain
5900   // and flag operands which copy the outgoing args into the appropriate regs.
5901   SDValue InFlag;
5902   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5903     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5904                              RegsToPass[i].second, InFlag);
5905     InFlag = Chain.getValue(1);
5906   }
5907
5908   if (isTailCall)
5909     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5910                     TailCallArguments);
5911
5912   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5913                     /* unused except on PPC64 ELFv1 */ false, DAG,
5914                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5915                     NumBytes, Ins, InVals, CS);
5916 }
5917
5918 bool
5919 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5920                                   MachineFunction &MF, bool isVarArg,
5921                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5922                                   LLVMContext &Context) const {
5923   SmallVector<CCValAssign, 16> RVLocs;
5924   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5925   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5926 }
5927
5928 SDValue
5929 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5930                                bool isVarArg,
5931                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5932                                const SmallVectorImpl<SDValue> &OutVals,
5933                                const SDLoc &dl, SelectionDAG &DAG) const {
5934
5935   SmallVector<CCValAssign, 16> RVLocs;
5936   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5937                  *DAG.getContext());
5938   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5939
5940   SDValue Flag;
5941   SmallVector<SDValue, 4> RetOps(1, Chain);
5942
5943   // Copy the result values into the output registers.
5944   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5945     CCValAssign &VA = RVLocs[i];
5946     assert(VA.isRegLoc() && "Can only return in registers!");
5947
5948     SDValue Arg = OutVals[i];
5949
5950     switch (VA.getLocInfo()) {
5951     default: llvm_unreachable("Unknown loc info!");
5952     case CCValAssign::Full: break;
5953     case CCValAssign::AExt:
5954       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5955       break;
5956     case CCValAssign::ZExt:
5957       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5958       break;
5959     case CCValAssign::SExt:
5960       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5961       break;
5962     }
5963
5964     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5965     Flag = Chain.getValue(1);
5966     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5967   }
5968
5969   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
5970   const MCPhysReg *I =
5971     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5972   if (I) {
5973     for (; *I; ++I) {
5974
5975       if (PPC::G8RCRegClass.contains(*I))
5976         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5977       else if (PPC::F8RCRegClass.contains(*I))
5978         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
5979       else if (PPC::CRRCRegClass.contains(*I))
5980         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
5981       else if (PPC::VRRCRegClass.contains(*I))
5982         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
5983       else
5984         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
5985     }
5986   }
5987
5988   RetOps[0] = Chain;  // Update chain.
5989
5990   // Add the flag if we have it.
5991   if (Flag.getNode())
5992     RetOps.push_back(Flag);
5993
5994   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5995 }
5996
5997 SDValue
5998 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
5999                                                 SelectionDAG &DAG) const {
6000   SDLoc dl(Op);
6001
6002   // Get the corect type for integers.
6003   EVT IntVT = Op.getValueType();
6004
6005   // Get the inputs.
6006   SDValue Chain = Op.getOperand(0);
6007   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6008   // Build a DYNAREAOFFSET node.
6009   SDValue Ops[2] = {Chain, FPSIdx};
6010   SDVTList VTs = DAG.getVTList(IntVT);
6011   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6012 }
6013
6014 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6015                                              SelectionDAG &DAG) const {
6016   // When we pop the dynamic allocation we need to restore the SP link.
6017   SDLoc dl(Op);
6018
6019   // Get the corect type for pointers.
6020   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6021
6022   // Construct the stack pointer operand.
6023   bool isPPC64 = Subtarget.isPPC64();
6024   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6025   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6026
6027   // Get the operands for the STACKRESTORE.
6028   SDValue Chain = Op.getOperand(0);
6029   SDValue SaveSP = Op.getOperand(1);
6030
6031   // Load the old link SP.
6032   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
6033                                    MachinePointerInfo(),
6034                                    false, false, false, 0);
6035
6036   // Restore the stack pointer.
6037   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6038
6039   // Store the old link SP.
6040   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
6041                       false, false, 0);
6042 }
6043
6044 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6045   MachineFunction &MF = DAG.getMachineFunction();
6046   bool isPPC64 = Subtarget.isPPC64();
6047   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6048
6049   // Get current frame pointer save index.  The users of this index will be
6050   // primarily DYNALLOC instructions.
6051   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6052   int RASI = FI->getReturnAddrSaveIndex();
6053
6054   // If the frame pointer save index hasn't been defined yet.
6055   if (!RASI) {
6056     // Find out what the fix offset of the frame pointer save area.
6057     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6058     // Allocate the frame index for frame pointer save area.
6059     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6060     // Save the result.
6061     FI->setReturnAddrSaveIndex(RASI);
6062   }
6063   return DAG.getFrameIndex(RASI, PtrVT);
6064 }
6065
6066 SDValue
6067 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6068   MachineFunction &MF = DAG.getMachineFunction();
6069   bool isPPC64 = Subtarget.isPPC64();
6070   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6071
6072   // Get current frame pointer save index.  The users of this index will be
6073   // primarily DYNALLOC instructions.
6074   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6075   int FPSI = FI->getFramePointerSaveIndex();
6076
6077   // If the frame pointer save index hasn't been defined yet.
6078   if (!FPSI) {
6079     // Find out what the fix offset of the frame pointer save area.
6080     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6081     // Allocate the frame index for frame pointer save area.
6082     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6083     // Save the result.
6084     FI->setFramePointerSaveIndex(FPSI);
6085   }
6086   return DAG.getFrameIndex(FPSI, PtrVT);
6087 }
6088
6089 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6090                                                    SelectionDAG &DAG) const {
6091   // Get the inputs.
6092   SDValue Chain = Op.getOperand(0);
6093   SDValue Size  = Op.getOperand(1);
6094   SDLoc dl(Op);
6095
6096   // Get the corect type for pointers.
6097   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6098   // Negate the size.
6099   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6100                                 DAG.getConstant(0, dl, PtrVT), Size);
6101   // Construct a node for the frame pointer save index.
6102   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6103   // Build a DYNALLOC node.
6104   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6105   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6106   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6107 }
6108
6109 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6110                                                SelectionDAG &DAG) const {
6111   SDLoc DL(Op);
6112   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6113                      DAG.getVTList(MVT::i32, MVT::Other),
6114                      Op.getOperand(0), Op.getOperand(1));
6115 }
6116
6117 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6118                                                 SelectionDAG &DAG) const {
6119   SDLoc DL(Op);
6120   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6121                      Op.getOperand(0), Op.getOperand(1));
6122 }
6123
6124 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6125   if (Op.getValueType().isVector())
6126     return LowerVectorLoad(Op, DAG);
6127
6128   assert(Op.getValueType() == MVT::i1 &&
6129          "Custom lowering only for i1 loads");
6130
6131   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6132
6133   SDLoc dl(Op);
6134   LoadSDNode *LD = cast<LoadSDNode>(Op);
6135
6136   SDValue Chain = LD->getChain();
6137   SDValue BasePtr = LD->getBasePtr();
6138   MachineMemOperand *MMO = LD->getMemOperand();
6139
6140   SDValue NewLD =
6141       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6142                      BasePtr, MVT::i8, MMO);
6143   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6144
6145   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6146   return DAG.getMergeValues(Ops, dl);
6147 }
6148
6149 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6150   if (Op.getOperand(1).getValueType().isVector())
6151     return LowerVectorStore(Op, DAG);
6152
6153   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6154          "Custom lowering only for i1 stores");
6155
6156   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6157
6158   SDLoc dl(Op);
6159   StoreSDNode *ST = cast<StoreSDNode>(Op);
6160
6161   SDValue Chain = ST->getChain();
6162   SDValue BasePtr = ST->getBasePtr();
6163   SDValue Value = ST->getValue();
6164   MachineMemOperand *MMO = ST->getMemOperand();
6165
6166   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6167                       Value);
6168   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6169 }
6170
6171 // FIXME: Remove this once the ANDI glue bug is fixed:
6172 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6173   assert(Op.getValueType() == MVT::i1 &&
6174          "Custom lowering only for i1 results");
6175
6176   SDLoc DL(Op);
6177   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6178                      Op.getOperand(0));
6179 }
6180
6181 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6182 /// possible.
6183 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6184   // Not FP? Not a fsel.
6185   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6186       !Op.getOperand(2).getValueType().isFloatingPoint())
6187     return Op;
6188
6189   // We might be able to do better than this under some circumstances, but in
6190   // general, fsel-based lowering of select is a finite-math-only optimization.
6191   // For more information, see section F.3 of the 2.06 ISA specification.
6192   if (!DAG.getTarget().Options.NoInfsFPMath ||
6193       !DAG.getTarget().Options.NoNaNsFPMath)
6194     return Op;
6195   // TODO: Propagate flags from the select rather than global settings.
6196   SDNodeFlags Flags;
6197   Flags.setNoInfs(true);
6198   Flags.setNoNaNs(true);
6199
6200   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6201
6202   EVT ResVT = Op.getValueType();
6203   EVT CmpVT = Op.getOperand(0).getValueType();
6204   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6205   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6206   SDLoc dl(Op);
6207
6208   // If the RHS of the comparison is a 0.0, we don't need to do the
6209   // subtraction at all.
6210   SDValue Sel1;
6211   if (isFloatingPointZero(RHS))
6212     switch (CC) {
6213     default: break;       // SETUO etc aren't handled by fsel.
6214     case ISD::SETNE:
6215       std::swap(TV, FV);
6216     case ISD::SETEQ:
6217       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6218         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6219       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6220       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6221         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6222       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6223                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6224     case ISD::SETULT:
6225     case ISD::SETLT:
6226       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6227     case ISD::SETOGE:
6228     case ISD::SETGE:
6229       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6230         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6231       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6232     case ISD::SETUGT:
6233     case ISD::SETGT:
6234       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6235     case ISD::SETOLE:
6236     case ISD::SETLE:
6237       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6238         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6239       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6240                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6241     }
6242
6243   SDValue Cmp;
6244   switch (CC) {
6245   default: break;       // SETUO etc aren't handled by fsel.
6246   case ISD::SETNE:
6247     std::swap(TV, FV);
6248   case ISD::SETEQ:
6249     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6250     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6251       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6252     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6253     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6254       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6255     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6256                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6257   case ISD::SETULT:
6258   case ISD::SETLT:
6259     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6260     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6261       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6262     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6263   case ISD::SETOGE:
6264   case ISD::SETGE:
6265     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6266     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6267       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6268     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6269   case ISD::SETUGT:
6270   case ISD::SETGT:
6271     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6272     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6273       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6274     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6275   case ISD::SETOLE:
6276   case ISD::SETLE:
6277     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6278     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6279       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6280     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6281   }
6282   return Op;
6283 }
6284
6285 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6286                                                SelectionDAG &DAG,
6287                                                const SDLoc &dl) const {
6288   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6289   SDValue Src = Op.getOperand(0);
6290   if (Src.getValueType() == MVT::f32)
6291     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6292
6293   SDValue Tmp;
6294   switch (Op.getSimpleValueType().SimpleTy) {
6295   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6296   case MVT::i32:
6297     Tmp = DAG.getNode(
6298         Op.getOpcode() == ISD::FP_TO_SINT
6299             ? PPCISD::FCTIWZ
6300             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6301         dl, MVT::f64, Src);
6302     break;
6303   case MVT::i64:
6304     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6305            "i64 FP_TO_UINT is supported only with FPCVT");
6306     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6307                                                         PPCISD::FCTIDUZ,
6308                       dl, MVT::f64, Src);
6309     break;
6310   }
6311
6312   // Convert the FP value to an int value through memory.
6313   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6314     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6315   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6316   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6317   MachinePointerInfo MPI =
6318       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6319
6320   // Emit a store to the stack slot.
6321   SDValue Chain;
6322   if (i32Stack) {
6323     MachineFunction &MF = DAG.getMachineFunction();
6324     MachineMemOperand *MMO =
6325       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6326     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6327     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6328               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6329   } else
6330     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6331                          MPI, false, false, 0);
6332
6333   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6334   // add in a bias on big endian.
6335   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6336     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6337                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6338     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6339   }
6340
6341   RLI.Chain = Chain;
6342   RLI.Ptr = FIPtr;
6343   RLI.MPI = MPI;
6344 }
6345
6346 /// \brief Custom lowers floating point to integer conversions to use
6347 /// the direct move instructions available in ISA 2.07 to avoid the
6348 /// need for load/store combinations.
6349 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6350                                                     SelectionDAG &DAG,
6351                                                     const SDLoc &dl) const {
6352   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6353   SDValue Src = Op.getOperand(0);
6354
6355   if (Src.getValueType() == MVT::f32)
6356     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6357
6358   SDValue Tmp;
6359   switch (Op.getSimpleValueType().SimpleTy) {
6360   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6361   case MVT::i32:
6362     Tmp = DAG.getNode(
6363         Op.getOpcode() == ISD::FP_TO_SINT
6364             ? PPCISD::FCTIWZ
6365             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6366         dl, MVT::f64, Src);
6367     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6368     break;
6369   case MVT::i64:
6370     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6371            "i64 FP_TO_UINT is supported only with FPCVT");
6372     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6373                                                         PPCISD::FCTIDUZ,
6374                       dl, MVT::f64, Src);
6375     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6376     break;
6377   }
6378   return Tmp;
6379 }
6380
6381 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6382                                           const SDLoc &dl) const {
6383   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6384     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6385
6386   ReuseLoadInfo RLI;
6387   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6388
6389   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6390                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6391                      RLI.Ranges);
6392 }
6393
6394 // We're trying to insert a regular store, S, and then a load, L. If the
6395 // incoming value, O, is a load, we might just be able to have our load use the
6396 // address used by O. However, we don't know if anything else will store to
6397 // that address before we can load from it. To prevent this situation, we need
6398 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6399 // the same chain operand as O, we create a token factor from the chain results
6400 // of O and L, and we replace all uses of O's chain result with that token
6401 // factor (see spliceIntoChain below for this last part).
6402 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6403                                             ReuseLoadInfo &RLI,
6404                                             SelectionDAG &DAG,
6405                                             ISD::LoadExtType ET) const {
6406   SDLoc dl(Op);
6407   if (ET == ISD::NON_EXTLOAD &&
6408       (Op.getOpcode() == ISD::FP_TO_UINT ||
6409        Op.getOpcode() == ISD::FP_TO_SINT) &&
6410       isOperationLegalOrCustom(Op.getOpcode(),
6411                                Op.getOperand(0).getValueType())) {
6412
6413     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6414     return true;
6415   }
6416
6417   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6418   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6419       LD->isNonTemporal())
6420     return false;
6421   if (LD->getMemoryVT() != MemVT)
6422     return false;
6423
6424   RLI.Ptr = LD->getBasePtr();
6425   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6426     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6427            "Non-pre-inc AM on PPC?");
6428     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6429                           LD->getOffset());
6430   }
6431
6432   RLI.Chain = LD->getChain();
6433   RLI.MPI = LD->getPointerInfo();
6434   RLI.IsInvariant = LD->isInvariant();
6435   RLI.Alignment = LD->getAlignment();
6436   RLI.AAInfo = LD->getAAInfo();
6437   RLI.Ranges = LD->getRanges();
6438
6439   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6440   return true;
6441 }
6442
6443 // Given the head of the old chain, ResChain, insert a token factor containing
6444 // it and NewResChain, and make users of ResChain now be users of that token
6445 // factor.
6446 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6447                                         SDValue NewResChain,
6448                                         SelectionDAG &DAG) const {
6449   if (!ResChain)
6450     return;
6451
6452   SDLoc dl(NewResChain);
6453
6454   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6455                            NewResChain, DAG.getUNDEF(MVT::Other));
6456   assert(TF.getNode() != NewResChain.getNode() &&
6457          "A new TF really is required here");
6458
6459   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6460   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6461 }
6462
6463 /// \brief Analyze profitability of direct move
6464 /// prefer float load to int load plus direct move
6465 /// when there is no integer use of int load
6466 static bool directMoveIsProfitable(const SDValue &Op) {
6467   SDNode *Origin = Op.getOperand(0).getNode();
6468   if (Origin->getOpcode() != ISD::LOAD)
6469     return true;
6470
6471   for (SDNode::use_iterator UI = Origin->use_begin(),
6472                             UE = Origin->use_end();
6473        UI != UE; ++UI) {
6474
6475     // Only look at the users of the loaded value.
6476     if (UI.getUse().get().getResNo() != 0)
6477       continue;
6478
6479     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6480         UI->getOpcode() != ISD::UINT_TO_FP)
6481       return true;
6482   }
6483
6484   return false;
6485 }
6486
6487 /// \brief Custom lowers integer to floating point conversions to use
6488 /// the direct move instructions available in ISA 2.07 to avoid the
6489 /// need for load/store combinations.
6490 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6491                                                     SelectionDAG &DAG,
6492                                                     const SDLoc &dl) const {
6493   assert((Op.getValueType() == MVT::f32 ||
6494           Op.getValueType() == MVT::f64) &&
6495          "Invalid floating point type as target of conversion");
6496   assert(Subtarget.hasFPCVT() &&
6497          "Int to FP conversions with direct moves require FPCVT");
6498   SDValue FP;
6499   SDValue Src = Op.getOperand(0);
6500   bool SinglePrec = Op.getValueType() == MVT::f32;
6501   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6502   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6503   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6504                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6505
6506   if (WordInt) {
6507     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6508                      dl, MVT::f64, Src);
6509     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6510   }
6511   else {
6512     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6513     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6514   }
6515
6516   return FP;
6517 }
6518
6519 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6520                                           SelectionDAG &DAG) const {
6521   SDLoc dl(Op);
6522
6523   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6524     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6525       return SDValue();
6526
6527     SDValue Value = Op.getOperand(0);
6528     // The values are now known to be -1 (false) or 1 (true). To convert this
6529     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6530     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6531     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6532
6533     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6534
6535     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6536
6537     if (Op.getValueType() != MVT::v4f64)
6538       Value = DAG.getNode(ISD::FP_ROUND, dl,
6539                           Op.getValueType(), Value,
6540                           DAG.getIntPtrConstant(1, dl));
6541     return Value;
6542   }
6543
6544   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6545   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6546     return SDValue();
6547
6548   if (Op.getOperand(0).getValueType() == MVT::i1)
6549     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6550                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6551                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6552
6553   // If we have direct moves, we can do all the conversion, skip the store/load
6554   // however, without FPCVT we can't do most conversions.
6555   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6556       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6557     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6558
6559   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6560          "UINT_TO_FP is supported only with FPCVT");
6561
6562   // If we have FCFIDS, then use it when converting to single-precision.
6563   // Otherwise, convert to double-precision and then round.
6564   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6565                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6566                                                             : PPCISD::FCFIDS)
6567                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6568                                                             : PPCISD::FCFID);
6569   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6570                   ? MVT::f32
6571                   : MVT::f64;
6572
6573   if (Op.getOperand(0).getValueType() == MVT::i64) {
6574     SDValue SINT = Op.getOperand(0);
6575     // When converting to single-precision, we actually need to convert
6576     // to double-precision first and then round to single-precision.
6577     // To avoid double-rounding effects during that operation, we have
6578     // to prepare the input operand.  Bits that might be truncated when
6579     // converting to double-precision are replaced by a bit that won't
6580     // be lost at this stage, but is below the single-precision rounding
6581     // position.
6582     //
6583     // However, if -enable-unsafe-fp-math is in effect, accept double
6584     // rounding to avoid the extra overhead.
6585     if (Op.getValueType() == MVT::f32 &&
6586         !Subtarget.hasFPCVT() &&
6587         !DAG.getTarget().Options.UnsafeFPMath) {
6588
6589       // Twiddle input to make sure the low 11 bits are zero.  (If this
6590       // is the case, we are guaranteed the value will fit into the 53 bit
6591       // mantissa of an IEEE double-precision value without rounding.)
6592       // If any of those low 11 bits were not zero originally, make sure
6593       // bit 12 (value 2048) is set instead, so that the final rounding
6594       // to single-precision gets the correct result.
6595       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6596                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6597       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6598                           Round, DAG.getConstant(2047, dl, MVT::i64));
6599       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6600       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6601                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6602
6603       // However, we cannot use that value unconditionally: if the magnitude
6604       // of the input value is small, the bit-twiddling we did above might
6605       // end up visibly changing the output.  Fortunately, in that case, we
6606       // don't need to twiddle bits since the original input will convert
6607       // exactly to double-precision floating-point already.  Therefore,
6608       // construct a conditional to use the original value if the top 11
6609       // bits are all sign-bit copies, and use the rounded value computed
6610       // above otherwise.
6611       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6612                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6613       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6614                          Cond, DAG.getConstant(1, dl, MVT::i64));
6615       Cond = DAG.getSetCC(dl, MVT::i32,
6616                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6617
6618       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6619     }
6620
6621     ReuseLoadInfo RLI;
6622     SDValue Bits;
6623
6624     MachineFunction &MF = DAG.getMachineFunction();
6625     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6626       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6627                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6628                          RLI.Ranges);
6629       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6630     } else if (Subtarget.hasLFIWAX() &&
6631                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6632       MachineMemOperand *MMO =
6633         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6634                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6635       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6636       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6637                                      DAG.getVTList(MVT::f64, MVT::Other),
6638                                      Ops, MVT::i32, MMO);
6639       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6640     } else if (Subtarget.hasFPCVT() &&
6641                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6642       MachineMemOperand *MMO =
6643         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6644                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6645       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6646       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6647                                      DAG.getVTList(MVT::f64, MVT::Other),
6648                                      Ops, MVT::i32, MMO);
6649       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6650     } else if (((Subtarget.hasLFIWAX() &&
6651                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6652                 (Subtarget.hasFPCVT() &&
6653                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6654                SINT.getOperand(0).getValueType() == MVT::i32) {
6655       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6656       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6657
6658       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6659       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6660
6661       SDValue Store = DAG.getStore(
6662           DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6663           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6664           false, false, 0);
6665
6666       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6667              "Expected an i32 store");
6668
6669       RLI.Ptr = FIdx;
6670       RLI.Chain = Store;
6671       RLI.MPI =
6672           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6673       RLI.Alignment = 4;
6674
6675       MachineMemOperand *MMO =
6676         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6677                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6678       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6679       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6680                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6681                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6682                                      Ops, MVT::i32, MMO);
6683     } else
6684       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6685
6686     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6687
6688     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6689       FP = DAG.getNode(ISD::FP_ROUND, dl,
6690                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6691     return FP;
6692   }
6693
6694   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6695          "Unhandled INT_TO_FP type in custom expander!");
6696   // Since we only generate this in 64-bit mode, we can take advantage of
6697   // 64-bit registers.  In particular, sign extend the input value into the
6698   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6699   // then lfd it and fcfid it.
6700   MachineFunction &MF = DAG.getMachineFunction();
6701   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6702   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6703
6704   SDValue Ld;
6705   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6706     ReuseLoadInfo RLI;
6707     bool ReusingLoad;
6708     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6709                                             DAG))) {
6710       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6711       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6712
6713       SDValue Store = DAG.getStore(
6714           DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6715           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6716           false, false, 0);
6717
6718       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6719              "Expected an i32 store");
6720
6721       RLI.Ptr = FIdx;
6722       RLI.Chain = Store;
6723       RLI.MPI =
6724           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6725       RLI.Alignment = 4;
6726     }
6727
6728     MachineMemOperand *MMO =
6729       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6730                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6731     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6732     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6733                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6734                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6735                                  Ops, MVT::i32, MMO);
6736     if (ReusingLoad)
6737       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6738   } else {
6739     assert(Subtarget.isPPC64() &&
6740            "i32->FP without LFIWAX supported only on PPC64");
6741
6742     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6743     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6744
6745     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6746                                 Op.getOperand(0));
6747
6748     // STD the extended value into the stack slot.
6749     SDValue Store = DAG.getStore(
6750         DAG.getEntryNode(), dl, Ext64, FIdx,
6751         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6752         false, false, 0);
6753
6754     // Load the value as a double.
6755     Ld = DAG.getLoad(
6756         MVT::f64, dl, Store, FIdx,
6757         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6758         false, false, false, 0);
6759   }
6760
6761   // FCFID it and return it.
6762   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6763   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6764     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6765                      DAG.getIntPtrConstant(0, dl));
6766   return FP;
6767 }
6768
6769 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6770                                             SelectionDAG &DAG) const {
6771   SDLoc dl(Op);
6772   /*
6773    The rounding mode is in bits 30:31 of FPSR, and has the following
6774    settings:
6775      00 Round to nearest
6776      01 Round to 0
6777      10 Round to +inf
6778      11 Round to -inf
6779
6780   FLT_ROUNDS, on the other hand, expects the following:
6781     -1 Undefined
6782      0 Round to 0
6783      1 Round to nearest
6784      2 Round to +inf
6785      3 Round to -inf
6786
6787   To perform the conversion, we do:
6788     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6789   */
6790
6791   MachineFunction &MF = DAG.getMachineFunction();
6792   EVT VT = Op.getValueType();
6793   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6794
6795   // Save FP Control Word to register
6796   EVT NodeTys[] = {
6797     MVT::f64,    // return register
6798     MVT::Glue    // unused in this context
6799   };
6800   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6801
6802   // Save FP register to stack slot
6803   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6804   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6805   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6806                                StackSlot, MachinePointerInfo(), false, false,0);
6807
6808   // Load FP Control Word from low 32 bits of stack slot.
6809   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6810   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6811   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6812                             false, false, false, 0);
6813
6814   // Transform as necessary
6815   SDValue CWD1 =
6816     DAG.getNode(ISD::AND, dl, MVT::i32,
6817                 CWD, DAG.getConstant(3, dl, MVT::i32));
6818   SDValue CWD2 =
6819     DAG.getNode(ISD::SRL, dl, MVT::i32,
6820                 DAG.getNode(ISD::AND, dl, MVT::i32,
6821                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6822                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6823                             DAG.getConstant(3, dl, MVT::i32)),
6824                 DAG.getConstant(1, dl, MVT::i32));
6825
6826   SDValue RetVal =
6827     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6828
6829   return DAG.getNode((VT.getSizeInBits() < 16 ?
6830                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6831 }
6832
6833 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6834   EVT VT = Op.getValueType();
6835   unsigned BitWidth = VT.getSizeInBits();
6836   SDLoc dl(Op);
6837   assert(Op.getNumOperands() == 3 &&
6838          VT == Op.getOperand(1).getValueType() &&
6839          "Unexpected SHL!");
6840
6841   // Expand into a bunch of logical ops.  Note that these ops
6842   // depend on the PPC behavior for oversized shift amounts.
6843   SDValue Lo = Op.getOperand(0);
6844   SDValue Hi = Op.getOperand(1);
6845   SDValue Amt = Op.getOperand(2);
6846   EVT AmtVT = Amt.getValueType();
6847
6848   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6849                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6850   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6851   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6852   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6853   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6854                              DAG.getConstant(-BitWidth, dl, AmtVT));
6855   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6856   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6857   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6858   SDValue OutOps[] = { OutLo, OutHi };
6859   return DAG.getMergeValues(OutOps, dl);
6860 }
6861
6862 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6863   EVT VT = Op.getValueType();
6864   SDLoc dl(Op);
6865   unsigned BitWidth = VT.getSizeInBits();
6866   assert(Op.getNumOperands() == 3 &&
6867          VT == Op.getOperand(1).getValueType() &&
6868          "Unexpected SRL!");
6869
6870   // Expand into a bunch of logical ops.  Note that these ops
6871   // depend on the PPC behavior for oversized shift amounts.
6872   SDValue Lo = Op.getOperand(0);
6873   SDValue Hi = Op.getOperand(1);
6874   SDValue Amt = Op.getOperand(2);
6875   EVT AmtVT = Amt.getValueType();
6876
6877   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6878                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6879   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6880   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6881   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6882   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6883                              DAG.getConstant(-BitWidth, dl, AmtVT));
6884   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6885   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6886   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6887   SDValue OutOps[] = { OutLo, OutHi };
6888   return DAG.getMergeValues(OutOps, dl);
6889 }
6890
6891 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6892   SDLoc dl(Op);
6893   EVT VT = Op.getValueType();
6894   unsigned BitWidth = VT.getSizeInBits();
6895   assert(Op.getNumOperands() == 3 &&
6896          VT == Op.getOperand(1).getValueType() &&
6897          "Unexpected SRA!");
6898
6899   // Expand into a bunch of logical ops, followed by a select_cc.
6900   SDValue Lo = Op.getOperand(0);
6901   SDValue Hi = Op.getOperand(1);
6902   SDValue Amt = Op.getOperand(2);
6903   EVT AmtVT = Amt.getValueType();
6904
6905   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6906                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6907   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6908   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6909   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6910   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6911                              DAG.getConstant(-BitWidth, dl, AmtVT));
6912   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6913   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6914   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6915                                   Tmp4, Tmp6, ISD::SETLE);
6916   SDValue OutOps[] = { OutLo, OutHi };
6917   return DAG.getMergeValues(OutOps, dl);
6918 }
6919
6920 //===----------------------------------------------------------------------===//
6921 // Vector related lowering.
6922 //
6923
6924 /// BuildSplatI - Build a canonical splati of Val with an element size of
6925 /// SplatSize.  Cast the result to VT.
6926 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6927                            SelectionDAG &DAG, const SDLoc &dl) {
6928   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6929
6930   static const MVT VTys[] = { // canonical VT to use for each size.
6931     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6932   };
6933
6934   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6935
6936   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6937   if (Val == -1)
6938     SplatSize = 1;
6939
6940   EVT CanonicalVT = VTys[SplatSize-1];
6941
6942   // Build a canonical splat for this value.
6943   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
6944 }
6945
6946 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6947 /// specified intrinsic ID.
6948 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
6949                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
6950   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6951   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6952                      DAG.getConstant(IID, dl, MVT::i32), Op);
6953 }
6954
6955 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6956 /// specified intrinsic ID.
6957 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6958                                 SelectionDAG &DAG, const SDLoc &dl,
6959                                 EVT DestVT = MVT::Other) {
6960   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6961   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6962                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6963 }
6964
6965 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6966 /// specified intrinsic ID.
6967 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6968                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
6969                                 EVT DestVT = MVT::Other) {
6970   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6971   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6972                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6973 }
6974
6975 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6976 /// amount.  The result has the specified value type.
6977 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
6978                            SelectionDAG &DAG, const SDLoc &dl) {
6979   // Force LHS/RHS to be the right type.
6980   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6981   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6982
6983   int Ops[16];
6984   for (unsigned i = 0; i != 16; ++i)
6985     Ops[i] = i + Amt;
6986   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6987   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6988 }
6989
6990 // If this is a case we can't handle, return null and let the default
6991 // expansion code take care of it.  If we CAN select this case, and if it
6992 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6993 // this case more efficiently than a constant pool load, lower it to the
6994 // sequence of ops that should be used.
6995 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6996                                              SelectionDAG &DAG) const {
6997   SDLoc dl(Op);
6998   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6999   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7000
7001   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7002     // We first build an i32 vector, load it into a QPX register,
7003     // then convert it to a floating-point vector and compare it
7004     // to a zero vector to get the boolean result.
7005     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7006     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7007     MachinePointerInfo PtrInfo =
7008         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7009     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7010     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7011
7012     assert(BVN->getNumOperands() == 4 &&
7013       "BUILD_VECTOR for v4i1 does not have 4 operands");
7014
7015     bool IsConst = true;
7016     for (unsigned i = 0; i < 4; ++i) {
7017       if (BVN->getOperand(i).isUndef()) continue;
7018       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7019         IsConst = false;
7020         break;
7021       }
7022     }
7023
7024     if (IsConst) {
7025       Constant *One =
7026         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7027       Constant *NegOne =
7028         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7029
7030       Constant *CV[4];
7031       for (unsigned i = 0; i < 4; ++i) {
7032         if (BVN->getOperand(i).isUndef())
7033           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7034         else if (isNullConstant(BVN->getOperand(i)))
7035           CV[i] = NegOne;
7036         else
7037           CV[i] = One;
7038       }
7039
7040       Constant *CP = ConstantVector::get(CV);
7041       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7042                                           16 /* alignment */);
7043
7044       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7045       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7046       return DAG.getMemIntrinsicNode(
7047           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7048           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7049     }
7050
7051     SmallVector<SDValue, 4> Stores;
7052     for (unsigned i = 0; i < 4; ++i) {
7053       if (BVN->getOperand(i).isUndef()) continue;
7054
7055       unsigned Offset = 4*i;
7056       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7057       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7058
7059       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7060       if (StoreSize > 4) {
7061         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
7062                                            BVN->getOperand(i), Idx,
7063                                            PtrInfo.getWithOffset(Offset),
7064                                            MVT::i32, false, false, 0));
7065       } else {
7066         SDValue StoreValue = BVN->getOperand(i);
7067         if (StoreSize < 4)
7068           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7069
7070         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
7071                                       StoreValue, Idx,
7072                                       PtrInfo.getWithOffset(Offset),
7073                                       false, false, 0));
7074       }
7075     }
7076
7077     SDValue StoreChain;
7078     if (!Stores.empty())
7079       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7080     else
7081       StoreChain = DAG.getEntryNode();
7082
7083     // Now load from v4i32 into the QPX register; this will extend it to
7084     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7085     // is typed as v4f64 because the QPX register integer states are not
7086     // explicitly represented.
7087
7088     SDValue Ops[] = {StoreChain,
7089                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7090                      FIdx};
7091     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7092
7093     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7094       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7095     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7096       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7097       LoadedVect);
7098
7099     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7100
7101     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7102   }
7103
7104   // All other QPX vectors are handled by generic code.
7105   if (Subtarget.hasQPX())
7106     return SDValue();
7107
7108   // Check if this is a splat of a constant value.
7109   APInt APSplatBits, APSplatUndef;
7110   unsigned SplatBitSize;
7111   bool HasAnyUndefs;
7112   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7113                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7114       SplatBitSize > 32)
7115     return SDValue();
7116
7117   unsigned SplatBits = APSplatBits.getZExtValue();
7118   unsigned SplatUndef = APSplatUndef.getZExtValue();
7119   unsigned SplatSize = SplatBitSize / 8;
7120
7121   // First, handle single instruction cases.
7122
7123   // All zeros?
7124   if (SplatBits == 0) {
7125     // Canonicalize all zero vectors to be v4i32.
7126     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7127       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7128       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7129     }
7130     return Op;
7131   }
7132
7133   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7134   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7135                     (32-SplatBitSize));
7136   if (SextVal >= -16 && SextVal <= 15)
7137     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7138
7139   // Two instruction sequences.
7140
7141   // If this value is in the range [-32,30] and is even, use:
7142   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7143   // If this value is in the range [17,31] and is odd, use:
7144   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7145   // If this value is in the range [-31,-17] and is odd, use:
7146   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7147   // Note the last two are three-instruction sequences.
7148   if (SextVal >= -32 && SextVal <= 31) {
7149     // To avoid having these optimizations undone by constant folding,
7150     // we convert to a pseudo that will be expanded later into one of
7151     // the above forms.
7152     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7153     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7154               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7155     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7156     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7157     if (VT == Op.getValueType())
7158       return RetVal;
7159     else
7160       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7161   }
7162
7163   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7164   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7165   // for fneg/fabs.
7166   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7167     // Make -1 and vspltisw -1:
7168     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7169
7170     // Make the VSLW intrinsic, computing 0x8000_0000.
7171     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7172                                    OnesV, DAG, dl);
7173
7174     // xor by OnesV to invert it.
7175     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7176     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7177   }
7178
7179   // Check to see if this is a wide variety of vsplti*, binop self cases.
7180   static const signed char SplatCsts[] = {
7181     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7182     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7183   };
7184
7185   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7186     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7187     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7188     int i = SplatCsts[idx];
7189
7190     // Figure out what shift amount will be used by altivec if shifted by i in
7191     // this splat size.
7192     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7193
7194     // vsplti + shl self.
7195     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7196       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7197       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7198         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7199         Intrinsic::ppc_altivec_vslw
7200       };
7201       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7202       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7203     }
7204
7205     // vsplti + srl self.
7206     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7207       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7208       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7209         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7210         Intrinsic::ppc_altivec_vsrw
7211       };
7212       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7213       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7214     }
7215
7216     // vsplti + sra self.
7217     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7218       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7219       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7220         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7221         Intrinsic::ppc_altivec_vsraw
7222       };
7223       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7224       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7225     }
7226
7227     // vsplti + rol self.
7228     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7229                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7230       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7231       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7232         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7233         Intrinsic::ppc_altivec_vrlw
7234       };
7235       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7236       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7237     }
7238
7239     // t = vsplti c, result = vsldoi t, t, 1
7240     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7241       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7242       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7243       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7244     }
7245     // t = vsplti c, result = vsldoi t, t, 2
7246     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7247       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7248       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7249       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7250     }
7251     // t = vsplti c, result = vsldoi t, t, 3
7252     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7253       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7254       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7255       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7256     }
7257   }
7258
7259   return SDValue();
7260 }
7261
7262 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7263 /// the specified operations to build the shuffle.
7264 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7265                                       SDValue RHS, SelectionDAG &DAG,
7266                                       const SDLoc &dl) {
7267   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7268   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7269   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7270
7271   enum {
7272     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7273     OP_VMRGHW,
7274     OP_VMRGLW,
7275     OP_VSPLTISW0,
7276     OP_VSPLTISW1,
7277     OP_VSPLTISW2,
7278     OP_VSPLTISW3,
7279     OP_VSLDOI4,
7280     OP_VSLDOI8,
7281     OP_VSLDOI12
7282   };
7283
7284   if (OpNum == OP_COPY) {
7285     if (LHSID == (1*9+2)*9+3) return LHS;
7286     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7287     return RHS;
7288   }
7289
7290   SDValue OpLHS, OpRHS;
7291   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7292   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7293
7294   int ShufIdxs[16];
7295   switch (OpNum) {
7296   default: llvm_unreachable("Unknown i32 permute!");
7297   case OP_VMRGHW:
7298     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7299     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7300     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7301     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7302     break;
7303   case OP_VMRGLW:
7304     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7305     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7306     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7307     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7308     break;
7309   case OP_VSPLTISW0:
7310     for (unsigned i = 0; i != 16; ++i)
7311       ShufIdxs[i] = (i&3)+0;
7312     break;
7313   case OP_VSPLTISW1:
7314     for (unsigned i = 0; i != 16; ++i)
7315       ShufIdxs[i] = (i&3)+4;
7316     break;
7317   case OP_VSPLTISW2:
7318     for (unsigned i = 0; i != 16; ++i)
7319       ShufIdxs[i] = (i&3)+8;
7320     break;
7321   case OP_VSPLTISW3:
7322     for (unsigned i = 0; i != 16; ++i)
7323       ShufIdxs[i] = (i&3)+12;
7324     break;
7325   case OP_VSLDOI4:
7326     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7327   case OP_VSLDOI8:
7328     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7329   case OP_VSLDOI12:
7330     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7331   }
7332   EVT VT = OpLHS.getValueType();
7333   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7334   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7335   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7336   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7337 }
7338
7339 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7340 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7341 /// return the code it can be lowered into.  Worst case, it can always be
7342 /// lowered into a vperm.
7343 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7344                                                SelectionDAG &DAG) const {
7345   SDLoc dl(Op);
7346   SDValue V1 = Op.getOperand(0);
7347   SDValue V2 = Op.getOperand(1);
7348   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7349   EVT VT = Op.getValueType();
7350   bool isLittleEndian = Subtarget.isLittleEndian();
7351
7352   if (Subtarget.hasVSX()) {
7353     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7354       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7355       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7356       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7357                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7358       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7359     }
7360   }
7361
7362   if (Subtarget.hasQPX()) {
7363     if (VT.getVectorNumElements() != 4)
7364       return SDValue();
7365
7366     if (V2.isUndef()) V2 = V1;
7367
7368     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7369     if (AlignIdx != -1) {
7370       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7371                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7372     } else if (SVOp->isSplat()) {
7373       int SplatIdx = SVOp->getSplatIndex();
7374       if (SplatIdx >= 4) {
7375         std::swap(V1, V2);
7376         SplatIdx -= 4;
7377       }
7378
7379       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7380                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7381     }
7382
7383     // Lower this into a qvgpci/qvfperm pair.
7384
7385     // Compute the qvgpci literal
7386     unsigned idx = 0;
7387     for (unsigned i = 0; i < 4; ++i) {
7388       int m = SVOp->getMaskElt(i);
7389       unsigned mm = m >= 0 ? (unsigned) m : i;
7390       idx |= mm << (3-i)*3;
7391     }
7392
7393     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7394                              DAG.getConstant(idx, dl, MVT::i32));
7395     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7396   }
7397
7398   // Cases that are handled by instructions that take permute immediates
7399   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7400   // selected by the instruction selector.
7401   if (V2.isUndef()) {
7402     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7403         PPC::isSplatShuffleMask(SVOp, 2) ||
7404         PPC::isSplatShuffleMask(SVOp, 4) ||
7405         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7406         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7407         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7408         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7409         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7410         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7411         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7412         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7413         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7414         (Subtarget.hasP8Altivec() && (
7415          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7416          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7417          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7418       return Op;
7419     }
7420   }
7421
7422   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7423   // and produce a fixed permutation.  If any of these match, do not lower to
7424   // VPERM.
7425   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7426   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7427       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7428       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7429       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7430       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7431       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7432       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7433       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7434       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7435       (Subtarget.hasP8Altivec() && (
7436        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7437        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7438        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7439     return Op;
7440
7441   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7442   // perfect shuffle table to emit an optimal matching sequence.
7443   ArrayRef<int> PermMask = SVOp->getMask();
7444
7445   unsigned PFIndexes[4];
7446   bool isFourElementShuffle = true;
7447   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7448     unsigned EltNo = 8;   // Start out undef.
7449     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7450       if (PermMask[i*4+j] < 0)
7451         continue;   // Undef, ignore it.
7452
7453       unsigned ByteSource = PermMask[i*4+j];
7454       if ((ByteSource & 3) != j) {
7455         isFourElementShuffle = false;
7456         break;
7457       }
7458
7459       if (EltNo == 8) {
7460         EltNo = ByteSource/4;
7461       } else if (EltNo != ByteSource/4) {
7462         isFourElementShuffle = false;
7463         break;
7464       }
7465     }
7466     PFIndexes[i] = EltNo;
7467   }
7468
7469   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7470   // perfect shuffle vector to determine if it is cost effective to do this as
7471   // discrete instructions, or whether we should use a vperm.
7472   // For now, we skip this for little endian until such time as we have a
7473   // little-endian perfect shuffle table.
7474   if (isFourElementShuffle && !isLittleEndian) {
7475     // Compute the index in the perfect shuffle table.
7476     unsigned PFTableIndex =
7477       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7478
7479     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7480     unsigned Cost  = (PFEntry >> 30);
7481
7482     // Determining when to avoid vperm is tricky.  Many things affect the cost
7483     // of vperm, particularly how many times the perm mask needs to be computed.
7484     // For example, if the perm mask can be hoisted out of a loop or is already
7485     // used (perhaps because there are multiple permutes with the same shuffle
7486     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7487     // the loop requires an extra register.
7488     //
7489     // As a compromise, we only emit discrete instructions if the shuffle can be
7490     // generated in 3 or fewer operations.  When we have loop information
7491     // available, if this block is within a loop, we should avoid using vperm
7492     // for 3-operation perms and use a constant pool load instead.
7493     if (Cost < 3)
7494       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7495   }
7496
7497   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7498   // vector that will get spilled to the constant pool.
7499   if (V2.isUndef()) V2 = V1;
7500
7501   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7502   // that it is in input element units, not in bytes.  Convert now.
7503
7504   // For little endian, the order of the input vectors is reversed, and
7505   // the permutation mask is complemented with respect to 31.  This is
7506   // necessary to produce proper semantics with the big-endian-biased vperm
7507   // instruction.
7508   EVT EltVT = V1.getValueType().getVectorElementType();
7509   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7510
7511   SmallVector<SDValue, 16> ResultMask;
7512   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7513     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7514
7515     for (unsigned j = 0; j != BytesPerElement; ++j)
7516       if (isLittleEndian)
7517         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7518                                              dl, MVT::i32));
7519       else
7520         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7521                                              MVT::i32));
7522   }
7523
7524   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7525   if (isLittleEndian)
7526     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7527                        V2, V1, VPermMask);
7528   else
7529     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7530                        V1, V2, VPermMask);
7531 }
7532
7533 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7534 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7535 /// information about the intrinsic.
7536 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7537                                  bool &isDot, const PPCSubtarget &Subtarget) {
7538   unsigned IntrinsicID =
7539     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7540   CompareOpc = -1;
7541   isDot = false;
7542   switch (IntrinsicID) {
7543   default: return false;
7544     // Comparison predicates.
7545   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7546   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7547   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7548   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7549   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7550   case Intrinsic::ppc_altivec_vcmpequd_p:
7551     if (Subtarget.hasP8Altivec()) {
7552       CompareOpc = 199;
7553       isDot = 1;
7554     } else
7555       return false;
7556
7557     break;
7558   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7559   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7560   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7561   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7562   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7563   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7564     if (Subtarget.hasP8Altivec()) {
7565       CompareOpc = 967;
7566       isDot = 1;
7567     } else
7568       return false;
7569
7570     break;
7571   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7572   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7573   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7574   case Intrinsic::ppc_altivec_vcmpgtud_p:
7575     if (Subtarget.hasP8Altivec()) {
7576       CompareOpc = 711;
7577       isDot = 1;
7578     } else
7579       return false;
7580
7581     break;
7582     // VSX predicate comparisons use the same infrastructure
7583   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7584   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7585   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7586   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7587   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7588   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7589     if (Subtarget.hasVSX()) {
7590       switch (IntrinsicID) {
7591       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7592       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7593       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7594       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7595       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7596       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7597       }
7598       isDot = 1;
7599     }
7600     else
7601       return false;
7602
7603     break;
7604
7605     // Normal Comparisons.
7606   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7607   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7608   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7609   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7610   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7611   case Intrinsic::ppc_altivec_vcmpequd:
7612     if (Subtarget.hasP8Altivec()) {
7613       CompareOpc = 199;
7614       isDot = 0;
7615     } else
7616       return false;
7617
7618     break;
7619   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7620   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7621   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7622   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7623   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7624   case Intrinsic::ppc_altivec_vcmpgtsd:
7625     if (Subtarget.hasP8Altivec()) {
7626       CompareOpc = 967;
7627       isDot = 0;
7628     } else
7629       return false;
7630
7631     break;
7632   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7633   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7634   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7635   case Intrinsic::ppc_altivec_vcmpgtud:
7636     if (Subtarget.hasP8Altivec()) {
7637       CompareOpc = 711;
7638       isDot = 0;
7639     } else
7640       return false;
7641
7642     break;
7643   }
7644   return true;
7645 }
7646
7647 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7648 /// lower, do it, otherwise return null.
7649 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7650                                                    SelectionDAG &DAG) const {
7651   unsigned IntrinsicID =
7652     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7653
7654   if (IntrinsicID == Intrinsic::thread_pointer) {
7655     // Reads the thread pointer register, used for __builtin_thread_pointer.
7656     bool is64bit = Subtarget.isPPC64();
7657     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7658                            is64bit ? MVT::i64 : MVT::i32);
7659   }
7660
7661   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7662   // opcode number of the comparison.
7663   SDLoc dl(Op);
7664   int CompareOpc;
7665   bool isDot;
7666   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7667     return SDValue();    // Don't custom lower most intrinsics.
7668
7669   // If this is a non-dot comparison, make the VCMP node and we are done.
7670   if (!isDot) {
7671     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7672                               Op.getOperand(1), Op.getOperand(2),
7673                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7674     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7675   }
7676
7677   // Create the PPCISD altivec 'dot' comparison node.
7678   SDValue Ops[] = {
7679     Op.getOperand(2),  // LHS
7680     Op.getOperand(3),  // RHS
7681     DAG.getConstant(CompareOpc, dl, MVT::i32)
7682   };
7683   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7684   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7685
7686   // Now that we have the comparison, emit a copy from the CR to a GPR.
7687   // This is flagged to the above dot comparison.
7688   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7689                                 DAG.getRegister(PPC::CR6, MVT::i32),
7690                                 CompNode.getValue(1));
7691
7692   // Unpack the result based on how the target uses it.
7693   unsigned BitNo;   // Bit # of CR6.
7694   bool InvertBit;   // Invert result?
7695   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7696   default:  // Can't happen, don't crash on invalid number though.
7697   case 0:   // Return the value of the EQ bit of CR6.
7698     BitNo = 0; InvertBit = false;
7699     break;
7700   case 1:   // Return the inverted value of the EQ bit of CR6.
7701     BitNo = 0; InvertBit = true;
7702     break;
7703   case 2:   // Return the value of the LT bit of CR6.
7704     BitNo = 2; InvertBit = false;
7705     break;
7706   case 3:   // Return the inverted value of the LT bit of CR6.
7707     BitNo = 2; InvertBit = true;
7708     break;
7709   }
7710
7711   // Shift the bit into the low position.
7712   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7713                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7714   // Isolate the bit.
7715   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7716                       DAG.getConstant(1, dl, MVT::i32));
7717
7718   // If we are supposed to, toggle the bit.
7719   if (InvertBit)
7720     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7721                         DAG.getConstant(1, dl, MVT::i32));
7722   return Flags;
7723 }
7724
7725 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7726                                                   SelectionDAG &DAG) const {
7727   SDLoc dl(Op);
7728   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7729   // instructions), but for smaller types, we need to first extend up to v2i32
7730   // before doing going farther.
7731   if (Op.getValueType() == MVT::v2i64) {
7732     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7733     if (ExtVT != MVT::v2i32) {
7734       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7735       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7736                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7737                                         ExtVT.getVectorElementType(), 4)));
7738       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7739       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7740                        DAG.getValueType(MVT::v2i32));
7741     }
7742
7743     return Op;
7744   }
7745
7746   return SDValue();
7747 }
7748
7749 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7750                                                    SelectionDAG &DAG) const {
7751   SDLoc dl(Op);
7752   // Create a stack slot that is 16-byte aligned.
7753   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7754   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7755   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7756   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7757
7758   // Store the input value into Value#0 of the stack slot.
7759   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7760                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7761                                false, false, 0);
7762   // Load it out.
7763   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7764                      false, false, false, 0);
7765 }
7766
7767 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7768                                                    SelectionDAG &DAG) const {
7769   SDLoc dl(Op);
7770   SDNode *N = Op.getNode();
7771
7772   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7773          "Unknown extract_vector_elt type");
7774
7775   SDValue Value = N->getOperand(0);
7776
7777   // The first part of this is like the store lowering except that we don't
7778   // need to track the chain.
7779
7780   // The values are now known to be -1 (false) or 1 (true). To convert this
7781   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7782   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7783   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7784
7785   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7786   // understand how to form the extending load.
7787   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7788
7789   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7790
7791   // Now convert to an integer and store.
7792   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7793     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7794     Value);
7795
7796   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7797   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7798   MachinePointerInfo PtrInfo =
7799       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7800   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7801   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7802
7803   SDValue StoreChain = DAG.getEntryNode();
7804   SDValue Ops[] = {StoreChain,
7805                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7806                    Value, FIdx};
7807   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7808
7809   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7810     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7811
7812   // Extract the value requested.
7813   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7814   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7815   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7816
7817   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7818                                PtrInfo.getWithOffset(Offset),
7819                                false, false, false, 0);
7820
7821   if (!Subtarget.useCRBits())
7822     return IntVal;
7823
7824   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7825 }
7826
7827 /// Lowering for QPX v4i1 loads
7828 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7829                                            SelectionDAG &DAG) const {
7830   SDLoc dl(Op);
7831   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7832   SDValue LoadChain = LN->getChain();
7833   SDValue BasePtr = LN->getBasePtr();
7834
7835   if (Op.getValueType() == MVT::v4f64 ||
7836       Op.getValueType() == MVT::v4f32) {
7837     EVT MemVT = LN->getMemoryVT();
7838     unsigned Alignment = LN->getAlignment();
7839
7840     // If this load is properly aligned, then it is legal.
7841     if (Alignment >= MemVT.getStoreSize())
7842       return Op;
7843
7844     EVT ScalarVT = Op.getValueType().getScalarType(),
7845         ScalarMemVT = MemVT.getScalarType();
7846     unsigned Stride = ScalarMemVT.getStoreSize();
7847
7848     SDValue Vals[4], LoadChains[4];
7849     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7850       SDValue Load;
7851       if (ScalarVT != ScalarMemVT)
7852         Load =
7853           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7854                          BasePtr,
7855                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7856                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7857                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7858                          LN->getAAInfo());
7859       else
7860         Load =
7861           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7862                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7863                        LN->isVolatile(), LN->isNonTemporal(),
7864                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7865                        LN->getAAInfo());
7866
7867       if (Idx == 0 && LN->isIndexed()) {
7868         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7869                "Unknown addressing mode on vector load");
7870         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7871                                   LN->getAddressingMode());
7872       }
7873
7874       Vals[Idx] = Load;
7875       LoadChains[Idx] = Load.getValue(1);
7876
7877       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7878                             DAG.getConstant(Stride, dl,
7879                                             BasePtr.getValueType()));
7880     }
7881
7882     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7883     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7884
7885     if (LN->isIndexed()) {
7886       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7887       return DAG.getMergeValues(RetOps, dl);
7888     }
7889
7890     SDValue RetOps[] = { Value, TF };
7891     return DAG.getMergeValues(RetOps, dl);
7892   }
7893
7894   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7895   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7896
7897   // To lower v4i1 from a byte array, we load the byte elements of the
7898   // vector and then reuse the BUILD_VECTOR logic.
7899
7900   SDValue VectElmts[4], VectElmtChains[4];
7901   for (unsigned i = 0; i < 4; ++i) {
7902     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7903     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7904
7905     VectElmts[i] = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
7906                                   LN->getPointerInfo().getWithOffset(i),
7907                                   MVT::i8 /* memory type */, LN->isVolatile(),
7908                                   LN->isNonTemporal(), LN->isInvariant(),
7909                                   1 /* alignment */, LN->getAAInfo());
7910     VectElmtChains[i] = VectElmts[i].getValue(1);
7911   }
7912
7913   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7914   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
7915
7916   SDValue RVals[] = { Value, LoadChain };
7917   return DAG.getMergeValues(RVals, dl);
7918 }
7919
7920 /// Lowering for QPX v4i1 stores
7921 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7922                                             SelectionDAG &DAG) const {
7923   SDLoc dl(Op);
7924   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7925   SDValue StoreChain = SN->getChain();
7926   SDValue BasePtr = SN->getBasePtr();
7927   SDValue Value = SN->getValue();
7928
7929   if (Value.getValueType() == MVT::v4f64 ||
7930       Value.getValueType() == MVT::v4f32) {
7931     EVT MemVT = SN->getMemoryVT();
7932     unsigned Alignment = SN->getAlignment();
7933
7934     // If this store is properly aligned, then it is legal.
7935     if (Alignment >= MemVT.getStoreSize())
7936       return Op;
7937
7938     EVT ScalarVT = Value.getValueType().getScalarType(),
7939         ScalarMemVT = MemVT.getScalarType();
7940     unsigned Stride = ScalarMemVT.getStoreSize();
7941
7942     SDValue Stores[4];
7943     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7944       SDValue Ex = DAG.getNode(
7945           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7946           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
7947       SDValue Store;
7948       if (ScalarVT != ScalarMemVT)
7949         Store =
7950           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7951                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7952                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7953                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7954       else
7955         Store =
7956           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7957                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7958                        SN->isVolatile(), SN->isNonTemporal(),
7959                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7960
7961       if (Idx == 0 && SN->isIndexed()) {
7962         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7963                "Unknown addressing mode on vector store");
7964         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7965                                     SN->getAddressingMode());
7966       }
7967
7968       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7969                             DAG.getConstant(Stride, dl,
7970                                             BasePtr.getValueType()));
7971       Stores[Idx] = Store;
7972     }
7973
7974     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7975
7976     if (SN->isIndexed()) {
7977       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7978       return DAG.getMergeValues(RetOps, dl);
7979     }
7980
7981     return TF;
7982   }
7983
7984   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7985   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7986
7987   // The values are now known to be -1 (false) or 1 (true). To convert this
7988   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7989   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7990   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7991
7992   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7993   // understand how to form the extending load.
7994   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7995
7996   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7997
7998   // Now convert to an integer and store.
7999   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8000     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8001     Value);
8002
8003   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
8004   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
8005   MachinePointerInfo PtrInfo =
8006       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8007   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8008   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8009
8010   SDValue Ops[] = {StoreChain,
8011                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8012                    Value, FIdx};
8013   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8014
8015   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8016     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8017
8018   // Move data into the byte array.
8019   SDValue Loads[4], LoadChains[4];
8020   for (unsigned i = 0; i < 4; ++i) {
8021     unsigned Offset = 4*i;
8022     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8023     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8024
8025     Loads[i] =
8026         DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8027                     PtrInfo.getWithOffset(Offset), false, false, false, 0);
8028     LoadChains[i] = Loads[i].getValue(1);
8029   }
8030
8031   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8032
8033   SDValue Stores[4];
8034   for (unsigned i = 0; i < 4; ++i) {
8035     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8036     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8037
8038     Stores[i] = DAG.getTruncStore(
8039         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8040         MVT::i8 /* memory type */, SN->isNonTemporal(), SN->isVolatile(),
8041         1 /* alignment */, SN->getAAInfo());
8042   }
8043
8044   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8045
8046   return StoreChain;
8047 }
8048
8049 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8050   SDLoc dl(Op);
8051   if (Op.getValueType() == MVT::v4i32) {
8052     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8053
8054     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8055     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8056
8057     SDValue RHSSwap =   // = vrlw RHS, 16
8058       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8059
8060     // Shrinkify inputs to v8i16.
8061     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8062     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8063     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8064
8065     // Low parts multiplied together, generating 32-bit results (we ignore the
8066     // top parts).
8067     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8068                                         LHS, RHS, DAG, dl, MVT::v4i32);
8069
8070     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8071                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8072     // Shift the high parts up 16 bits.
8073     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8074                               Neg16, DAG, dl);
8075     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8076   } else if (Op.getValueType() == MVT::v8i16) {
8077     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8078
8079     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8080
8081     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8082                             LHS, RHS, Zero, DAG, dl);
8083   } else if (Op.getValueType() == MVT::v16i8) {
8084     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8085     bool isLittleEndian = Subtarget.isLittleEndian();
8086
8087     // Multiply the even 8-bit parts, producing 16-bit sums.
8088     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8089                                            LHS, RHS, DAG, dl, MVT::v8i16);
8090     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8091
8092     // Multiply the odd 8-bit parts, producing 16-bit sums.
8093     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8094                                           LHS, RHS, DAG, dl, MVT::v8i16);
8095     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8096
8097     // Merge the results together.  Because vmuleub and vmuloub are
8098     // instructions with a big-endian bias, we must reverse the
8099     // element numbering and reverse the meaning of "odd" and "even"
8100     // when generating little endian code.
8101     int Ops[16];
8102     for (unsigned i = 0; i != 8; ++i) {
8103       if (isLittleEndian) {
8104         Ops[i*2  ] = 2*i;
8105         Ops[i*2+1] = 2*i+16;
8106       } else {
8107         Ops[i*2  ] = 2*i+1;
8108         Ops[i*2+1] = 2*i+1+16;
8109       }
8110     }
8111     if (isLittleEndian)
8112       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8113     else
8114       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8115   } else {
8116     llvm_unreachable("Unknown mul to lower!");
8117   }
8118 }
8119
8120 /// LowerOperation - Provide custom lowering hooks for some operations.
8121 ///
8122 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8123   switch (Op.getOpcode()) {
8124   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8125   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8126   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8127   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8128   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8129   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8130   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8131   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8132   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8133   case ISD::VASTART:
8134     return LowerVASTART(Op, DAG);
8135
8136   case ISD::VAARG:
8137     return LowerVAARG(Op, DAG);
8138
8139   case ISD::VACOPY:
8140     return LowerVACOPY(Op, DAG);
8141
8142   case ISD::STACKRESTORE:
8143     return LowerSTACKRESTORE(Op, DAG);
8144
8145   case ISD::DYNAMIC_STACKALLOC:
8146     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8147
8148   case ISD::GET_DYNAMIC_AREA_OFFSET:
8149     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8150
8151   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8152   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8153
8154   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8155   case ISD::STORE:              return LowerSTORE(Op, DAG);
8156   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8157   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8158   case ISD::FP_TO_UINT:
8159   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8160                                                       SDLoc(Op));
8161   case ISD::UINT_TO_FP:
8162   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8163   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8164
8165   // Lower 64-bit shifts.
8166   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8167   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8168   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8169
8170   // Vector-related lowering.
8171   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8172   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8173   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8174   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8175   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8176   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8177   case ISD::MUL:                return LowerMUL(Op, DAG);
8178
8179   // For counter-based loop handling.
8180   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8181
8182   // Frame & Return address.
8183   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8184   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8185   }
8186 }
8187
8188 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8189                                            SmallVectorImpl<SDValue>&Results,
8190                                            SelectionDAG &DAG) const {
8191   SDLoc dl(N);
8192   switch (N->getOpcode()) {
8193   default:
8194     llvm_unreachable("Do not know how to custom type legalize this operation!");
8195   case ISD::READCYCLECOUNTER: {
8196     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8197     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8198
8199     Results.push_back(RTB);
8200     Results.push_back(RTB.getValue(1));
8201     Results.push_back(RTB.getValue(2));
8202     break;
8203   }
8204   case ISD::INTRINSIC_W_CHAIN: {
8205     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8206         Intrinsic::ppc_is_decremented_ctr_nonzero)
8207       break;
8208
8209     assert(N->getValueType(0) == MVT::i1 &&
8210            "Unexpected result type for CTR decrement intrinsic");
8211     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8212                                  N->getValueType(0));
8213     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8214     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8215                                  N->getOperand(1));
8216
8217     Results.push_back(NewInt);
8218     Results.push_back(NewInt.getValue(1));
8219     break;
8220   }
8221   case ISD::VAARG: {
8222     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8223       return;
8224
8225     EVT VT = N->getValueType(0);
8226
8227     if (VT == MVT::i64) {
8228       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8229
8230       Results.push_back(NewNode);
8231       Results.push_back(NewNode.getValue(1));
8232     }
8233     return;
8234   }
8235   case ISD::FP_ROUND_INREG: {
8236     assert(N->getValueType(0) == MVT::ppcf128);
8237     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8238     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8239                              MVT::f64, N->getOperand(0),
8240                              DAG.getIntPtrConstant(0, dl));
8241     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8242                              MVT::f64, N->getOperand(0),
8243                              DAG.getIntPtrConstant(1, dl));
8244
8245     // Add the two halves of the long double in round-to-zero mode.
8246     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8247
8248     // We know the low half is about to be thrown away, so just use something
8249     // convenient.
8250     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8251                                 FPreg, FPreg));
8252     return;
8253   }
8254   case ISD::FP_TO_SINT:
8255   case ISD::FP_TO_UINT:
8256     // LowerFP_TO_INT() can only handle f32 and f64.
8257     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8258       return;
8259     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8260     return;
8261   }
8262 }
8263
8264 //===----------------------------------------------------------------------===//
8265 //  Other Lowering Code
8266 //===----------------------------------------------------------------------===//
8267
8268 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8269   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8270   Function *Func = Intrinsic::getDeclaration(M, Id);
8271   return Builder.CreateCall(Func, {});
8272 }
8273
8274 // The mappings for emitLeading/TrailingFence is taken from
8275 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8276 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8277                                          AtomicOrdering Ord, bool IsStore,
8278                                          bool IsLoad) const {
8279   if (Ord == AtomicOrdering::SequentiallyConsistent)
8280     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8281   if (isReleaseOrStronger(Ord))
8282     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8283   return nullptr;
8284 }
8285
8286 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8287                                           AtomicOrdering Ord, bool IsStore,
8288                                           bool IsLoad) const {
8289   if (IsLoad && isAcquireOrStronger(Ord))
8290     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8291   // FIXME: this is too conservative, a dependent branch + isync is enough.
8292   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8293   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8294   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8295   return nullptr;
8296 }
8297
8298 MachineBasicBlock *
8299 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8300                                     unsigned AtomicSize,
8301                                     unsigned BinOpcode) const {
8302   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8303   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8304
8305   auto LoadMnemonic = PPC::LDARX;
8306   auto StoreMnemonic = PPC::STDCX;
8307   switch (AtomicSize) {
8308   default:
8309     llvm_unreachable("Unexpected size of atomic entity");
8310   case 1:
8311     LoadMnemonic = PPC::LBARX;
8312     StoreMnemonic = PPC::STBCX;
8313     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8314     break;
8315   case 2:
8316     LoadMnemonic = PPC::LHARX;
8317     StoreMnemonic = PPC::STHCX;
8318     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8319     break;
8320   case 4:
8321     LoadMnemonic = PPC::LWARX;
8322     StoreMnemonic = PPC::STWCX;
8323     break;
8324   case 8:
8325     LoadMnemonic = PPC::LDARX;
8326     StoreMnemonic = PPC::STDCX;
8327     break;
8328   }
8329
8330   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8331   MachineFunction *F = BB->getParent();
8332   MachineFunction::iterator It = ++BB->getIterator();
8333
8334   unsigned dest = MI.getOperand(0).getReg();
8335   unsigned ptrA = MI.getOperand(1).getReg();
8336   unsigned ptrB = MI.getOperand(2).getReg();
8337   unsigned incr = MI.getOperand(3).getReg();
8338   DebugLoc dl = MI.getDebugLoc();
8339
8340   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8341   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8342   F->insert(It, loopMBB);
8343   F->insert(It, exitMBB);
8344   exitMBB->splice(exitMBB->begin(), BB,
8345                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8346   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8347
8348   MachineRegisterInfo &RegInfo = F->getRegInfo();
8349   unsigned TmpReg = (!BinOpcode) ? incr :
8350     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8351                                            : &PPC::GPRCRegClass);
8352
8353   //  thisMBB:
8354   //   ...
8355   //   fallthrough --> loopMBB
8356   BB->addSuccessor(loopMBB);
8357
8358   //  loopMBB:
8359   //   l[wd]arx dest, ptr
8360   //   add r0, dest, incr
8361   //   st[wd]cx. r0, ptr
8362   //   bne- loopMBB
8363   //   fallthrough --> exitMBB
8364   BB = loopMBB;
8365   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8366     .addReg(ptrA).addReg(ptrB);
8367   if (BinOpcode)
8368     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8369   BuildMI(BB, dl, TII->get(StoreMnemonic))
8370     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8371   BuildMI(BB, dl, TII->get(PPC::BCC))
8372     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8373   BB->addSuccessor(loopMBB);
8374   BB->addSuccessor(exitMBB);
8375
8376   //  exitMBB:
8377   //   ...
8378   BB = exitMBB;
8379   return BB;
8380 }
8381
8382 MachineBasicBlock *
8383 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8384                                             MachineBasicBlock *BB,
8385                                             bool is8bit, // operation
8386                                             unsigned BinOpcode) const {
8387   // If we support part-word atomic mnemonics, just use them
8388   if (Subtarget.hasPartwordAtomics())
8389     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8390
8391   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8392   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8393   // In 64 bit mode we have to use 64 bits for addresses, even though the
8394   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8395   // registers without caring whether they're 32 or 64, but here we're
8396   // doing actual arithmetic on the addresses.
8397   bool is64bit = Subtarget.isPPC64();
8398   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8399
8400   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8401   MachineFunction *F = BB->getParent();
8402   MachineFunction::iterator It = ++BB->getIterator();
8403
8404   unsigned dest = MI.getOperand(0).getReg();
8405   unsigned ptrA = MI.getOperand(1).getReg();
8406   unsigned ptrB = MI.getOperand(2).getReg();
8407   unsigned incr = MI.getOperand(3).getReg();
8408   DebugLoc dl = MI.getDebugLoc();
8409
8410   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8411   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8412   F->insert(It, loopMBB);
8413   F->insert(It, exitMBB);
8414   exitMBB->splice(exitMBB->begin(), BB,
8415                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8416   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8417
8418   MachineRegisterInfo &RegInfo = F->getRegInfo();
8419   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8420                                           : &PPC::GPRCRegClass;
8421   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8422   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8423   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8424   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8425   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8426   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8427   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8428   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8429   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8430   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8431   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8432   unsigned Ptr1Reg;
8433   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8434
8435   //  thisMBB:
8436   //   ...
8437   //   fallthrough --> loopMBB
8438   BB->addSuccessor(loopMBB);
8439
8440   // The 4-byte load must be aligned, while a char or short may be
8441   // anywhere in the word.  Hence all this nasty bookkeeping code.
8442   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8443   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8444   //   xori shift, shift1, 24 [16]
8445   //   rlwinm ptr, ptr1, 0, 0, 29
8446   //   slw incr2, incr, shift
8447   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8448   //   slw mask, mask2, shift
8449   //  loopMBB:
8450   //   lwarx tmpDest, ptr
8451   //   add tmp, tmpDest, incr2
8452   //   andc tmp2, tmpDest, mask
8453   //   and tmp3, tmp, mask
8454   //   or tmp4, tmp3, tmp2
8455   //   stwcx. tmp4, ptr
8456   //   bne- loopMBB
8457   //   fallthrough --> exitMBB
8458   //   srw dest, tmpDest, shift
8459   if (ptrA != ZeroReg) {
8460     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8461     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8462       .addReg(ptrA).addReg(ptrB);
8463   } else {
8464     Ptr1Reg = ptrB;
8465   }
8466   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8467       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8468   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8469       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8470   if (is64bit)
8471     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8472       .addReg(Ptr1Reg).addImm(0).addImm(61);
8473   else
8474     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8475       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8476   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8477       .addReg(incr).addReg(ShiftReg);
8478   if (is8bit)
8479     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8480   else {
8481     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8482     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8483   }
8484   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8485       .addReg(Mask2Reg).addReg(ShiftReg);
8486
8487   BB = loopMBB;
8488   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8489     .addReg(ZeroReg).addReg(PtrReg);
8490   if (BinOpcode)
8491     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8492       .addReg(Incr2Reg).addReg(TmpDestReg);
8493   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8494     .addReg(TmpDestReg).addReg(MaskReg);
8495   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8496     .addReg(TmpReg).addReg(MaskReg);
8497   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8498     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8499   BuildMI(BB, dl, TII->get(PPC::STWCX))
8500     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8501   BuildMI(BB, dl, TII->get(PPC::BCC))
8502     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8503   BB->addSuccessor(loopMBB);
8504   BB->addSuccessor(exitMBB);
8505
8506   //  exitMBB:
8507   //   ...
8508   BB = exitMBB;
8509   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8510     .addReg(ShiftReg);
8511   return BB;
8512 }
8513
8514 llvm::MachineBasicBlock *
8515 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8516                                     MachineBasicBlock *MBB) const {
8517   DebugLoc DL = MI.getDebugLoc();
8518   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8519
8520   MachineFunction *MF = MBB->getParent();
8521   MachineRegisterInfo &MRI = MF->getRegInfo();
8522
8523   const BasicBlock *BB = MBB->getBasicBlock();
8524   MachineFunction::iterator I = ++MBB->getIterator();
8525
8526   // Memory Reference
8527   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8528   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8529
8530   unsigned DstReg = MI.getOperand(0).getReg();
8531   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8532   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8533   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8534   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8535
8536   MVT PVT = getPointerTy(MF->getDataLayout());
8537   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8538          "Invalid Pointer Size!");
8539   // For v = setjmp(buf), we generate
8540   //
8541   // thisMBB:
8542   //  SjLjSetup mainMBB
8543   //  bl mainMBB
8544   //  v_restore = 1
8545   //  b sinkMBB
8546   //
8547   // mainMBB:
8548   //  buf[LabelOffset] = LR
8549   //  v_main = 0
8550   //
8551   // sinkMBB:
8552   //  v = phi(main, restore)
8553   //
8554
8555   MachineBasicBlock *thisMBB = MBB;
8556   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8557   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8558   MF->insert(I, mainMBB);
8559   MF->insert(I, sinkMBB);
8560
8561   MachineInstrBuilder MIB;
8562
8563   // Transfer the remainder of BB and its successor edges to sinkMBB.
8564   sinkMBB->splice(sinkMBB->begin(), MBB,
8565                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8566   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8567
8568   // Note that the structure of the jmp_buf used here is not compatible
8569   // with that used by libc, and is not designed to be. Specifically, it
8570   // stores only those 'reserved' registers that LLVM does not otherwise
8571   // understand how to spill. Also, by convention, by the time this
8572   // intrinsic is called, Clang has already stored the frame address in the
8573   // first slot of the buffer and stack address in the third. Following the
8574   // X86 target code, we'll store the jump address in the second slot. We also
8575   // need to save the TOC pointer (R2) to handle jumps between shared
8576   // libraries, and that will be stored in the fourth slot. The thread
8577   // identifier (R13) is not affected.
8578
8579   // thisMBB:
8580   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8581   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8582   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8583
8584   // Prepare IP either in reg.
8585   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8586   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8587   unsigned BufReg = MI.getOperand(1).getReg();
8588
8589   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8590     setUsesTOCBasePtr(*MBB->getParent());
8591     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8592             .addReg(PPC::X2)
8593             .addImm(TOCOffset)
8594             .addReg(BufReg);
8595     MIB.setMemRefs(MMOBegin, MMOEnd);
8596   }
8597
8598   // Naked functions never have a base pointer, and so we use r1. For all
8599   // other functions, this decision must be delayed until during PEI.
8600   unsigned BaseReg;
8601   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8602     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8603   else
8604     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8605
8606   MIB = BuildMI(*thisMBB, MI, DL,
8607                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8608             .addReg(BaseReg)
8609             .addImm(BPOffset)
8610             .addReg(BufReg);
8611   MIB.setMemRefs(MMOBegin, MMOEnd);
8612
8613   // Setup
8614   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8615   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8616   MIB.addRegMask(TRI->getNoPreservedMask());
8617
8618   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8619
8620   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8621           .addMBB(mainMBB);
8622   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8623
8624   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8625   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8626
8627   // mainMBB:
8628   //  mainDstReg = 0
8629   MIB =
8630       BuildMI(mainMBB, DL,
8631               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8632
8633   // Store IP
8634   if (Subtarget.isPPC64()) {
8635     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8636             .addReg(LabelReg)
8637             .addImm(LabelOffset)
8638             .addReg(BufReg);
8639   } else {
8640     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8641             .addReg(LabelReg)
8642             .addImm(LabelOffset)
8643             .addReg(BufReg);
8644   }
8645
8646   MIB.setMemRefs(MMOBegin, MMOEnd);
8647
8648   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8649   mainMBB->addSuccessor(sinkMBB);
8650
8651   // sinkMBB:
8652   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8653           TII->get(PPC::PHI), DstReg)
8654     .addReg(mainDstReg).addMBB(mainMBB)
8655     .addReg(restoreDstReg).addMBB(thisMBB);
8656
8657   MI.eraseFromParent();
8658   return sinkMBB;
8659 }
8660
8661 MachineBasicBlock *
8662 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8663                                      MachineBasicBlock *MBB) const {
8664   DebugLoc DL = MI.getDebugLoc();
8665   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8666
8667   MachineFunction *MF = MBB->getParent();
8668   MachineRegisterInfo &MRI = MF->getRegInfo();
8669
8670   // Memory Reference
8671   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8672   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8673
8674   MVT PVT = getPointerTy(MF->getDataLayout());
8675   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8676          "Invalid Pointer Size!");
8677
8678   const TargetRegisterClass *RC =
8679     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8680   unsigned Tmp = MRI.createVirtualRegister(RC);
8681   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8682   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8683   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8684   unsigned BP =
8685       (PVT == MVT::i64)
8686           ? PPC::X30
8687           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
8688                                                               : PPC::R30);
8689
8690   MachineInstrBuilder MIB;
8691
8692   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8693   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8694   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8695   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8696
8697   unsigned BufReg = MI.getOperand(0).getReg();
8698
8699   // Reload FP (the jumped-to function may not have had a
8700   // frame pointer, and if so, then its r31 will be restored
8701   // as necessary).
8702   if (PVT == MVT::i64) {
8703     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8704             .addImm(0)
8705             .addReg(BufReg);
8706   } else {
8707     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8708             .addImm(0)
8709             .addReg(BufReg);
8710   }
8711   MIB.setMemRefs(MMOBegin, MMOEnd);
8712
8713   // Reload IP
8714   if (PVT == MVT::i64) {
8715     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8716             .addImm(LabelOffset)
8717             .addReg(BufReg);
8718   } else {
8719     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8720             .addImm(LabelOffset)
8721             .addReg(BufReg);
8722   }
8723   MIB.setMemRefs(MMOBegin, MMOEnd);
8724
8725   // Reload SP
8726   if (PVT == MVT::i64) {
8727     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8728             .addImm(SPOffset)
8729             .addReg(BufReg);
8730   } else {
8731     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8732             .addImm(SPOffset)
8733             .addReg(BufReg);
8734   }
8735   MIB.setMemRefs(MMOBegin, MMOEnd);
8736
8737   // Reload BP
8738   if (PVT == MVT::i64) {
8739     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8740             .addImm(BPOffset)
8741             .addReg(BufReg);
8742   } else {
8743     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8744             .addImm(BPOffset)
8745             .addReg(BufReg);
8746   }
8747   MIB.setMemRefs(MMOBegin, MMOEnd);
8748
8749   // Reload TOC
8750   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8751     setUsesTOCBasePtr(*MBB->getParent());
8752     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8753             .addImm(TOCOffset)
8754             .addReg(BufReg);
8755
8756     MIB.setMemRefs(MMOBegin, MMOEnd);
8757   }
8758
8759   // Jump
8760   BuildMI(*MBB, MI, DL,
8761           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8762   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8763
8764   MI.eraseFromParent();
8765   return MBB;
8766 }
8767
8768 MachineBasicBlock *
8769 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8770                                                MachineBasicBlock *BB) const {
8771   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
8772       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8773     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8774         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8775       // Call lowering should have added an r2 operand to indicate a dependence
8776       // on the TOC base pointer value. It can't however, because there is no
8777       // way to mark the dependence as implicit there, and so the stackmap code
8778       // will confuse it with a regular operand. Instead, add the dependence
8779       // here.
8780       setUsesTOCBasePtr(*BB->getParent());
8781       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8782     }
8783
8784     return emitPatchPoint(MI, BB);
8785   }
8786
8787   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8788       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
8789     return emitEHSjLjSetJmp(MI, BB);
8790   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8791              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
8792     return emitEHSjLjLongJmp(MI, BB);
8793   }
8794
8795   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8796
8797   // To "insert" these instructions we actually have to insert their
8798   // control-flow patterns.
8799   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8800   MachineFunction::iterator It = ++BB->getIterator();
8801
8802   MachineFunction *F = BB->getParent();
8803
8804   if (Subtarget.hasISEL() &&
8805       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8806        MI.getOpcode() == PPC::SELECT_CC_I8 ||
8807        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
8808     SmallVector<MachineOperand, 2> Cond;
8809     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8810         MI.getOpcode() == PPC::SELECT_CC_I8)
8811       Cond.push_back(MI.getOperand(4));
8812     else
8813       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8814     Cond.push_back(MI.getOperand(1));
8815
8816     DebugLoc dl = MI.getDebugLoc();
8817     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
8818                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
8819   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8820              MI.getOpcode() == PPC::SELECT_CC_I8 ||
8821              MI.getOpcode() == PPC::SELECT_CC_F4 ||
8822              MI.getOpcode() == PPC::SELECT_CC_F8 ||
8823              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
8824              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
8825              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
8826              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
8827              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
8828              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
8829              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
8830              MI.getOpcode() == PPC::SELECT_I4 ||
8831              MI.getOpcode() == PPC::SELECT_I8 ||
8832              MI.getOpcode() == PPC::SELECT_F4 ||
8833              MI.getOpcode() == PPC::SELECT_F8 ||
8834              MI.getOpcode() == PPC::SELECT_QFRC ||
8835              MI.getOpcode() == PPC::SELECT_QSRC ||
8836              MI.getOpcode() == PPC::SELECT_QBRC ||
8837              MI.getOpcode() == PPC::SELECT_VRRC ||
8838              MI.getOpcode() == PPC::SELECT_VSFRC ||
8839              MI.getOpcode() == PPC::SELECT_VSSRC ||
8840              MI.getOpcode() == PPC::SELECT_VSRC) {
8841     // The incoming instruction knows the destination vreg to set, the
8842     // condition code register to branch on, the true/false values to
8843     // select between, and a branch opcode to use.
8844
8845     //  thisMBB:
8846     //  ...
8847     //   TrueVal = ...
8848     //   cmpTY ccX, r1, r2
8849     //   bCC copy1MBB
8850     //   fallthrough --> copy0MBB
8851     MachineBasicBlock *thisMBB = BB;
8852     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8853     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8854     DebugLoc dl = MI.getDebugLoc();
8855     F->insert(It, copy0MBB);
8856     F->insert(It, sinkMBB);
8857
8858     // Transfer the remainder of BB and its successor edges to sinkMBB.
8859     sinkMBB->splice(sinkMBB->begin(), BB,
8860                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8861     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8862
8863     // Next, add the true and fallthrough blocks as its successors.
8864     BB->addSuccessor(copy0MBB);
8865     BB->addSuccessor(sinkMBB);
8866
8867     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
8868         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
8869         MI.getOpcode() == PPC::SELECT_QFRC ||
8870         MI.getOpcode() == PPC::SELECT_QSRC ||
8871         MI.getOpcode() == PPC::SELECT_QBRC ||
8872         MI.getOpcode() == PPC::SELECT_VRRC ||
8873         MI.getOpcode() == PPC::SELECT_VSFRC ||
8874         MI.getOpcode() == PPC::SELECT_VSSRC ||
8875         MI.getOpcode() == PPC::SELECT_VSRC) {
8876       BuildMI(BB, dl, TII->get(PPC::BC))
8877           .addReg(MI.getOperand(1).getReg())
8878           .addMBB(sinkMBB);
8879     } else {
8880       unsigned SelectPred = MI.getOperand(4).getImm();
8881       BuildMI(BB, dl, TII->get(PPC::BCC))
8882           .addImm(SelectPred)
8883           .addReg(MI.getOperand(1).getReg())
8884           .addMBB(sinkMBB);
8885     }
8886
8887     //  copy0MBB:
8888     //   %FalseValue = ...
8889     //   # fallthrough to sinkMBB
8890     BB = copy0MBB;
8891
8892     // Update machine-CFG edges
8893     BB->addSuccessor(sinkMBB);
8894
8895     //  sinkMBB:
8896     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8897     //  ...
8898     BB = sinkMBB;
8899     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
8900         .addReg(MI.getOperand(3).getReg())
8901         .addMBB(copy0MBB)
8902         .addReg(MI.getOperand(2).getReg())
8903         .addMBB(thisMBB);
8904   } else if (MI.getOpcode() == PPC::ReadTB) {
8905     // To read the 64-bit time-base register on a 32-bit target, we read the
8906     // two halves. Should the counter have wrapped while it was being read, we
8907     // need to try again.
8908     // ...
8909     // readLoop:
8910     // mfspr Rx,TBU # load from TBU
8911     // mfspr Ry,TB  # load from TB
8912     // mfspr Rz,TBU # load from TBU
8913     // cmpw crX,Rx,Rz # check if 'old'='new'
8914     // bne readLoop   # branch if they're not equal
8915     // ...
8916
8917     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8918     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8919     DebugLoc dl = MI.getDebugLoc();
8920     F->insert(It, readMBB);
8921     F->insert(It, sinkMBB);
8922
8923     // Transfer the remainder of BB and its successor edges to sinkMBB.
8924     sinkMBB->splice(sinkMBB->begin(), BB,
8925                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8926     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8927
8928     BB->addSuccessor(readMBB);
8929     BB = readMBB;
8930
8931     MachineRegisterInfo &RegInfo = F->getRegInfo();
8932     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8933     unsigned LoReg = MI.getOperand(0).getReg();
8934     unsigned HiReg = MI.getOperand(1).getReg();
8935
8936     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8937     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8938     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8939
8940     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8941
8942     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8943       .addReg(HiReg).addReg(ReadAgainReg);
8944     BuildMI(BB, dl, TII->get(PPC::BCC))
8945       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8946
8947     BB->addSuccessor(readMBB);
8948     BB->addSuccessor(sinkMBB);
8949   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8950     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8951   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8952     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8953   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8954     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8955   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8956     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8957
8958   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8959     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8960   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8961     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8962   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8963     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8964   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8965     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8966
8967   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8968     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8969   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8970     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8971   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8972     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8973   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8974     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8975
8976   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8977     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8978   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8979     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8980   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8981     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8982   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8983     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8984
8985   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8986     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8987   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8988     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8989   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8990     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8991   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8992     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8993
8994   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8995     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8996   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8997     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8998   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8999     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9000   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9001     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9002
9003   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9004     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9005   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9006     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9007   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9008     BB = EmitAtomicBinary(MI, BB, 4, 0);
9009   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9010     BB = EmitAtomicBinary(MI, BB, 8, 0);
9011
9012   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9013            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9014            (Subtarget.hasPartwordAtomics() &&
9015             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9016            (Subtarget.hasPartwordAtomics() &&
9017             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9018     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9019
9020     auto LoadMnemonic = PPC::LDARX;
9021     auto StoreMnemonic = PPC::STDCX;
9022     switch (MI.getOpcode()) {
9023     default:
9024       llvm_unreachable("Compare and swap of unknown size");
9025     case PPC::ATOMIC_CMP_SWAP_I8:
9026       LoadMnemonic = PPC::LBARX;
9027       StoreMnemonic = PPC::STBCX;
9028       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9029       break;
9030     case PPC::ATOMIC_CMP_SWAP_I16:
9031       LoadMnemonic = PPC::LHARX;
9032       StoreMnemonic = PPC::STHCX;
9033       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9034       break;
9035     case PPC::ATOMIC_CMP_SWAP_I32:
9036       LoadMnemonic = PPC::LWARX;
9037       StoreMnemonic = PPC::STWCX;
9038       break;
9039     case PPC::ATOMIC_CMP_SWAP_I64:
9040       LoadMnemonic = PPC::LDARX;
9041       StoreMnemonic = PPC::STDCX;
9042       break;
9043     }
9044     unsigned dest = MI.getOperand(0).getReg();
9045     unsigned ptrA = MI.getOperand(1).getReg();
9046     unsigned ptrB = MI.getOperand(2).getReg();
9047     unsigned oldval = MI.getOperand(3).getReg();
9048     unsigned newval = MI.getOperand(4).getReg();
9049     DebugLoc dl = MI.getDebugLoc();
9050
9051     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9052     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9053     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9054     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9055     F->insert(It, loop1MBB);
9056     F->insert(It, loop2MBB);
9057     F->insert(It, midMBB);
9058     F->insert(It, exitMBB);
9059     exitMBB->splice(exitMBB->begin(), BB,
9060                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9061     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9062
9063     //  thisMBB:
9064     //   ...
9065     //   fallthrough --> loopMBB
9066     BB->addSuccessor(loop1MBB);
9067
9068     // loop1MBB:
9069     //   l[bhwd]arx dest, ptr
9070     //   cmp[wd] dest, oldval
9071     //   bne- midMBB
9072     // loop2MBB:
9073     //   st[bhwd]cx. newval, ptr
9074     //   bne- loopMBB
9075     //   b exitBB
9076     // midMBB:
9077     //   st[bhwd]cx. dest, ptr
9078     // exitBB:
9079     BB = loop1MBB;
9080     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9081       .addReg(ptrA).addReg(ptrB);
9082     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9083       .addReg(oldval).addReg(dest);
9084     BuildMI(BB, dl, TII->get(PPC::BCC))
9085       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9086     BB->addSuccessor(loop2MBB);
9087     BB->addSuccessor(midMBB);
9088
9089     BB = loop2MBB;
9090     BuildMI(BB, dl, TII->get(StoreMnemonic))
9091       .addReg(newval).addReg(ptrA).addReg(ptrB);
9092     BuildMI(BB, dl, TII->get(PPC::BCC))
9093       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9094     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9095     BB->addSuccessor(loop1MBB);
9096     BB->addSuccessor(exitMBB);
9097
9098     BB = midMBB;
9099     BuildMI(BB, dl, TII->get(StoreMnemonic))
9100       .addReg(dest).addReg(ptrA).addReg(ptrB);
9101     BB->addSuccessor(exitMBB);
9102
9103     //  exitMBB:
9104     //   ...
9105     BB = exitMBB;
9106   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9107              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9108     // We must use 64-bit registers for addresses when targeting 64-bit,
9109     // since we're actually doing arithmetic on them.  Other registers
9110     // can be 32-bit.
9111     bool is64bit = Subtarget.isPPC64();
9112     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9113
9114     unsigned dest = MI.getOperand(0).getReg();
9115     unsigned ptrA = MI.getOperand(1).getReg();
9116     unsigned ptrB = MI.getOperand(2).getReg();
9117     unsigned oldval = MI.getOperand(3).getReg();
9118     unsigned newval = MI.getOperand(4).getReg();
9119     DebugLoc dl = MI.getDebugLoc();
9120
9121     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9122     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9123     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9124     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9125     F->insert(It, loop1MBB);
9126     F->insert(It, loop2MBB);
9127     F->insert(It, midMBB);
9128     F->insert(It, exitMBB);
9129     exitMBB->splice(exitMBB->begin(), BB,
9130                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9131     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9132
9133     MachineRegisterInfo &RegInfo = F->getRegInfo();
9134     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9135                                             : &PPC::GPRCRegClass;
9136     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9137     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9138     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
9139     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9140     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9141     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9142     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9143     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9144     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9145     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9146     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9147     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9148     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9149     unsigned Ptr1Reg;
9150     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9151     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9152     //  thisMBB:
9153     //   ...
9154     //   fallthrough --> loopMBB
9155     BB->addSuccessor(loop1MBB);
9156
9157     // The 4-byte load must be aligned, while a char or short may be
9158     // anywhere in the word.  Hence all this nasty bookkeeping code.
9159     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9160     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9161     //   xori shift, shift1, 24 [16]
9162     //   rlwinm ptr, ptr1, 0, 0, 29
9163     //   slw newval2, newval, shift
9164     //   slw oldval2, oldval,shift
9165     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9166     //   slw mask, mask2, shift
9167     //   and newval3, newval2, mask
9168     //   and oldval3, oldval2, mask
9169     // loop1MBB:
9170     //   lwarx tmpDest, ptr
9171     //   and tmp, tmpDest, mask
9172     //   cmpw tmp, oldval3
9173     //   bne- midMBB
9174     // loop2MBB:
9175     //   andc tmp2, tmpDest, mask
9176     //   or tmp4, tmp2, newval3
9177     //   stwcx. tmp4, ptr
9178     //   bne- loop1MBB
9179     //   b exitBB
9180     // midMBB:
9181     //   stwcx. tmpDest, ptr
9182     // exitBB:
9183     //   srw dest, tmpDest, shift
9184     if (ptrA != ZeroReg) {
9185       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9186       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9187         .addReg(ptrA).addReg(ptrB);
9188     } else {
9189       Ptr1Reg = ptrB;
9190     }
9191     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9192         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9193     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9194         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9195     if (is64bit)
9196       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9197         .addReg(Ptr1Reg).addImm(0).addImm(61);
9198     else
9199       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9200         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9201     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9202         .addReg(newval).addReg(ShiftReg);
9203     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9204         .addReg(oldval).addReg(ShiftReg);
9205     if (is8bit)
9206       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9207     else {
9208       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9209       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9210         .addReg(Mask3Reg).addImm(65535);
9211     }
9212     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9213         .addReg(Mask2Reg).addReg(ShiftReg);
9214     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9215         .addReg(NewVal2Reg).addReg(MaskReg);
9216     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9217         .addReg(OldVal2Reg).addReg(MaskReg);
9218
9219     BB = loop1MBB;
9220     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9221         .addReg(ZeroReg).addReg(PtrReg);
9222     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9223         .addReg(TmpDestReg).addReg(MaskReg);
9224     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9225         .addReg(TmpReg).addReg(OldVal3Reg);
9226     BuildMI(BB, dl, TII->get(PPC::BCC))
9227         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9228     BB->addSuccessor(loop2MBB);
9229     BB->addSuccessor(midMBB);
9230
9231     BB = loop2MBB;
9232     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9233         .addReg(TmpDestReg).addReg(MaskReg);
9234     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9235         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9236     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9237         .addReg(ZeroReg).addReg(PtrReg);
9238     BuildMI(BB, dl, TII->get(PPC::BCC))
9239       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9240     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9241     BB->addSuccessor(loop1MBB);
9242     BB->addSuccessor(exitMBB);
9243
9244     BB = midMBB;
9245     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9246       .addReg(ZeroReg).addReg(PtrReg);
9247     BB->addSuccessor(exitMBB);
9248
9249     //  exitMBB:
9250     //   ...
9251     BB = exitMBB;
9252     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9253       .addReg(ShiftReg);
9254   } else if (MI.getOpcode() == PPC::FADDrtz) {
9255     // This pseudo performs an FADD with rounding mode temporarily forced
9256     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9257     // is not modeled at the SelectionDAG level.
9258     unsigned Dest = MI.getOperand(0).getReg();
9259     unsigned Src1 = MI.getOperand(1).getReg();
9260     unsigned Src2 = MI.getOperand(2).getReg();
9261     DebugLoc dl = MI.getDebugLoc();
9262
9263     MachineRegisterInfo &RegInfo = F->getRegInfo();
9264     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9265
9266     // Save FPSCR value.
9267     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9268
9269     // Set rounding mode to round-to-zero.
9270     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9271     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9272
9273     // Perform addition.
9274     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9275
9276     // Restore FPSCR value.
9277     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9278   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9279              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9280              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9281              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9282     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9283                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9284                           ? PPC::ANDIo8
9285                           : PPC::ANDIo;
9286     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9287                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9288
9289     MachineRegisterInfo &RegInfo = F->getRegInfo();
9290     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9291                                                   &PPC::GPRCRegClass :
9292                                                   &PPC::G8RCRegClass);
9293
9294     DebugLoc dl = MI.getDebugLoc();
9295     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9296         .addReg(MI.getOperand(1).getReg())
9297         .addImm(1);
9298     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9299             MI.getOperand(0).getReg())
9300         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9301   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9302     DebugLoc Dl = MI.getDebugLoc();
9303     MachineRegisterInfo &RegInfo = F->getRegInfo();
9304     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9305     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9306     return BB;
9307   } else {
9308     llvm_unreachable("Unexpected instr type to insert");
9309   }
9310
9311   MI.eraseFromParent(); // The pseudo instruction is gone now.
9312   return BB;
9313 }
9314
9315 //===----------------------------------------------------------------------===//
9316 // Target Optimization Hooks
9317 //===----------------------------------------------------------------------===//
9318
9319 static std::string getRecipOp(const char *Base, EVT VT) {
9320   std::string RecipOp(Base);
9321   if (VT.getScalarType() == MVT::f64)
9322     RecipOp += "d";
9323   else
9324     RecipOp += "f";
9325
9326   if (VT.isVector())
9327     RecipOp = "vec-" + RecipOp;
9328
9329   return RecipOp;
9330 }
9331
9332 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9333                                             DAGCombinerInfo &DCI,
9334                                             unsigned &RefinementSteps,
9335                                             bool &UseOneConstNR) const {
9336   EVT VT = Operand.getValueType();
9337   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9338       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9339       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9340       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9341       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9342       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9343     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9344     std::string RecipOp = getRecipOp("sqrt", VT);
9345     if (!Recips.isEnabled(RecipOp))
9346       return SDValue();
9347
9348     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9349     UseOneConstNR = true;
9350     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9351   }
9352   return SDValue();
9353 }
9354
9355 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9356                                             DAGCombinerInfo &DCI,
9357                                             unsigned &RefinementSteps) const {
9358   EVT VT = Operand.getValueType();
9359   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9360       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9361       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9362       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9363       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9364       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9365     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9366     std::string RecipOp = getRecipOp("div", VT);
9367     if (!Recips.isEnabled(RecipOp))
9368       return SDValue();
9369
9370     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9371     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9372   }
9373   return SDValue();
9374 }
9375
9376 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9377   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9378   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9379   // enabled for division), this functionality is redundant with the default
9380   // combiner logic (once the division -> reciprocal/multiply transformation
9381   // has taken place). As a result, this matters more for older cores than for
9382   // newer ones.
9383
9384   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9385   // reciprocal if there are two or more FDIVs (for embedded cores with only
9386   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9387   switch (Subtarget.getDarwinDirective()) {
9388   default:
9389     return 3;
9390   case PPC::DIR_440:
9391   case PPC::DIR_A2:
9392   case PPC::DIR_E500mc:
9393   case PPC::DIR_E5500:
9394     return 2;
9395   }
9396 }
9397
9398 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9399 // collapsed, and so we need to look through chains of them.
9400 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9401                                      int64_t& Offset, SelectionDAG &DAG) {
9402   if (DAG.isBaseWithConstantOffset(Loc)) {
9403     Base = Loc.getOperand(0);
9404     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9405
9406     // The base might itself be a base plus an offset, and if so, accumulate
9407     // that as well.
9408     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9409   }
9410 }
9411
9412 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9413                             unsigned Bytes, int Dist,
9414                             SelectionDAG &DAG) {
9415   if (VT.getSizeInBits() / 8 != Bytes)
9416     return false;
9417
9418   SDValue BaseLoc = Base->getBasePtr();
9419   if (Loc.getOpcode() == ISD::FrameIndex) {
9420     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9421       return false;
9422     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9423     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9424     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9425     int FS  = MFI->getObjectSize(FI);
9426     int BFS = MFI->getObjectSize(BFI);
9427     if (FS != BFS || FS != (int)Bytes) return false;
9428     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9429   }
9430
9431   SDValue Base1 = Loc, Base2 = BaseLoc;
9432   int64_t Offset1 = 0, Offset2 = 0;
9433   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9434   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9435   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9436     return true;
9437
9438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9439   const GlobalValue *GV1 = nullptr;
9440   const GlobalValue *GV2 = nullptr;
9441   Offset1 = 0;
9442   Offset2 = 0;
9443   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9444   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9445   if (isGA1 && isGA2 && GV1 == GV2)
9446     return Offset1 == (Offset2 + Dist*Bytes);
9447   return false;
9448 }
9449
9450 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9451 // not enforce equality of the chain operands.
9452 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9453                             unsigned Bytes, int Dist,
9454                             SelectionDAG &DAG) {
9455   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9456     EVT VT = LS->getMemoryVT();
9457     SDValue Loc = LS->getBasePtr();
9458     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9459   }
9460
9461   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9462     EVT VT;
9463     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9464     default: return false;
9465     case Intrinsic::ppc_qpx_qvlfd:
9466     case Intrinsic::ppc_qpx_qvlfda:
9467       VT = MVT::v4f64;
9468       break;
9469     case Intrinsic::ppc_qpx_qvlfs:
9470     case Intrinsic::ppc_qpx_qvlfsa:
9471       VT = MVT::v4f32;
9472       break;
9473     case Intrinsic::ppc_qpx_qvlfcd:
9474     case Intrinsic::ppc_qpx_qvlfcda:
9475       VT = MVT::v2f64;
9476       break;
9477     case Intrinsic::ppc_qpx_qvlfcs:
9478     case Intrinsic::ppc_qpx_qvlfcsa:
9479       VT = MVT::v2f32;
9480       break;
9481     case Intrinsic::ppc_qpx_qvlfiwa:
9482     case Intrinsic::ppc_qpx_qvlfiwz:
9483     case Intrinsic::ppc_altivec_lvx:
9484     case Intrinsic::ppc_altivec_lvxl:
9485     case Intrinsic::ppc_vsx_lxvw4x:
9486       VT = MVT::v4i32;
9487       break;
9488     case Intrinsic::ppc_vsx_lxvd2x:
9489       VT = MVT::v2f64;
9490       break;
9491     case Intrinsic::ppc_altivec_lvebx:
9492       VT = MVT::i8;
9493       break;
9494     case Intrinsic::ppc_altivec_lvehx:
9495       VT = MVT::i16;
9496       break;
9497     case Intrinsic::ppc_altivec_lvewx:
9498       VT = MVT::i32;
9499       break;
9500     }
9501
9502     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9503   }
9504
9505   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9506     EVT VT;
9507     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9508     default: return false;
9509     case Intrinsic::ppc_qpx_qvstfd:
9510     case Intrinsic::ppc_qpx_qvstfda:
9511       VT = MVT::v4f64;
9512       break;
9513     case Intrinsic::ppc_qpx_qvstfs:
9514     case Intrinsic::ppc_qpx_qvstfsa:
9515       VT = MVT::v4f32;
9516       break;
9517     case Intrinsic::ppc_qpx_qvstfcd:
9518     case Intrinsic::ppc_qpx_qvstfcda:
9519       VT = MVT::v2f64;
9520       break;
9521     case Intrinsic::ppc_qpx_qvstfcs:
9522     case Intrinsic::ppc_qpx_qvstfcsa:
9523       VT = MVT::v2f32;
9524       break;
9525     case Intrinsic::ppc_qpx_qvstfiw:
9526     case Intrinsic::ppc_qpx_qvstfiwa:
9527     case Intrinsic::ppc_altivec_stvx:
9528     case Intrinsic::ppc_altivec_stvxl:
9529     case Intrinsic::ppc_vsx_stxvw4x:
9530       VT = MVT::v4i32;
9531       break;
9532     case Intrinsic::ppc_vsx_stxvd2x:
9533       VT = MVT::v2f64;
9534       break;
9535     case Intrinsic::ppc_altivec_stvebx:
9536       VT = MVT::i8;
9537       break;
9538     case Intrinsic::ppc_altivec_stvehx:
9539       VT = MVT::i16;
9540       break;
9541     case Intrinsic::ppc_altivec_stvewx:
9542       VT = MVT::i32;
9543       break;
9544     }
9545
9546     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9547   }
9548
9549   return false;
9550 }
9551
9552 // Return true is there is a nearyby consecutive load to the one provided
9553 // (regardless of alignment). We search up and down the chain, looking though
9554 // token factors and other loads (but nothing else). As a result, a true result
9555 // indicates that it is safe to create a new consecutive load adjacent to the
9556 // load provided.
9557 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9558   SDValue Chain = LD->getChain();
9559   EVT VT = LD->getMemoryVT();
9560
9561   SmallSet<SDNode *, 16> LoadRoots;
9562   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9563   SmallSet<SDNode *, 16> Visited;
9564
9565   // First, search up the chain, branching to follow all token-factor operands.
9566   // If we find a consecutive load, then we're done, otherwise, record all
9567   // nodes just above the top-level loads and token factors.
9568   while (!Queue.empty()) {
9569     SDNode *ChainNext = Queue.pop_back_val();
9570     if (!Visited.insert(ChainNext).second)
9571       continue;
9572
9573     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9574       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9575         return true;
9576
9577       if (!Visited.count(ChainLD->getChain().getNode()))
9578         Queue.push_back(ChainLD->getChain().getNode());
9579     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9580       for (const SDUse &O : ChainNext->ops())
9581         if (!Visited.count(O.getNode()))
9582           Queue.push_back(O.getNode());
9583     } else
9584       LoadRoots.insert(ChainNext);
9585   }
9586
9587   // Second, search down the chain, starting from the top-level nodes recorded
9588   // in the first phase. These top-level nodes are the nodes just above all
9589   // loads and token factors. Starting with their uses, recursively look though
9590   // all loads (just the chain uses) and token factors to find a consecutive
9591   // load.
9592   Visited.clear();
9593   Queue.clear();
9594
9595   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9596        IE = LoadRoots.end(); I != IE; ++I) {
9597     Queue.push_back(*I);
9598
9599     while (!Queue.empty()) {
9600       SDNode *LoadRoot = Queue.pop_back_val();
9601       if (!Visited.insert(LoadRoot).second)
9602         continue;
9603
9604       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9605         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9606           return true;
9607
9608       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9609            UE = LoadRoot->use_end(); UI != UE; ++UI)
9610         if (((isa<MemSDNode>(*UI) &&
9611             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9612             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9613           Queue.push_back(*UI);
9614     }
9615   }
9616
9617   return false;
9618 }
9619
9620 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9621                                                   DAGCombinerInfo &DCI) const {
9622   SelectionDAG &DAG = DCI.DAG;
9623   SDLoc dl(N);
9624
9625   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9626   // If we're tracking CR bits, we need to be careful that we don't have:
9627   //   trunc(binary-ops(zext(x), zext(y)))
9628   // or
9629   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9630   // such that we're unnecessarily moving things into GPRs when it would be
9631   // better to keep them in CR bits.
9632
9633   // Note that trunc here can be an actual i1 trunc, or can be the effective
9634   // truncation that comes from a setcc or select_cc.
9635   if (N->getOpcode() == ISD::TRUNCATE &&
9636       N->getValueType(0) != MVT::i1)
9637     return SDValue();
9638
9639   if (N->getOperand(0).getValueType() != MVT::i32 &&
9640       N->getOperand(0).getValueType() != MVT::i64)
9641     return SDValue();
9642
9643   if (N->getOpcode() == ISD::SETCC ||
9644       N->getOpcode() == ISD::SELECT_CC) {
9645     // If we're looking at a comparison, then we need to make sure that the
9646     // high bits (all except for the first) don't matter the result.
9647     ISD::CondCode CC =
9648       cast<CondCodeSDNode>(N->getOperand(
9649         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9650     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9651
9652     if (ISD::isSignedIntSetCC(CC)) {
9653       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9654           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9655         return SDValue();
9656     } else if (ISD::isUnsignedIntSetCC(CC)) {
9657       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9658                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9659           !DAG.MaskedValueIsZero(N->getOperand(1),
9660                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9661         return SDValue();
9662     } else {
9663       // This is neither a signed nor an unsigned comparison, just make sure
9664       // that the high bits are equal.
9665       APInt Op1Zero, Op1One;
9666       APInt Op2Zero, Op2One;
9667       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9668       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9669
9670       // We don't really care about what is known about the first bit (if
9671       // anything), so clear it in all masks prior to comparing them.
9672       Op1Zero.clearBit(0); Op1One.clearBit(0);
9673       Op2Zero.clearBit(0); Op2One.clearBit(0);
9674
9675       if (Op1Zero != Op2Zero || Op1One != Op2One)
9676         return SDValue();
9677     }
9678   }
9679
9680   // We now know that the higher-order bits are irrelevant, we just need to
9681   // make sure that all of the intermediate operations are bit operations, and
9682   // all inputs are extensions.
9683   if (N->getOperand(0).getOpcode() != ISD::AND &&
9684       N->getOperand(0).getOpcode() != ISD::OR  &&
9685       N->getOperand(0).getOpcode() != ISD::XOR &&
9686       N->getOperand(0).getOpcode() != ISD::SELECT &&
9687       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9688       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9689       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9690       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9691       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9692     return SDValue();
9693
9694   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9695       N->getOperand(1).getOpcode() != ISD::AND &&
9696       N->getOperand(1).getOpcode() != ISD::OR  &&
9697       N->getOperand(1).getOpcode() != ISD::XOR &&
9698       N->getOperand(1).getOpcode() != ISD::SELECT &&
9699       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9700       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9701       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9702       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9703       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9704     return SDValue();
9705
9706   SmallVector<SDValue, 4> Inputs;
9707   SmallVector<SDValue, 8> BinOps, PromOps;
9708   SmallPtrSet<SDNode *, 16> Visited;
9709
9710   for (unsigned i = 0; i < 2; ++i) {
9711     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9712           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9713           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9714           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9715         isa<ConstantSDNode>(N->getOperand(i)))
9716       Inputs.push_back(N->getOperand(i));
9717     else
9718       BinOps.push_back(N->getOperand(i));
9719
9720     if (N->getOpcode() == ISD::TRUNCATE)
9721       break;
9722   }
9723
9724   // Visit all inputs, collect all binary operations (and, or, xor and
9725   // select) that are all fed by extensions.
9726   while (!BinOps.empty()) {
9727     SDValue BinOp = BinOps.back();
9728     BinOps.pop_back();
9729
9730     if (!Visited.insert(BinOp.getNode()).second)
9731       continue;
9732
9733     PromOps.push_back(BinOp);
9734
9735     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9736       // The condition of the select is not promoted.
9737       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9738         continue;
9739       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9740         continue;
9741
9742       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9743             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9744             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9745            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9746           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9747         Inputs.push_back(BinOp.getOperand(i));
9748       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9749                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9750                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9751                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9752                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9753                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9754                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9755                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9756                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9757         BinOps.push_back(BinOp.getOperand(i));
9758       } else {
9759         // We have an input that is not an extension or another binary
9760         // operation; we'll abort this transformation.
9761         return SDValue();
9762       }
9763     }
9764   }
9765
9766   // Make sure that this is a self-contained cluster of operations (which
9767   // is not quite the same thing as saying that everything has only one
9768   // use).
9769   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9770     if (isa<ConstantSDNode>(Inputs[i]))
9771       continue;
9772
9773     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9774                               UE = Inputs[i].getNode()->use_end();
9775          UI != UE; ++UI) {
9776       SDNode *User = *UI;
9777       if (User != N && !Visited.count(User))
9778         return SDValue();
9779
9780       // Make sure that we're not going to promote the non-output-value
9781       // operand(s) or SELECT or SELECT_CC.
9782       // FIXME: Although we could sometimes handle this, and it does occur in
9783       // practice that one of the condition inputs to the select is also one of
9784       // the outputs, we currently can't deal with this.
9785       if (User->getOpcode() == ISD::SELECT) {
9786         if (User->getOperand(0) == Inputs[i])
9787           return SDValue();
9788       } else if (User->getOpcode() == ISD::SELECT_CC) {
9789         if (User->getOperand(0) == Inputs[i] ||
9790             User->getOperand(1) == Inputs[i])
9791           return SDValue();
9792       }
9793     }
9794   }
9795
9796   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9797     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9798                               UE = PromOps[i].getNode()->use_end();
9799          UI != UE; ++UI) {
9800       SDNode *User = *UI;
9801       if (User != N && !Visited.count(User))
9802         return SDValue();
9803
9804       // Make sure that we're not going to promote the non-output-value
9805       // operand(s) or SELECT or SELECT_CC.
9806       // FIXME: Although we could sometimes handle this, and it does occur in
9807       // practice that one of the condition inputs to the select is also one of
9808       // the outputs, we currently can't deal with this.
9809       if (User->getOpcode() == ISD::SELECT) {
9810         if (User->getOperand(0) == PromOps[i])
9811           return SDValue();
9812       } else if (User->getOpcode() == ISD::SELECT_CC) {
9813         if (User->getOperand(0) == PromOps[i] ||
9814             User->getOperand(1) == PromOps[i])
9815           return SDValue();
9816       }
9817     }
9818   }
9819
9820   // Replace all inputs with the extension operand.
9821   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9822     // Constants may have users outside the cluster of to-be-promoted nodes,
9823     // and so we need to replace those as we do the promotions.
9824     if (isa<ConstantSDNode>(Inputs[i]))
9825       continue;
9826     else
9827       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9828   }
9829
9830   std::list<HandleSDNode> PromOpHandles;
9831   for (auto &PromOp : PromOps)
9832     PromOpHandles.emplace_back(PromOp);
9833
9834   // Replace all operations (these are all the same, but have a different
9835   // (i1) return type). DAG.getNode will validate that the types of
9836   // a binary operator match, so go through the list in reverse so that
9837   // we've likely promoted both operands first. Any intermediate truncations or
9838   // extensions disappear.
9839   while (!PromOpHandles.empty()) {
9840     SDValue PromOp = PromOpHandles.back().getValue();
9841     PromOpHandles.pop_back();
9842
9843     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9844         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9845         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9846         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9847       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9848           PromOp.getOperand(0).getValueType() != MVT::i1) {
9849         // The operand is not yet ready (see comment below).
9850         PromOpHandles.emplace_front(PromOp);
9851         continue;
9852       }
9853
9854       SDValue RepValue = PromOp.getOperand(0);
9855       if (isa<ConstantSDNode>(RepValue))
9856         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9857
9858       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9859       continue;
9860     }
9861
9862     unsigned C;
9863     switch (PromOp.getOpcode()) {
9864     default:             C = 0; break;
9865     case ISD::SELECT:    C = 1; break;
9866     case ISD::SELECT_CC: C = 2; break;
9867     }
9868
9869     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9870          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9871         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9872          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9873       // The to-be-promoted operands of this node have not yet been
9874       // promoted (this should be rare because we're going through the
9875       // list backward, but if one of the operands has several users in
9876       // this cluster of to-be-promoted nodes, it is possible).
9877       PromOpHandles.emplace_front(PromOp);
9878       continue;
9879     }
9880
9881     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9882                                 PromOp.getNode()->op_end());
9883
9884     // If there are any constant inputs, make sure they're replaced now.
9885     for (unsigned i = 0; i < 2; ++i)
9886       if (isa<ConstantSDNode>(Ops[C+i]))
9887         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9888
9889     DAG.ReplaceAllUsesOfValueWith(PromOp,
9890       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9891   }
9892
9893   // Now we're left with the initial truncation itself.
9894   if (N->getOpcode() == ISD::TRUNCATE)
9895     return N->getOperand(0);
9896
9897   // Otherwise, this is a comparison. The operands to be compared have just
9898   // changed type (to i1), but everything else is the same.
9899   return SDValue(N, 0);
9900 }
9901
9902 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9903                                                   DAGCombinerInfo &DCI) const {
9904   SelectionDAG &DAG = DCI.DAG;
9905   SDLoc dl(N);
9906
9907   // If we're tracking CR bits, we need to be careful that we don't have:
9908   //   zext(binary-ops(trunc(x), trunc(y)))
9909   // or
9910   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9911   // such that we're unnecessarily moving things into CR bits that can more
9912   // efficiently stay in GPRs. Note that if we're not certain that the high
9913   // bits are set as required by the final extension, we still may need to do
9914   // some masking to get the proper behavior.
9915
9916   // This same functionality is important on PPC64 when dealing with
9917   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9918   // the return values of functions. Because it is so similar, it is handled
9919   // here as well.
9920
9921   if (N->getValueType(0) != MVT::i32 &&
9922       N->getValueType(0) != MVT::i64)
9923     return SDValue();
9924
9925   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9926         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9927     return SDValue();
9928
9929   if (N->getOperand(0).getOpcode() != ISD::AND &&
9930       N->getOperand(0).getOpcode() != ISD::OR  &&
9931       N->getOperand(0).getOpcode() != ISD::XOR &&
9932       N->getOperand(0).getOpcode() != ISD::SELECT &&
9933       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9934     return SDValue();
9935
9936   SmallVector<SDValue, 4> Inputs;
9937   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9938   SmallPtrSet<SDNode *, 16> Visited;
9939
9940   // Visit all inputs, collect all binary operations (and, or, xor and
9941   // select) that are all fed by truncations.
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::TRUNCATE ||
9959           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9960         Inputs.push_back(BinOp.getOperand(i));
9961       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9962                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9963                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9964                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9965                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9966         BinOps.push_back(BinOp.getOperand(i));
9967       } else {
9968         // We have an input that is not a truncation or another binary
9969         // operation; we'll abort this transformation.
9970         return SDValue();
9971       }
9972     }
9973   }
9974
9975   // The operands of a select that must be truncated when the select is
9976   // promoted because the operand is actually part of the to-be-promoted set.
9977   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9978
9979   // Make sure that this is a self-contained cluster of operations (which
9980   // is not quite the same thing as saying that everything has only one
9981   // use).
9982   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9983     if (isa<ConstantSDNode>(Inputs[i]))
9984       continue;
9985
9986     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9987                               UE = Inputs[i].getNode()->use_end();
9988          UI != UE; ++UI) {
9989       SDNode *User = *UI;
9990       if (User != N && !Visited.count(User))
9991         return SDValue();
9992
9993       // If we're going to promote the non-output-value operand(s) or SELECT or
9994       // SELECT_CC, record them for truncation.
9995       if (User->getOpcode() == ISD::SELECT) {
9996         if (User->getOperand(0) == Inputs[i])
9997           SelectTruncOp[0].insert(std::make_pair(User,
9998                                     User->getOperand(0).getValueType()));
9999       } else if (User->getOpcode() == ISD::SELECT_CC) {
10000         if (User->getOperand(0) == Inputs[i])
10001           SelectTruncOp[0].insert(std::make_pair(User,
10002                                     User->getOperand(0).getValueType()));
10003         if (User->getOperand(1) == Inputs[i])
10004           SelectTruncOp[1].insert(std::make_pair(User,
10005                                     User->getOperand(1).getValueType()));
10006       }
10007     }
10008   }
10009
10010   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10011     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10012                               UE = PromOps[i].getNode()->use_end();
10013          UI != UE; ++UI) {
10014       SDNode *User = *UI;
10015       if (User != N && !Visited.count(User))
10016         return SDValue();
10017
10018       // If we're going to promote the non-output-value operand(s) or SELECT or
10019       // SELECT_CC, record them for truncation.
10020       if (User->getOpcode() == ISD::SELECT) {
10021         if (User->getOperand(0) == PromOps[i])
10022           SelectTruncOp[0].insert(std::make_pair(User,
10023                                     User->getOperand(0).getValueType()));
10024       } else if (User->getOpcode() == ISD::SELECT_CC) {
10025         if (User->getOperand(0) == PromOps[i])
10026           SelectTruncOp[0].insert(std::make_pair(User,
10027                                     User->getOperand(0).getValueType()));
10028         if (User->getOperand(1) == PromOps[i])
10029           SelectTruncOp[1].insert(std::make_pair(User,
10030                                     User->getOperand(1).getValueType()));
10031       }
10032     }
10033   }
10034
10035   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10036   bool ReallyNeedsExt = false;
10037   if (N->getOpcode() != ISD::ANY_EXTEND) {
10038     // If all of the inputs are not already sign/zero extended, then
10039     // we'll still need to do that at the end.
10040     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10041       if (isa<ConstantSDNode>(Inputs[i]))
10042         continue;
10043
10044       unsigned OpBits =
10045         Inputs[i].getOperand(0).getValueSizeInBits();
10046       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10047
10048       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10049            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10050                                   APInt::getHighBitsSet(OpBits,
10051                                                         OpBits-PromBits))) ||
10052           (N->getOpcode() == ISD::SIGN_EXTEND &&
10053            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10054              (OpBits-(PromBits-1)))) {
10055         ReallyNeedsExt = true;
10056         break;
10057       }
10058     }
10059   }
10060
10061   // Replace all inputs, either with the truncation operand, or a
10062   // truncation or extension to the final output type.
10063   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10064     // Constant inputs need to be replaced with the to-be-promoted nodes that
10065     // use them because they might have users outside of the cluster of
10066     // promoted nodes.
10067     if (isa<ConstantSDNode>(Inputs[i]))
10068       continue;
10069
10070     SDValue InSrc = Inputs[i].getOperand(0);
10071     if (Inputs[i].getValueType() == N->getValueType(0))
10072       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10073     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10074       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10075         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10076     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10077       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10078         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10079     else
10080       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10081         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10082   }
10083
10084   std::list<HandleSDNode> PromOpHandles;
10085   for (auto &PromOp : PromOps)
10086     PromOpHandles.emplace_back(PromOp);
10087
10088   // Replace all operations (these are all the same, but have a different
10089   // (promoted) return type). DAG.getNode will validate that the types of
10090   // a binary operator match, so go through the list in reverse so that
10091   // we've likely promoted both operands first.
10092   while (!PromOpHandles.empty()) {
10093     SDValue PromOp = PromOpHandles.back().getValue();
10094     PromOpHandles.pop_back();
10095
10096     unsigned C;
10097     switch (PromOp.getOpcode()) {
10098     default:             C = 0; break;
10099     case ISD::SELECT:    C = 1; break;
10100     case ISD::SELECT_CC: C = 2; break;
10101     }
10102
10103     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10104          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10105         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10106          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10107       // The to-be-promoted operands of this node have not yet been
10108       // promoted (this should be rare because we're going through the
10109       // list backward, but if one of the operands has several users in
10110       // this cluster of to-be-promoted nodes, it is possible).
10111       PromOpHandles.emplace_front(PromOp);
10112       continue;
10113     }
10114
10115     // For SELECT and SELECT_CC nodes, we do a similar check for any
10116     // to-be-promoted comparison inputs.
10117     if (PromOp.getOpcode() == ISD::SELECT ||
10118         PromOp.getOpcode() == ISD::SELECT_CC) {
10119       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10120            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10121           (SelectTruncOp[1].count(PromOp.getNode()) &&
10122            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10123         PromOpHandles.emplace_front(PromOp);
10124         continue;
10125       }
10126     }
10127
10128     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10129                                 PromOp.getNode()->op_end());
10130
10131     // If this node has constant inputs, then they'll need to be promoted here.
10132     for (unsigned i = 0; i < 2; ++i) {
10133       if (!isa<ConstantSDNode>(Ops[C+i]))
10134         continue;
10135       if (Ops[C+i].getValueType() == N->getValueType(0))
10136         continue;
10137
10138       if (N->getOpcode() == ISD::SIGN_EXTEND)
10139         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10140       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10141         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10142       else
10143         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10144     }
10145
10146     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10147     // truncate them again to the original value type.
10148     if (PromOp.getOpcode() == ISD::SELECT ||
10149         PromOp.getOpcode() == ISD::SELECT_CC) {
10150       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10151       if (SI0 != SelectTruncOp[0].end())
10152         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10153       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10154       if (SI1 != SelectTruncOp[1].end())
10155         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10156     }
10157
10158     DAG.ReplaceAllUsesOfValueWith(PromOp,
10159       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10160   }
10161
10162   // Now we're left with the initial extension itself.
10163   if (!ReallyNeedsExt)
10164     return N->getOperand(0);
10165
10166   // To zero extend, just mask off everything except for the first bit (in the
10167   // i1 case).
10168   if (N->getOpcode() == ISD::ZERO_EXTEND)
10169     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10170                        DAG.getConstant(APInt::getLowBitsSet(
10171                                          N->getValueSizeInBits(0), PromBits),
10172                                        dl, N->getValueType(0)));
10173
10174   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10175          "Invalid extension type");
10176   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10177   SDValue ShiftCst =
10178       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10179   return DAG.getNode(
10180       ISD::SRA, dl, N->getValueType(0),
10181       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10182       ShiftCst);
10183 }
10184
10185 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10186                                                  DAGCombinerInfo &DCI) const {
10187   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10188          "Should be called with a BUILD_VECTOR node");
10189
10190   SelectionDAG &DAG = DCI.DAG;
10191   SDLoc dl(N);
10192   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10193     return SDValue();
10194
10195   // Looking for:
10196   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10197   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10198       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10199     return SDValue();
10200   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10201       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10202     return SDValue();
10203   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10204     return SDValue();
10205
10206   SDValue Ext1 = N->getOperand(0).getOperand(0);
10207   SDValue Ext2 = N->getOperand(1).getOperand(0);
10208   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10209      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10210     return SDValue();
10211
10212   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10213   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10214   if (!Ext1Op || !Ext2Op)
10215     return SDValue();
10216   if (Ext1.getValueType() != MVT::i32 ||
10217       Ext2.getValueType() != MVT::i32)
10218   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10219     return SDValue();
10220
10221   int FirstElem = Ext1Op->getZExtValue();
10222   int SecondElem = Ext2Op->getZExtValue();
10223   int SubvecIdx;
10224   if (FirstElem == 0 && SecondElem == 1)
10225     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10226   else if (FirstElem == 2 && SecondElem == 3)
10227     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10228   else
10229     return SDValue();
10230
10231   SDValue SrcVec = Ext1.getOperand(0);
10232   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10233     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10234   return DAG.getNode(NodeType, dl, MVT::v2f64,
10235                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10236 }
10237
10238 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10239                                               DAGCombinerInfo &DCI) const {
10240   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10241           N->getOpcode() == ISD::UINT_TO_FP) &&
10242          "Need an int -> FP conversion node here");
10243
10244   if (!Subtarget.has64BitSupport())
10245     return SDValue();
10246
10247   SelectionDAG &DAG = DCI.DAG;
10248   SDLoc dl(N);
10249   SDValue Op(N, 0);
10250
10251   // Don't handle ppc_fp128 here or i1 conversions.
10252   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10253     return SDValue();
10254   if (Op.getOperand(0).getValueType() == MVT::i1)
10255     return SDValue();
10256
10257   // For i32 intermediate values, unfortunately, the conversion functions
10258   // leave the upper 32 bits of the value are undefined. Within the set of
10259   // scalar instructions, we have no method for zero- or sign-extending the
10260   // value. Thus, we cannot handle i32 intermediate values here.
10261   if (Op.getOperand(0).getValueType() == MVT::i32)
10262     return SDValue();
10263
10264   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10265          "UINT_TO_FP is supported only with FPCVT");
10266
10267   // If we have FCFIDS, then use it when converting to single-precision.
10268   // Otherwise, convert to double-precision and then round.
10269   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10270                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10271                                                             : PPCISD::FCFIDS)
10272                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10273                                                             : PPCISD::FCFID);
10274   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10275                   ? MVT::f32
10276                   : MVT::f64;
10277
10278   // If we're converting from a float, to an int, and back to a float again,
10279   // then we don't need the store/load pair at all.
10280   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10281        Subtarget.hasFPCVT()) ||
10282       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10283     SDValue Src = Op.getOperand(0).getOperand(0);
10284     if (Src.getValueType() == MVT::f32) {
10285       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10286       DCI.AddToWorklist(Src.getNode());
10287     } else if (Src.getValueType() != MVT::f64) {
10288       // Make sure that we don't pick up a ppc_fp128 source value.
10289       return SDValue();
10290     }
10291
10292     unsigned FCTOp =
10293       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10294                                                         PPCISD::FCTIDUZ;
10295
10296     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10297     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10298
10299     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10300       FP = DAG.getNode(ISD::FP_ROUND, dl,
10301                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10302       DCI.AddToWorklist(FP.getNode());
10303     }
10304
10305     return FP;
10306   }
10307
10308   return SDValue();
10309 }
10310
10311 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10312 // builtins) into loads with swaps.
10313 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10314                                               DAGCombinerInfo &DCI) const {
10315   SelectionDAG &DAG = DCI.DAG;
10316   SDLoc dl(N);
10317   SDValue Chain;
10318   SDValue Base;
10319   MachineMemOperand *MMO;
10320
10321   switch (N->getOpcode()) {
10322   default:
10323     llvm_unreachable("Unexpected opcode for little endian VSX load");
10324   case ISD::LOAD: {
10325     LoadSDNode *LD = cast<LoadSDNode>(N);
10326     Chain = LD->getChain();
10327     Base = LD->getBasePtr();
10328     MMO = LD->getMemOperand();
10329     // If the MMO suggests this isn't a load of a full vector, leave
10330     // things alone.  For a built-in, we have to make the change for
10331     // correctness, so if there is a size problem that will be a bug.
10332     if (MMO->getSize() < 16)
10333       return SDValue();
10334     break;
10335   }
10336   case ISD::INTRINSIC_W_CHAIN: {
10337     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10338     Chain = Intrin->getChain();
10339     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10340     // us what we want. Get operand 2 instead.
10341     Base = Intrin->getOperand(2);
10342     MMO = Intrin->getMemOperand();
10343     break;
10344   }
10345   }
10346
10347   MVT VecTy = N->getValueType(0).getSimpleVT();
10348   SDValue LoadOps[] = { Chain, Base };
10349   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10350                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10351                                          LoadOps, MVT::v2f64, MMO);
10352
10353   DCI.AddToWorklist(Load.getNode());
10354   Chain = Load.getValue(1);
10355   SDValue Swap = DAG.getNode(
10356       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10357   DCI.AddToWorklist(Swap.getNode());
10358
10359   // Add a bitcast if the resulting load type doesn't match v2f64.
10360   if (VecTy != MVT::v2f64) {
10361     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10362     DCI.AddToWorklist(N.getNode());
10363     // Package {bitcast value, swap's chain} to match Load's shape.
10364     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10365                        N, Swap.getValue(1));
10366   }
10367
10368   return Swap;
10369 }
10370
10371 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10372 // builtins) into stores with swaps.
10373 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10374                                                DAGCombinerInfo &DCI) const {
10375   SelectionDAG &DAG = DCI.DAG;
10376   SDLoc dl(N);
10377   SDValue Chain;
10378   SDValue Base;
10379   unsigned SrcOpnd;
10380   MachineMemOperand *MMO;
10381
10382   switch (N->getOpcode()) {
10383   default:
10384     llvm_unreachable("Unexpected opcode for little endian VSX store");
10385   case ISD::STORE: {
10386     StoreSDNode *ST = cast<StoreSDNode>(N);
10387     Chain = ST->getChain();
10388     Base = ST->getBasePtr();
10389     MMO = ST->getMemOperand();
10390     SrcOpnd = 1;
10391     // If the MMO suggests this isn't a store of a full vector, leave
10392     // things alone.  For a built-in, we have to make the change for
10393     // correctness, so if there is a size problem that will be a bug.
10394     if (MMO->getSize() < 16)
10395       return SDValue();
10396     break;
10397   }
10398   case ISD::INTRINSIC_VOID: {
10399     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10400     Chain = Intrin->getChain();
10401     // Intrin->getBasePtr() oddly does not get what we want.
10402     Base = Intrin->getOperand(3);
10403     MMO = Intrin->getMemOperand();
10404     SrcOpnd = 2;
10405     break;
10406   }
10407   }
10408
10409   SDValue Src = N->getOperand(SrcOpnd);
10410   MVT VecTy = Src.getValueType().getSimpleVT();
10411
10412   // All stores are done as v2f64 and possible bit cast.
10413   if (VecTy != MVT::v2f64) {
10414     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10415     DCI.AddToWorklist(Src.getNode());
10416   }
10417
10418   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10419                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10420   DCI.AddToWorklist(Swap.getNode());
10421   Chain = Swap.getValue(1);
10422   SDValue StoreOps[] = { Chain, Swap, Base };
10423   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10424                                           DAG.getVTList(MVT::Other),
10425                                           StoreOps, VecTy, MMO);
10426   DCI.AddToWorklist(Store.getNode());
10427   return Store;
10428 }
10429
10430 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10431                                              DAGCombinerInfo &DCI) const {
10432   SelectionDAG &DAG = DCI.DAG;
10433   SDLoc dl(N);
10434   switch (N->getOpcode()) {
10435   default: break;
10436   case PPCISD::SHL:
10437     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10438         return N->getOperand(0);
10439     break;
10440   case PPCISD::SRL:
10441     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10442         return N->getOperand(0);
10443     break;
10444   case PPCISD::SRA:
10445     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10446       if (C->isNullValue() ||   //  0 >>s V -> 0.
10447           C->isAllOnesValue())    // -1 >>s V -> -1.
10448         return N->getOperand(0);
10449     }
10450     break;
10451   case ISD::SIGN_EXTEND:
10452   case ISD::ZERO_EXTEND:
10453   case ISD::ANY_EXTEND:
10454     return DAGCombineExtBoolTrunc(N, DCI);
10455   case ISD::TRUNCATE:
10456   case ISD::SETCC:
10457   case ISD::SELECT_CC:
10458     return DAGCombineTruncBoolExt(N, DCI);
10459   case ISD::SINT_TO_FP:
10460   case ISD::UINT_TO_FP:
10461     return combineFPToIntToFP(N, DCI);
10462   case ISD::STORE: {
10463     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10464     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10465         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10466         N->getOperand(1).getValueType() == MVT::i32 &&
10467         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10468       SDValue Val = N->getOperand(1).getOperand(0);
10469       if (Val.getValueType() == MVT::f32) {
10470         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10471         DCI.AddToWorklist(Val.getNode());
10472       }
10473       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10474       DCI.AddToWorklist(Val.getNode());
10475
10476       SDValue Ops[] = {
10477         N->getOperand(0), Val, N->getOperand(2),
10478         DAG.getValueType(N->getOperand(1).getValueType())
10479       };
10480
10481       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10482               DAG.getVTList(MVT::Other), Ops,
10483               cast<StoreSDNode>(N)->getMemoryVT(),
10484               cast<StoreSDNode>(N)->getMemOperand());
10485       DCI.AddToWorklist(Val.getNode());
10486       return Val;
10487     }
10488
10489     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10490     if (cast<StoreSDNode>(N)->isUnindexed() &&
10491         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10492         N->getOperand(1).getNode()->hasOneUse() &&
10493         (N->getOperand(1).getValueType() == MVT::i32 ||
10494          N->getOperand(1).getValueType() == MVT::i16 ||
10495          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10496           N->getOperand(1).getValueType() == MVT::i64))) {
10497       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10498       // Do an any-extend to 32-bits if this is a half-word input.
10499       if (BSwapOp.getValueType() == MVT::i16)
10500         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10501
10502       SDValue Ops[] = {
10503         N->getOperand(0), BSwapOp, N->getOperand(2),
10504         DAG.getValueType(N->getOperand(1).getValueType())
10505       };
10506       return
10507         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10508                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10509                                 cast<StoreSDNode>(N)->getMemOperand());
10510     }
10511
10512     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10513     EVT VT = N->getOperand(1).getValueType();
10514     if (VT.isSimple()) {
10515       MVT StoreVT = VT.getSimpleVT();
10516       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10517           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10518            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10519         return expandVSXStoreForLE(N, DCI);
10520     }
10521     break;
10522   }
10523   case ISD::LOAD: {
10524     LoadSDNode *LD = cast<LoadSDNode>(N);
10525     EVT VT = LD->getValueType(0);
10526
10527     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10528     if (VT.isSimple()) {
10529       MVT LoadVT = VT.getSimpleVT();
10530       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10531           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10532            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10533         return expandVSXLoadForLE(N, DCI);
10534     }
10535
10536     // We sometimes end up with a 64-bit integer load, from which we extract
10537     // two single-precision floating-point numbers. This happens with
10538     // std::complex<float>, and other similar structures, because of the way we
10539     // canonicalize structure copies. However, if we lack direct moves,
10540     // then the final bitcasts from the extracted integer values to the
10541     // floating-point numbers turn into store/load pairs. Even with direct moves,
10542     // just loading the two floating-point numbers is likely better.
10543     auto ReplaceTwoFloatLoad = [&]() {
10544       if (VT != MVT::i64)
10545         return false;
10546
10547       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10548           LD->isVolatile())
10549         return false;
10550
10551       //  We're looking for a sequence like this:
10552       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10553       //      t16: i64 = srl t13, Constant:i32<32>
10554       //    t17: i32 = truncate t16
10555       //  t18: f32 = bitcast t17
10556       //    t19: i32 = truncate t13
10557       //  t20: f32 = bitcast t19
10558
10559       if (!LD->hasNUsesOfValue(2, 0))
10560         return false;
10561
10562       auto UI = LD->use_begin();
10563       while (UI.getUse().getResNo() != 0) ++UI;
10564       SDNode *Trunc = *UI++;
10565       while (UI.getUse().getResNo() != 0) ++UI;
10566       SDNode *RightShift = *UI;
10567       if (Trunc->getOpcode() != ISD::TRUNCATE)
10568         std::swap(Trunc, RightShift);
10569
10570       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10571           Trunc->getValueType(0) != MVT::i32 ||
10572           !Trunc->hasOneUse())
10573         return false;
10574       if (RightShift->getOpcode() != ISD::SRL ||
10575           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10576           RightShift->getConstantOperandVal(1) != 32 ||
10577           !RightShift->hasOneUse())
10578         return false;
10579
10580       SDNode *Trunc2 = *RightShift->use_begin();
10581       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10582           Trunc2->getValueType(0) != MVT::i32 ||
10583           !Trunc2->hasOneUse())
10584         return false;
10585
10586       SDNode *Bitcast = *Trunc->use_begin();
10587       SDNode *Bitcast2 = *Trunc2->use_begin();
10588
10589       if (Bitcast->getOpcode() != ISD::BITCAST ||
10590           Bitcast->getValueType(0) != MVT::f32)
10591         return false;
10592       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10593           Bitcast2->getValueType(0) != MVT::f32)
10594         return false;
10595
10596       if (Subtarget.isLittleEndian())
10597         std::swap(Bitcast, Bitcast2);
10598
10599       // Bitcast has the second float (in memory-layout order) and Bitcast2
10600       // has the first one.
10601
10602       SDValue BasePtr = LD->getBasePtr();
10603       if (LD->isIndexed()) {
10604         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10605                "Non-pre-inc AM on PPC?");
10606         BasePtr =
10607           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10608                       LD->getOffset());
10609       }
10610
10611       SDValue FloatLoad =
10612         DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10613                     LD->getPointerInfo(), false, LD->isNonTemporal(),
10614                     LD->isInvariant(), LD->getAlignment(), LD->getAAInfo());
10615       SDValue AddPtr =
10616         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10617                     BasePtr, DAG.getIntPtrConstant(4, dl));
10618       SDValue FloatLoad2 =
10619         DAG.getLoad(MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10620                     LD->getPointerInfo().getWithOffset(4), false,
10621                     LD->isNonTemporal(), LD->isInvariant(),
10622                     MinAlign(LD->getAlignment(), 4), LD->getAAInfo());
10623
10624       if (LD->isIndexed()) {
10625         // Note that DAGCombine should re-form any pre-increment load(s) from
10626         // what is produced here if that makes sense.
10627         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10628       }
10629
10630       DCI.CombineTo(Bitcast2, FloatLoad);
10631       DCI.CombineTo(Bitcast, FloatLoad2);
10632
10633       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10634                                     SDValue(FloatLoad2.getNode(), 1));
10635       return true;
10636     };
10637
10638     if (ReplaceTwoFloatLoad())
10639       return SDValue(N, 0);
10640
10641     EVT MemVT = LD->getMemoryVT();
10642     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10643     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10644     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10645     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10646     if (LD->isUnindexed() && VT.isVector() &&
10647         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10648           // P8 and later hardware should just use LOAD.
10649           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10650                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10651          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10652           LD->getAlignment() >= ScalarABIAlignment)) &&
10653         LD->getAlignment() < ABIAlignment) {
10654       // This is a type-legal unaligned Altivec or QPX load.
10655       SDValue Chain = LD->getChain();
10656       SDValue Ptr = LD->getBasePtr();
10657       bool isLittleEndian = Subtarget.isLittleEndian();
10658
10659       // This implements the loading of unaligned vectors as described in
10660       // the venerable Apple Velocity Engine overview. Specifically:
10661       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10662       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10663       //
10664       // The general idea is to expand a sequence of one or more unaligned
10665       // loads into an alignment-based permutation-control instruction (lvsl
10666       // or lvsr), a series of regular vector loads (which always truncate
10667       // their input address to an aligned address), and a series of
10668       // permutations.  The results of these permutations are the requested
10669       // loaded values.  The trick is that the last "extra" load is not taken
10670       // from the address you might suspect (sizeof(vector) bytes after the
10671       // last requested load), but rather sizeof(vector) - 1 bytes after the
10672       // last requested vector. The point of this is to avoid a page fault if
10673       // the base address happened to be aligned. This works because if the
10674       // base address is aligned, then adding less than a full vector length
10675       // will cause the last vector in the sequence to be (re)loaded.
10676       // Otherwise, the next vector will be fetched as you might suspect was
10677       // necessary.
10678
10679       // We might be able to reuse the permutation generation from
10680       // a different base address offset from this one by an aligned amount.
10681       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10682       // optimization later.
10683       Intrinsic::ID Intr, IntrLD, IntrPerm;
10684       MVT PermCntlTy, PermTy, LDTy;
10685       if (Subtarget.hasAltivec()) {
10686         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10687                                  Intrinsic::ppc_altivec_lvsl;
10688         IntrLD = Intrinsic::ppc_altivec_lvx;
10689         IntrPerm = Intrinsic::ppc_altivec_vperm;
10690         PermCntlTy = MVT::v16i8;
10691         PermTy = MVT::v4i32;
10692         LDTy = MVT::v4i32;
10693       } else {
10694         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10695                                        Intrinsic::ppc_qpx_qvlpcls;
10696         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10697                                        Intrinsic::ppc_qpx_qvlfs;
10698         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10699         PermCntlTy = MVT::v4f64;
10700         PermTy = MVT::v4f64;
10701         LDTy = MemVT.getSimpleVT();
10702       }
10703
10704       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10705
10706       // Create the new MMO for the new base load. It is like the original MMO,
10707       // but represents an area in memory almost twice the vector size centered
10708       // on the original address. If the address is unaligned, we might start
10709       // reading up to (sizeof(vector)-1) bytes below the address of the
10710       // original unaligned load.
10711       MachineFunction &MF = DAG.getMachineFunction();
10712       MachineMemOperand *BaseMMO =
10713         MF.getMachineMemOperand(LD->getMemOperand(),
10714                                 -(long)MemVT.getStoreSize()+1,
10715                                 2*MemVT.getStoreSize()-1);
10716
10717       // Create the new base load.
10718       SDValue LDXIntID =
10719           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10720       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10721       SDValue BaseLoad =
10722         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10723                                 DAG.getVTList(PermTy, MVT::Other),
10724                                 BaseLoadOps, LDTy, BaseMMO);
10725
10726       // Note that the value of IncOffset (which is provided to the next
10727       // load's pointer info offset value, and thus used to calculate the
10728       // alignment), and the value of IncValue (which is actually used to
10729       // increment the pointer value) are different! This is because we
10730       // require the next load to appear to be aligned, even though it
10731       // is actually offset from the base pointer by a lesser amount.
10732       int IncOffset = VT.getSizeInBits() / 8;
10733       int IncValue = IncOffset;
10734
10735       // Walk (both up and down) the chain looking for another load at the real
10736       // (aligned) offset (the alignment of the other load does not matter in
10737       // this case). If found, then do not use the offset reduction trick, as
10738       // that will prevent the loads from being later combined (as they would
10739       // otherwise be duplicates).
10740       if (!findConsecutiveLoad(LD, DAG))
10741         --IncValue;
10742
10743       SDValue Increment =
10744           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10745       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10746
10747       MachineMemOperand *ExtraMMO =
10748         MF.getMachineMemOperand(LD->getMemOperand(),
10749                                 1, 2*MemVT.getStoreSize()-1);
10750       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10751       SDValue ExtraLoad =
10752         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10753                                 DAG.getVTList(PermTy, MVT::Other),
10754                                 ExtraLoadOps, LDTy, ExtraMMO);
10755
10756       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10757         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10758
10759       // Because vperm has a big-endian bias, we must reverse the order
10760       // of the input vectors and complement the permute control vector
10761       // when generating little endian code.  We have already handled the
10762       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10763       // and ExtraLoad here.
10764       SDValue Perm;
10765       if (isLittleEndian)
10766         Perm = BuildIntrinsicOp(IntrPerm,
10767                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10768       else
10769         Perm = BuildIntrinsicOp(IntrPerm,
10770                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10771
10772       if (VT != PermTy)
10773         Perm = Subtarget.hasAltivec() ?
10774                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10775                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10776                                DAG.getTargetConstant(1, dl, MVT::i64));
10777                                // second argument is 1 because this rounding
10778                                // is always exact.
10779
10780       // The output of the permutation is our loaded result, the TokenFactor is
10781       // our new chain.
10782       DCI.CombineTo(N, Perm, TF);
10783       return SDValue(N, 0);
10784     }
10785     }
10786     break;
10787     case ISD::INTRINSIC_WO_CHAIN: {
10788       bool isLittleEndian = Subtarget.isLittleEndian();
10789       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10790       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10791                                            : Intrinsic::ppc_altivec_lvsl);
10792       if ((IID == Intr ||
10793            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10794            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10795         N->getOperand(1)->getOpcode() == ISD::ADD) {
10796         SDValue Add = N->getOperand(1);
10797
10798         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10799                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10800
10801         if (DAG.MaskedValueIsZero(
10802                 Add->getOperand(1),
10803                 APInt::getAllOnesValue(Bits /* alignment */)
10804                     .zext(
10805                         Add.getValueType().getScalarType().getSizeInBits()))) {
10806           SDNode *BasePtr = Add->getOperand(0).getNode();
10807           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10808                                     UE = BasePtr->use_end();
10809                UI != UE; ++UI) {
10810             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10811                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10812               // We've found another LVSL/LVSR, and this address is an aligned
10813               // multiple of that one. The results will be the same, so use the
10814               // one we've just found instead.
10815
10816               return SDValue(*UI, 0);
10817             }
10818           }
10819         }
10820
10821         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10822           SDNode *BasePtr = Add->getOperand(0).getNode();
10823           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10824                UE = BasePtr->use_end(); UI != UE; ++UI) {
10825             if (UI->getOpcode() == ISD::ADD &&
10826                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10827                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10828                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10829                 (1ULL << Bits) == 0) {
10830               SDNode *OtherAdd = *UI;
10831               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10832                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10833                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10834                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10835                   return SDValue(*VI, 0);
10836                 }
10837               }
10838             }
10839           }
10840         }
10841       }
10842     }
10843
10844     break;
10845   case ISD::INTRINSIC_W_CHAIN: {
10846     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10847     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10848       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10849       default:
10850         break;
10851       case Intrinsic::ppc_vsx_lxvw4x:
10852       case Intrinsic::ppc_vsx_lxvd2x:
10853         return expandVSXLoadForLE(N, DCI);
10854       }
10855     }
10856     break;
10857   }
10858   case ISD::INTRINSIC_VOID: {
10859     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10860     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10861       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10862       default:
10863         break;
10864       case Intrinsic::ppc_vsx_stxvw4x:
10865       case Intrinsic::ppc_vsx_stxvd2x:
10866         return expandVSXStoreForLE(N, DCI);
10867       }
10868     }
10869     break;
10870   }
10871   case ISD::BSWAP:
10872     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10873     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10874         N->getOperand(0).hasOneUse() &&
10875         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10876          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10877           N->getValueType(0) == MVT::i64))) {
10878       SDValue Load = N->getOperand(0);
10879       LoadSDNode *LD = cast<LoadSDNode>(Load);
10880       // Create the byte-swapping load.
10881       SDValue Ops[] = {
10882         LD->getChain(),    // Chain
10883         LD->getBasePtr(),  // Ptr
10884         DAG.getValueType(N->getValueType(0)) // VT
10885       };
10886       SDValue BSLoad =
10887         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10888                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10889                                               MVT::i64 : MVT::i32, MVT::Other),
10890                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10891
10892       // If this is an i16 load, insert the truncate.
10893       SDValue ResVal = BSLoad;
10894       if (N->getValueType(0) == MVT::i16)
10895         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10896
10897       // First, combine the bswap away.  This makes the value produced by the
10898       // load dead.
10899       DCI.CombineTo(N, ResVal);
10900
10901       // Next, combine the load away, we give it a bogus result value but a real
10902       // chain result.  The result value is dead because the bswap is dead.
10903       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10904
10905       // Return N so it doesn't get rechecked!
10906       return SDValue(N, 0);
10907     }
10908
10909     break;
10910   case PPCISD::VCMP: {
10911     // If a VCMPo node already exists with exactly the same operands as this
10912     // node, use its result instead of this node (VCMPo computes both a CR6 and
10913     // a normal output).
10914     //
10915     if (!N->getOperand(0).hasOneUse() &&
10916         !N->getOperand(1).hasOneUse() &&
10917         !N->getOperand(2).hasOneUse()) {
10918
10919       // Scan all of the users of the LHS, looking for VCMPo's that match.
10920       SDNode *VCMPoNode = nullptr;
10921
10922       SDNode *LHSN = N->getOperand(0).getNode();
10923       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10924            UI != E; ++UI)
10925         if (UI->getOpcode() == PPCISD::VCMPo &&
10926             UI->getOperand(1) == N->getOperand(1) &&
10927             UI->getOperand(2) == N->getOperand(2) &&
10928             UI->getOperand(0) == N->getOperand(0)) {
10929           VCMPoNode = *UI;
10930           break;
10931         }
10932
10933       // If there is no VCMPo node, or if the flag value has a single use, don't
10934       // transform this.
10935       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10936         break;
10937
10938       // Look at the (necessarily single) use of the flag value.  If it has a
10939       // chain, this transformation is more complex.  Note that multiple things
10940       // could use the value result, which we should ignore.
10941       SDNode *FlagUser = nullptr;
10942       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10943            FlagUser == nullptr; ++UI) {
10944         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10945         SDNode *User = *UI;
10946         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10947           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10948             FlagUser = User;
10949             break;
10950           }
10951         }
10952       }
10953
10954       // If the user is a MFOCRF instruction, we know this is safe.
10955       // Otherwise we give up for right now.
10956       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10957         return SDValue(VCMPoNode, 0);
10958     }
10959     break;
10960   }
10961   case ISD::BRCOND: {
10962     SDValue Cond = N->getOperand(1);
10963     SDValue Target = N->getOperand(2);
10964
10965     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10966         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10967           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10968
10969       // We now need to make the intrinsic dead (it cannot be instruction
10970       // selected).
10971       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10972       assert(Cond.getNode()->hasOneUse() &&
10973              "Counter decrement has more than one use");
10974
10975       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10976                          N->getOperand(0), Target);
10977     }
10978   }
10979   break;
10980   case ISD::BR_CC: {
10981     // If this is a branch on an altivec predicate comparison, lower this so
10982     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10983     // lowering is done pre-legalize, because the legalizer lowers the predicate
10984     // compare down to code that is difficult to reassemble.
10985     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10986     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10987
10988     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10989     // value. If so, pass-through the AND to get to the intrinsic.
10990     if (LHS.getOpcode() == ISD::AND &&
10991         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10992         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10993           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10994         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10995         !isNullConstant(LHS.getOperand(1)))
10996       LHS = LHS.getOperand(0);
10997
10998     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10999         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11000           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11001         isa<ConstantSDNode>(RHS)) {
11002       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11003              "Counter decrement comparison is not EQ or NE");
11004
11005       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11006       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11007                     (CC == ISD::SETNE && !Val);
11008
11009       // We now need to make the intrinsic dead (it cannot be instruction
11010       // selected).
11011       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11012       assert(LHS.getNode()->hasOneUse() &&
11013              "Counter decrement has more than one use");
11014
11015       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11016                          N->getOperand(0), N->getOperand(4));
11017     }
11018
11019     int CompareOpc;
11020     bool isDot;
11021
11022     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11023         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11024         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11025       assert(isDot && "Can't compare against a vector result!");
11026
11027       // If this is a comparison against something other than 0/1, then we know
11028       // that the condition is never/always true.
11029       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11030       if (Val != 0 && Val != 1) {
11031         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11032           return N->getOperand(0);
11033         // Always !=, turn it into an unconditional branch.
11034         return DAG.getNode(ISD::BR, dl, MVT::Other,
11035                            N->getOperand(0), N->getOperand(4));
11036       }
11037
11038       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11039
11040       // Create the PPCISD altivec 'dot' comparison node.
11041       SDValue Ops[] = {
11042         LHS.getOperand(2),  // LHS of compare
11043         LHS.getOperand(3),  // RHS of compare
11044         DAG.getConstant(CompareOpc, dl, MVT::i32)
11045       };
11046       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11047       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11048
11049       // Unpack the result based on how the target uses it.
11050       PPC::Predicate CompOpc;
11051       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11052       default:  // Can't happen, don't crash on invalid number though.
11053       case 0:   // Branch on the value of the EQ bit of CR6.
11054         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11055         break;
11056       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11057         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11058         break;
11059       case 2:   // Branch on the value of the LT bit of CR6.
11060         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11061         break;
11062       case 3:   // Branch on the inverted value of the LT bit of CR6.
11063         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11064         break;
11065       }
11066
11067       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11068                          DAG.getConstant(CompOpc, dl, MVT::i32),
11069                          DAG.getRegister(PPC::CR6, MVT::i32),
11070                          N->getOperand(4), CompNode.getValue(1));
11071     }
11072     break;
11073   }
11074   case ISD::BUILD_VECTOR:
11075     return DAGCombineBuildVector(N, DCI);
11076   }
11077
11078   return SDValue();
11079 }
11080
11081 SDValue
11082 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11083                                   SelectionDAG &DAG,
11084                                   std::vector<SDNode *> *Created) const {
11085   // fold (sdiv X, pow2)
11086   EVT VT = N->getValueType(0);
11087   if (VT == MVT::i64 && !Subtarget.isPPC64())
11088     return SDValue();
11089   if ((VT != MVT::i32 && VT != MVT::i64) ||
11090       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11091     return SDValue();
11092
11093   SDLoc DL(N);
11094   SDValue N0 = N->getOperand(0);
11095
11096   bool IsNegPow2 = (-Divisor).isPowerOf2();
11097   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11098   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11099
11100   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11101   if (Created)
11102     Created->push_back(Op.getNode());
11103
11104   if (IsNegPow2) {
11105     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11106     if (Created)
11107       Created->push_back(Op.getNode());
11108   }
11109
11110   return Op;
11111 }
11112
11113 //===----------------------------------------------------------------------===//
11114 // Inline Assembly Support
11115 //===----------------------------------------------------------------------===//
11116
11117 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11118                                                       APInt &KnownZero,
11119                                                       APInt &KnownOne,
11120                                                       const SelectionDAG &DAG,
11121                                                       unsigned Depth) const {
11122   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11123   switch (Op.getOpcode()) {
11124   default: break;
11125   case PPCISD::LBRX: {
11126     // lhbrx is known to have the top bits cleared out.
11127     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11128       KnownZero = 0xFFFF0000;
11129     break;
11130   }
11131   case ISD::INTRINSIC_WO_CHAIN: {
11132     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11133     default: break;
11134     case Intrinsic::ppc_altivec_vcmpbfp_p:
11135     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11136     case Intrinsic::ppc_altivec_vcmpequb_p:
11137     case Intrinsic::ppc_altivec_vcmpequh_p:
11138     case Intrinsic::ppc_altivec_vcmpequw_p:
11139     case Intrinsic::ppc_altivec_vcmpequd_p:
11140     case Intrinsic::ppc_altivec_vcmpgefp_p:
11141     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11142     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11143     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11144     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11145     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11146     case Intrinsic::ppc_altivec_vcmpgtub_p:
11147     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11148     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11149     case Intrinsic::ppc_altivec_vcmpgtud_p:
11150       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11151       break;
11152     }
11153   }
11154   }
11155 }
11156
11157 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11158   switch (Subtarget.getDarwinDirective()) {
11159   default: break;
11160   case PPC::DIR_970:
11161   case PPC::DIR_PWR4:
11162   case PPC::DIR_PWR5:
11163   case PPC::DIR_PWR5X:
11164   case PPC::DIR_PWR6:
11165   case PPC::DIR_PWR6X:
11166   case PPC::DIR_PWR7:
11167   case PPC::DIR_PWR8:
11168   case PPC::DIR_PWR9: {
11169     if (!ML)
11170       break;
11171
11172     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11173
11174     // For small loops (between 5 and 8 instructions), align to a 32-byte
11175     // boundary so that the entire loop fits in one instruction-cache line.
11176     uint64_t LoopSize = 0;
11177     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11178       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11179         LoopSize += TII->GetInstSizeInBytes(*J);
11180         if (LoopSize > 32)
11181           break;
11182       }
11183
11184     if (LoopSize > 16 && LoopSize <= 32)
11185       return 5;
11186
11187     break;
11188   }
11189   }
11190
11191   return TargetLowering::getPrefLoopAlignment(ML);
11192 }
11193
11194 /// getConstraintType - Given a constraint, return the type of
11195 /// constraint it is for this target.
11196 PPCTargetLowering::ConstraintType
11197 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11198   if (Constraint.size() == 1) {
11199     switch (Constraint[0]) {
11200     default: break;
11201     case 'b':
11202     case 'r':
11203     case 'f':
11204     case 'd':
11205     case 'v':
11206     case 'y':
11207       return C_RegisterClass;
11208     case 'Z':
11209       // FIXME: While Z does indicate a memory constraint, it specifically
11210       // indicates an r+r address (used in conjunction with the 'y' modifier
11211       // in the replacement string). Currently, we're forcing the base
11212       // register to be r0 in the asm printer (which is interpreted as zero)
11213       // and forming the complete address in the second register. This is
11214       // suboptimal.
11215       return C_Memory;
11216     }
11217   } else if (Constraint == "wc") { // individual CR bits.
11218     return C_RegisterClass;
11219   } else if (Constraint == "wa" || Constraint == "wd" ||
11220              Constraint == "wf" || Constraint == "ws") {
11221     return C_RegisterClass; // VSX registers.
11222   }
11223   return TargetLowering::getConstraintType(Constraint);
11224 }
11225
11226 /// Examine constraint type and operand type and determine a weight value.
11227 /// This object must already have been set up with the operand type
11228 /// and the current alternative constraint selected.
11229 TargetLowering::ConstraintWeight
11230 PPCTargetLowering::getSingleConstraintMatchWeight(
11231     AsmOperandInfo &info, const char *constraint) const {
11232   ConstraintWeight weight = CW_Invalid;
11233   Value *CallOperandVal = info.CallOperandVal;
11234     // If we don't have a value, we can't do a match,
11235     // but allow it at the lowest weight.
11236   if (!CallOperandVal)
11237     return CW_Default;
11238   Type *type = CallOperandVal->getType();
11239
11240   // Look at the constraint type.
11241   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11242     return CW_Register; // an individual CR bit.
11243   else if ((StringRef(constraint) == "wa" ||
11244             StringRef(constraint) == "wd" ||
11245             StringRef(constraint) == "wf") &&
11246            type->isVectorTy())
11247     return CW_Register;
11248   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11249     return CW_Register;
11250
11251   switch (*constraint) {
11252   default:
11253     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11254     break;
11255   case 'b':
11256     if (type->isIntegerTy())
11257       weight = CW_Register;
11258     break;
11259   case 'f':
11260     if (type->isFloatTy())
11261       weight = CW_Register;
11262     break;
11263   case 'd':
11264     if (type->isDoubleTy())
11265       weight = CW_Register;
11266     break;
11267   case 'v':
11268     if (type->isVectorTy())
11269       weight = CW_Register;
11270     break;
11271   case 'y':
11272     weight = CW_Register;
11273     break;
11274   case 'Z':
11275     weight = CW_Memory;
11276     break;
11277   }
11278   return weight;
11279 }
11280
11281 std::pair<unsigned, const TargetRegisterClass *>
11282 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11283                                                 StringRef Constraint,
11284                                                 MVT VT) const {
11285   if (Constraint.size() == 1) {
11286     // GCC RS6000 Constraint Letters
11287     switch (Constraint[0]) {
11288     case 'b':   // R1-R31
11289       if (VT == MVT::i64 && Subtarget.isPPC64())
11290         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11291       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11292     case 'r':   // R0-R31
11293       if (VT == MVT::i64 && Subtarget.isPPC64())
11294         return std::make_pair(0U, &PPC::G8RCRegClass);
11295       return std::make_pair(0U, &PPC::GPRCRegClass);
11296     // 'd' and 'f' constraints are both defined to be "the floating point
11297     // registers", where one is for 32-bit and the other for 64-bit. We don't
11298     // really care overly much here so just give them all the same reg classes.
11299     case 'd':
11300     case 'f':
11301       if (VT == MVT::f32 || VT == MVT::i32)
11302         return std::make_pair(0U, &PPC::F4RCRegClass);
11303       if (VT == MVT::f64 || VT == MVT::i64)
11304         return std::make_pair(0U, &PPC::F8RCRegClass);
11305       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11306         return std::make_pair(0U, &PPC::QFRCRegClass);
11307       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11308         return std::make_pair(0U, &PPC::QSRCRegClass);
11309       break;
11310     case 'v':
11311       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11312         return std::make_pair(0U, &PPC::QFRCRegClass);
11313       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11314         return std::make_pair(0U, &PPC::QSRCRegClass);
11315       if (Subtarget.hasAltivec())
11316         return std::make_pair(0U, &PPC::VRRCRegClass);
11317     case 'y':   // crrc
11318       return std::make_pair(0U, &PPC::CRRCRegClass);
11319     }
11320   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11321     // An individual CR bit.
11322     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11323   } else if ((Constraint == "wa" || Constraint == "wd" ||
11324              Constraint == "wf") && Subtarget.hasVSX()) {
11325     return std::make_pair(0U, &PPC::VSRCRegClass);
11326   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11327     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11328       return std::make_pair(0U, &PPC::VSSRCRegClass);
11329     else
11330       return std::make_pair(0U, &PPC::VSFRCRegClass);
11331   }
11332
11333   std::pair<unsigned, const TargetRegisterClass *> R =
11334       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11335
11336   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11337   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11338   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11339   // register.
11340   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11341   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11342   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11343       PPC::GPRCRegClass.contains(R.first))
11344     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11345                             PPC::sub_32, &PPC::G8RCRegClass),
11346                           &PPC::G8RCRegClass);
11347
11348   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11349   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11350     R.first = PPC::CR0;
11351     R.second = &PPC::CRRCRegClass;
11352   }
11353
11354   return R;
11355 }
11356
11357 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11358 /// vector.  If it is invalid, don't add anything to Ops.
11359 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11360                                                      std::string &Constraint,
11361                                                      std::vector<SDValue>&Ops,
11362                                                      SelectionDAG &DAG) const {
11363   SDValue Result;
11364
11365   // Only support length 1 constraints.
11366   if (Constraint.length() > 1) return;
11367
11368   char Letter = Constraint[0];
11369   switch (Letter) {
11370   default: break;
11371   case 'I':
11372   case 'J':
11373   case 'K':
11374   case 'L':
11375   case 'M':
11376   case 'N':
11377   case 'O':
11378   case 'P': {
11379     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11380     if (!CST) return; // Must be an immediate to match.
11381     SDLoc dl(Op);
11382     int64_t Value = CST->getSExtValue();
11383     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11384                          // numbers are printed as such.
11385     switch (Letter) {
11386     default: llvm_unreachable("Unknown constraint letter!");
11387     case 'I':  // "I" is a signed 16-bit constant.
11388       if (isInt<16>(Value))
11389         Result = DAG.getTargetConstant(Value, dl, TCVT);
11390       break;
11391     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11392       if (isShiftedUInt<16, 16>(Value))
11393         Result = DAG.getTargetConstant(Value, dl, TCVT);
11394       break;
11395     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11396       if (isShiftedInt<16, 16>(Value))
11397         Result = DAG.getTargetConstant(Value, dl, TCVT);
11398       break;
11399     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11400       if (isUInt<16>(Value))
11401         Result = DAG.getTargetConstant(Value, dl, TCVT);
11402       break;
11403     case 'M':  // "M" is a constant that is greater than 31.
11404       if (Value > 31)
11405         Result = DAG.getTargetConstant(Value, dl, TCVT);
11406       break;
11407     case 'N':  // "N" is a positive constant that is an exact power of two.
11408       if (Value > 0 && isPowerOf2_64(Value))
11409         Result = DAG.getTargetConstant(Value, dl, TCVT);
11410       break;
11411     case 'O':  // "O" is the constant zero.
11412       if (Value == 0)
11413         Result = DAG.getTargetConstant(Value, dl, TCVT);
11414       break;
11415     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11416       if (isInt<16>(-Value))
11417         Result = DAG.getTargetConstant(Value, dl, TCVT);
11418       break;
11419     }
11420     break;
11421   }
11422   }
11423
11424   if (Result.getNode()) {
11425     Ops.push_back(Result);
11426     return;
11427   }
11428
11429   // Handle standard constraint letters.
11430   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11431 }
11432
11433 // isLegalAddressingMode - Return true if the addressing mode represented
11434 // by AM is legal for this target, for a load/store of the specified type.
11435 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11436                                               const AddrMode &AM, Type *Ty,
11437                                               unsigned AS) const {
11438   // PPC does not allow r+i addressing modes for vectors!
11439   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11440     return false;
11441
11442   // PPC allows a sign-extended 16-bit immediate field.
11443   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11444     return false;
11445
11446   // No global is ever allowed as a base.
11447   if (AM.BaseGV)
11448     return false;
11449
11450   // PPC only support r+r,
11451   switch (AM.Scale) {
11452   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11453     break;
11454   case 1:
11455     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11456       return false;
11457     // Otherwise we have r+r or r+i.
11458     break;
11459   case 2:
11460     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11461       return false;
11462     // Allow 2*r as r+r.
11463     break;
11464   default:
11465     // No other scales are supported.
11466     return false;
11467   }
11468
11469   return true;
11470 }
11471
11472 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11473                                            SelectionDAG &DAG) const {
11474   MachineFunction &MF = DAG.getMachineFunction();
11475   MachineFrameInfo *MFI = MF.getFrameInfo();
11476   MFI->setReturnAddressIsTaken(true);
11477
11478   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11479     return SDValue();
11480
11481   SDLoc dl(Op);
11482   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11483
11484   // Make sure the function does not optimize away the store of the RA to
11485   // the stack.
11486   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11487   FuncInfo->setLRStoreRequired();
11488   bool isPPC64 = Subtarget.isPPC64();
11489   auto PtrVT = getPointerTy(MF.getDataLayout());
11490
11491   if (Depth > 0) {
11492     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11493     SDValue Offset =
11494         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11495                         isPPC64 ? MVT::i64 : MVT::i32);
11496     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11497                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11498                        MachinePointerInfo(), false, false, false, 0);
11499   }
11500
11501   // Just load the return address off the stack.
11502   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11503   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11504                      MachinePointerInfo(), false, false, false, 0);
11505 }
11506
11507 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11508                                           SelectionDAG &DAG) const {
11509   SDLoc dl(Op);
11510   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11511
11512   MachineFunction &MF = DAG.getMachineFunction();
11513   MachineFrameInfo *MFI = MF.getFrameInfo();
11514   MFI->setFrameAddressIsTaken(true);
11515
11516   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11517   bool isPPC64 = PtrVT == MVT::i64;
11518
11519   // Naked functions never have a frame pointer, and so we use r1. For all
11520   // other functions, this decision must be delayed until during PEI.
11521   unsigned FrameReg;
11522   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11523     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11524   else
11525     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11526
11527   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11528                                          PtrVT);
11529   while (Depth--)
11530     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11531                             FrameAddr, MachinePointerInfo(), false, false,
11532                             false, 0);
11533   return FrameAddr;
11534 }
11535
11536 // FIXME? Maybe this could be a TableGen attribute on some registers and
11537 // this table could be generated automatically from RegInfo.
11538 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11539                                               SelectionDAG &DAG) const {
11540   bool isPPC64 = Subtarget.isPPC64();
11541   bool isDarwinABI = Subtarget.isDarwinABI();
11542
11543   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11544       (!isPPC64 && VT != MVT::i32))
11545     report_fatal_error("Invalid register global variable type");
11546
11547   bool is64Bit = isPPC64 && VT == MVT::i64;
11548   unsigned Reg = StringSwitch<unsigned>(RegName)
11549                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11550                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11551                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11552                                   (is64Bit ? PPC::X13 : PPC::R13))
11553                    .Default(0);
11554
11555   if (Reg)
11556     return Reg;
11557   report_fatal_error("Invalid register name global variable");
11558 }
11559
11560 bool
11561 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11562   // The PowerPC target isn't yet aware of offsets.
11563   return false;
11564 }
11565
11566 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11567                                            const CallInst &I,
11568                                            unsigned Intrinsic) const {
11569
11570   switch (Intrinsic) {
11571   case Intrinsic::ppc_qpx_qvlfd:
11572   case Intrinsic::ppc_qpx_qvlfs:
11573   case Intrinsic::ppc_qpx_qvlfcd:
11574   case Intrinsic::ppc_qpx_qvlfcs:
11575   case Intrinsic::ppc_qpx_qvlfiwa:
11576   case Intrinsic::ppc_qpx_qvlfiwz:
11577   case Intrinsic::ppc_altivec_lvx:
11578   case Intrinsic::ppc_altivec_lvxl:
11579   case Intrinsic::ppc_altivec_lvebx:
11580   case Intrinsic::ppc_altivec_lvehx:
11581   case Intrinsic::ppc_altivec_lvewx:
11582   case Intrinsic::ppc_vsx_lxvd2x:
11583   case Intrinsic::ppc_vsx_lxvw4x: {
11584     EVT VT;
11585     switch (Intrinsic) {
11586     case Intrinsic::ppc_altivec_lvebx:
11587       VT = MVT::i8;
11588       break;
11589     case Intrinsic::ppc_altivec_lvehx:
11590       VT = MVT::i16;
11591       break;
11592     case Intrinsic::ppc_altivec_lvewx:
11593       VT = MVT::i32;
11594       break;
11595     case Intrinsic::ppc_vsx_lxvd2x:
11596       VT = MVT::v2f64;
11597       break;
11598     case Intrinsic::ppc_qpx_qvlfd:
11599       VT = MVT::v4f64;
11600       break;
11601     case Intrinsic::ppc_qpx_qvlfs:
11602       VT = MVT::v4f32;
11603       break;
11604     case Intrinsic::ppc_qpx_qvlfcd:
11605       VT = MVT::v2f64;
11606       break;
11607     case Intrinsic::ppc_qpx_qvlfcs:
11608       VT = MVT::v2f32;
11609       break;
11610     default:
11611       VT = MVT::v4i32;
11612       break;
11613     }
11614
11615     Info.opc = ISD::INTRINSIC_W_CHAIN;
11616     Info.memVT = VT;
11617     Info.ptrVal = I.getArgOperand(0);
11618     Info.offset = -VT.getStoreSize()+1;
11619     Info.size = 2*VT.getStoreSize()-1;
11620     Info.align = 1;
11621     Info.vol = false;
11622     Info.readMem = true;
11623     Info.writeMem = false;
11624     return true;
11625   }
11626   case Intrinsic::ppc_qpx_qvlfda:
11627   case Intrinsic::ppc_qpx_qvlfsa:
11628   case Intrinsic::ppc_qpx_qvlfcda:
11629   case Intrinsic::ppc_qpx_qvlfcsa:
11630   case Intrinsic::ppc_qpx_qvlfiwaa:
11631   case Intrinsic::ppc_qpx_qvlfiwza: {
11632     EVT VT;
11633     switch (Intrinsic) {
11634     case Intrinsic::ppc_qpx_qvlfda:
11635       VT = MVT::v4f64;
11636       break;
11637     case Intrinsic::ppc_qpx_qvlfsa:
11638       VT = MVT::v4f32;
11639       break;
11640     case Intrinsic::ppc_qpx_qvlfcda:
11641       VT = MVT::v2f64;
11642       break;
11643     case Intrinsic::ppc_qpx_qvlfcsa:
11644       VT = MVT::v2f32;
11645       break;
11646     default:
11647       VT = MVT::v4i32;
11648       break;
11649     }
11650
11651     Info.opc = ISD::INTRINSIC_W_CHAIN;
11652     Info.memVT = VT;
11653     Info.ptrVal = I.getArgOperand(0);
11654     Info.offset = 0;
11655     Info.size = VT.getStoreSize();
11656     Info.align = 1;
11657     Info.vol = false;
11658     Info.readMem = true;
11659     Info.writeMem = false;
11660     return true;
11661   }
11662   case Intrinsic::ppc_qpx_qvstfd:
11663   case Intrinsic::ppc_qpx_qvstfs:
11664   case Intrinsic::ppc_qpx_qvstfcd:
11665   case Intrinsic::ppc_qpx_qvstfcs:
11666   case Intrinsic::ppc_qpx_qvstfiw:
11667   case Intrinsic::ppc_altivec_stvx:
11668   case Intrinsic::ppc_altivec_stvxl:
11669   case Intrinsic::ppc_altivec_stvebx:
11670   case Intrinsic::ppc_altivec_stvehx:
11671   case Intrinsic::ppc_altivec_stvewx:
11672   case Intrinsic::ppc_vsx_stxvd2x:
11673   case Intrinsic::ppc_vsx_stxvw4x: {
11674     EVT VT;
11675     switch (Intrinsic) {
11676     case Intrinsic::ppc_altivec_stvebx:
11677       VT = MVT::i8;
11678       break;
11679     case Intrinsic::ppc_altivec_stvehx:
11680       VT = MVT::i16;
11681       break;
11682     case Intrinsic::ppc_altivec_stvewx:
11683       VT = MVT::i32;
11684       break;
11685     case Intrinsic::ppc_vsx_stxvd2x:
11686       VT = MVT::v2f64;
11687       break;
11688     case Intrinsic::ppc_qpx_qvstfd:
11689       VT = MVT::v4f64;
11690       break;
11691     case Intrinsic::ppc_qpx_qvstfs:
11692       VT = MVT::v4f32;
11693       break;
11694     case Intrinsic::ppc_qpx_qvstfcd:
11695       VT = MVT::v2f64;
11696       break;
11697     case Intrinsic::ppc_qpx_qvstfcs:
11698       VT = MVT::v2f32;
11699       break;
11700     default:
11701       VT = MVT::v4i32;
11702       break;
11703     }
11704
11705     Info.opc = ISD::INTRINSIC_VOID;
11706     Info.memVT = VT;
11707     Info.ptrVal = I.getArgOperand(1);
11708     Info.offset = -VT.getStoreSize()+1;
11709     Info.size = 2*VT.getStoreSize()-1;
11710     Info.align = 1;
11711     Info.vol = false;
11712     Info.readMem = false;
11713     Info.writeMem = true;
11714     return true;
11715   }
11716   case Intrinsic::ppc_qpx_qvstfda:
11717   case Intrinsic::ppc_qpx_qvstfsa:
11718   case Intrinsic::ppc_qpx_qvstfcda:
11719   case Intrinsic::ppc_qpx_qvstfcsa:
11720   case Intrinsic::ppc_qpx_qvstfiwa: {
11721     EVT VT;
11722     switch (Intrinsic) {
11723     case Intrinsic::ppc_qpx_qvstfda:
11724       VT = MVT::v4f64;
11725       break;
11726     case Intrinsic::ppc_qpx_qvstfsa:
11727       VT = MVT::v4f32;
11728       break;
11729     case Intrinsic::ppc_qpx_qvstfcda:
11730       VT = MVT::v2f64;
11731       break;
11732     case Intrinsic::ppc_qpx_qvstfcsa:
11733       VT = MVT::v2f32;
11734       break;
11735     default:
11736       VT = MVT::v4i32;
11737       break;
11738     }
11739
11740     Info.opc = ISD::INTRINSIC_VOID;
11741     Info.memVT = VT;
11742     Info.ptrVal = I.getArgOperand(1);
11743     Info.offset = 0;
11744     Info.size = VT.getStoreSize();
11745     Info.align = 1;
11746     Info.vol = false;
11747     Info.readMem = false;
11748     Info.writeMem = true;
11749     return true;
11750   }
11751   default:
11752     break;
11753   }
11754
11755   return false;
11756 }
11757
11758 /// getOptimalMemOpType - Returns the target specific optimal type for load
11759 /// and store operations as a result of memset, memcpy, and memmove
11760 /// lowering. If DstAlign is zero that means it's safe to destination
11761 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11762 /// means there isn't a need to check it against alignment requirement,
11763 /// probably because the source does not need to be loaded. If 'IsMemset' is
11764 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11765 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11766 /// source is constant so it does not need to be loaded.
11767 /// It returns EVT::Other if the type should be determined using generic
11768 /// target-independent logic.
11769 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11770                                            unsigned DstAlign, unsigned SrcAlign,
11771                                            bool IsMemset, bool ZeroMemset,
11772                                            bool MemcpyStrSrc,
11773                                            MachineFunction &MF) const {
11774   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11775     const Function *F = MF.getFunction();
11776     // When expanding a memset, require at least two QPX instructions to cover
11777     // the cost of loading the value to be stored from the constant pool.
11778     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11779        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11780         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11781       return MVT::v4f64;
11782     }
11783
11784     // We should use Altivec/VSX loads and stores when available. For unaligned
11785     // addresses, unaligned VSX loads are only fast starting with the P8.
11786     if (Subtarget.hasAltivec() && Size >= 16 &&
11787         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11788          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11789       return MVT::v4i32;
11790   }
11791
11792   if (Subtarget.isPPC64()) {
11793     return MVT::i64;
11794   }
11795
11796   return MVT::i32;
11797 }
11798
11799 /// \brief Returns true if it is beneficial to convert a load of a constant
11800 /// to just the constant itself.
11801 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11802                                                           Type *Ty) const {
11803   assert(Ty->isIntegerTy());
11804
11805   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11806   return !(BitSize == 0 || BitSize > 64);
11807 }
11808
11809 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11810   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11811     return false;
11812   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11813   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11814   return NumBits1 == 64 && NumBits2 == 32;
11815 }
11816
11817 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11818   if (!VT1.isInteger() || !VT2.isInteger())
11819     return false;
11820   unsigned NumBits1 = VT1.getSizeInBits();
11821   unsigned NumBits2 = VT2.getSizeInBits();
11822   return NumBits1 == 64 && NumBits2 == 32;
11823 }
11824
11825 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11826   // Generally speaking, zexts are not free, but they are free when they can be
11827   // folded with other operations.
11828   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11829     EVT MemVT = LD->getMemoryVT();
11830     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11831          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11832         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11833          LD->getExtensionType() == ISD::ZEXTLOAD))
11834       return true;
11835   }
11836
11837   // FIXME: Add other cases...
11838   //  - 32-bit shifts with a zext to i64
11839   //  - zext after ctlz, bswap, etc.
11840   //  - zext after and by a constant mask
11841
11842   return TargetLowering::isZExtFree(Val, VT2);
11843 }
11844
11845 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11846   assert(VT.isFloatingPoint());
11847   return true;
11848 }
11849
11850 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11851   return isInt<16>(Imm) || isUInt<16>(Imm);
11852 }
11853
11854 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11855   return isInt<16>(Imm) || isUInt<16>(Imm);
11856 }
11857
11858 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11859                                                        unsigned,
11860                                                        unsigned,
11861                                                        bool *Fast) const {
11862   if (DisablePPCUnaligned)
11863     return false;
11864
11865   // PowerPC supports unaligned memory access for simple non-vector types.
11866   // Although accessing unaligned addresses is not as efficient as accessing
11867   // aligned addresses, it is generally more efficient than manual expansion,
11868   // and generally only traps for software emulation when crossing page
11869   // boundaries.
11870
11871   if (!VT.isSimple())
11872     return false;
11873
11874   if (VT.getSimpleVT().isVector()) {
11875     if (Subtarget.hasVSX()) {
11876       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11877           VT != MVT::v4f32 && VT != MVT::v4i32)
11878         return false;
11879     } else {
11880       return false;
11881     }
11882   }
11883
11884   if (VT == MVT::ppcf128)
11885     return false;
11886
11887   if (Fast)
11888     *Fast = true;
11889
11890   return true;
11891 }
11892
11893 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11894   VT = VT.getScalarType();
11895
11896   if (!VT.isSimple())
11897     return false;
11898
11899   switch (VT.getSimpleVT().SimpleTy) {
11900   case MVT::f32:
11901   case MVT::f64:
11902     return true;
11903   default:
11904     break;
11905   }
11906
11907   return false;
11908 }
11909
11910 const MCPhysReg *
11911 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11912   // LR is a callee-save register, but we must treat it as clobbered by any call
11913   // site. Hence we include LR in the scratch registers, which are in turn added
11914   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11915   // to CTR, which is used by any indirect call.
11916   static const MCPhysReg ScratchRegs[] = {
11917     PPC::X12, PPC::LR8, PPC::CTR8, 0
11918   };
11919
11920   return ScratchRegs;
11921 }
11922
11923 unsigned PPCTargetLowering::getExceptionPointerRegister(
11924     const Constant *PersonalityFn) const {
11925   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
11926 }
11927
11928 unsigned PPCTargetLowering::getExceptionSelectorRegister(
11929     const Constant *PersonalityFn) const {
11930   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
11931 }
11932
11933 bool
11934 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11935                      EVT VT , unsigned DefinedValues) const {
11936   if (VT == MVT::v2i64)
11937     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
11938
11939   if (Subtarget.hasVSX() || Subtarget.hasQPX())
11940     return true;
11941
11942   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11943 }
11944
11945 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11946   if (DisableILPPref || Subtarget.enableMachineScheduler())
11947     return TargetLowering::getSchedulingPreference(N);
11948
11949   return Sched::ILP;
11950 }
11951
11952 // Create a fast isel object.
11953 FastISel *
11954 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11955                                   const TargetLibraryInfo *LibInfo) const {
11956   return PPC::createFastISel(FuncInfo, LibInfo);
11957 }
11958
11959 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11960   if (Subtarget.isDarwinABI()) return;
11961   if (!Subtarget.isPPC64()) return;
11962
11963   // Update IsSplitCSR in PPCFunctionInfo
11964   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
11965   PFI->setIsSplitCSR(true);
11966 }
11967
11968 void PPCTargetLowering::insertCopiesSplitCSR(
11969   MachineBasicBlock *Entry,
11970   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11971   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11972   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11973   if (!IStart)
11974     return;
11975
11976   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11977   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
11978   MachineBasicBlock::iterator MBBI = Entry->begin();
11979   for (const MCPhysReg *I = IStart; *I; ++I) {
11980     const TargetRegisterClass *RC = nullptr;
11981     if (PPC::G8RCRegClass.contains(*I))
11982       RC = &PPC::G8RCRegClass;
11983     else if (PPC::F8RCRegClass.contains(*I))
11984       RC = &PPC::F8RCRegClass;
11985     else if (PPC::CRRCRegClass.contains(*I))
11986       RC = &PPC::CRRCRegClass;
11987     else if (PPC::VRRCRegClass.contains(*I))
11988       RC = &PPC::VRRCRegClass;
11989     else
11990       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11991
11992     unsigned NewVR = MRI->createVirtualRegister(RC);
11993     // Create copy from CSR to a virtual register.
11994     // FIXME: this currently does not emit CFI pseudo-instructions, it works
11995     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11996     // nounwind. If we want to generalize this later, we may need to emit
11997     // CFI pseudo-instructions.
11998     assert(Entry->getParent()->getFunction()->hasFnAttribute(
11999              Attribute::NoUnwind) &&
12000            "Function should be nounwind in insertCopiesSplitCSR!");
12001     Entry->addLiveIn(*I);
12002     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12003       .addReg(*I);
12004
12005     // Insert the copy-back instructions right before the terminator
12006     for (auto *Exit : Exits)
12007       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12008               TII->get(TargetOpcode::COPY), *I)
12009         .addReg(NewVR);
12010   }
12011 }
12012
12013 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12014 bool PPCTargetLowering::useLoadStackGuardNode() const {
12015   if (!Subtarget.isTargetLinux())
12016     return TargetLowering::useLoadStackGuardNode();
12017   return true;
12018 }
12019
12020 // Override to disable global variable loading on Linux.
12021 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12022   if (!Subtarget.isTargetLinux())
12023     return TargetLowering::insertSSPDeclarations(M);
12024 }