1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCCCState.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCPerfectShuffle.h"
20 #include "PPCTargetMachine.h"
21 #include "PPCTargetObjectFile.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include <list>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "ppc-lowering"
50 
51 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
52 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
53 
54 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
55 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
56 
57 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
58 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
59 
60 static cl::opt<bool> DisableSCO("disable-ppc-sco",
61 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
62 
63 STATISTIC(NumTailCalls, "Number of tail calls");
64 STATISTIC(NumSiblingCalls, "Number of sibling calls");
65 
66 // FIXME: Remove this once the bug has been fixed!
67 extern cl::opt<bool> ANDIGlueBug;
68 
69 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
70                                      const PPCSubtarget &STI)
71     : TargetLowering(TM), Subtarget(STI) {
72   // Use _setjmp/_longjmp instead of setjmp/longjmp.
73   setUseUnderscoreSetJmp(true);
74   setUseUnderscoreLongJmp(true);
75 
76   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77   // arguments are at least 4/8 bytes aligned.
78   bool isPPC64 = Subtarget.isPPC64();
79   setMinStackArgumentAlignment(isPPC64 ? 8:4);
80 
81   // Set up the register classes.
82   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
83   if (!useSoftFloat()) {
84     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
85     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
86   }
87 
88   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
89   for (MVT VT : MVT::integer_valuetypes()) {
90     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
91     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
92   }
93 
94   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
95 
96   // PowerPC has pre-inc load and store's.
97   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
98   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
99   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
100   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
101   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
102   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
103   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
104   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
105   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
106   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
107   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
108   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
110   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
111 
112   if (Subtarget.useCRBits()) {
113     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
114 
115     if (isPPC64 || Subtarget.hasFPCVT()) {
116       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
117       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
118                          isPPC64 ? MVT::i64 : MVT::i32);
119       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
120       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
121                         isPPC64 ? MVT::i64 : MVT::i32);
122     } else {
123       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
124       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
125     }
126 
127     // PowerPC does not support direct load / store of condition registers
128     setOperationAction(ISD::LOAD, MVT::i1, Custom);
129     setOperationAction(ISD::STORE, MVT::i1, Custom);
130 
131     // FIXME: Remove this once the ANDI glue bug is fixed:
132     if (ANDIGlueBug)
133       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
134 
135     for (MVT VT : MVT::integer_valuetypes()) {
136       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
137       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
138       setTruncStoreAction(VT, MVT::i1, Expand);
139     }
140 
141     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
142   }
143 
144   // This is used in the ppcf128->int sequence.  Note it has different semantics
145   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
146   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
147 
148   // We do not currently implement these libm ops for PowerPC.
149   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
150   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
151   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
152   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
153   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
154   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
155 
156   // PowerPC has no SREM/UREM instructions
157   setOperationAction(ISD::SREM, MVT::i32, Expand);
158   setOperationAction(ISD::UREM, MVT::i32, Expand);
159   setOperationAction(ISD::SREM, MVT::i64, Expand);
160   setOperationAction(ISD::UREM, MVT::i64, Expand);
161 
162   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
163   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
164   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
165   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
166   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
167   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
168   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
169   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
170   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
171 
172   // We don't support sin/cos/sqrt/fmod/pow
173   setOperationAction(ISD::FSIN , MVT::f64, Expand);
174   setOperationAction(ISD::FCOS , MVT::f64, Expand);
175   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
176   setOperationAction(ISD::FREM , MVT::f64, Expand);
177   setOperationAction(ISD::FPOW , MVT::f64, Expand);
178   setOperationAction(ISD::FMA  , MVT::f64, Legal);
179   setOperationAction(ISD::FSIN , MVT::f32, Expand);
180   setOperationAction(ISD::FCOS , MVT::f32, Expand);
181   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
182   setOperationAction(ISD::FREM , MVT::f32, Expand);
183   setOperationAction(ISD::FPOW , MVT::f32, Expand);
184   setOperationAction(ISD::FMA  , MVT::f32, Legal);
185 
186   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
187 
188   // If we're enabling GP optimizations, use hardware square root
189   if (!Subtarget.hasFSQRT() &&
190       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
191         Subtarget.hasFRE()))
192     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
193 
194   if (!Subtarget.hasFSQRT() &&
195       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
196         Subtarget.hasFRES()))
197     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
198 
199   if (Subtarget.hasFCPSGN()) {
200     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
201     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
202   } else {
203     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
204     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
205   }
206 
207   if (Subtarget.hasFPRND()) {
208     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
209     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
210     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
211     setOperationAction(ISD::FROUND, MVT::f64, Legal);
212 
213     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
214     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
215     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
216     setOperationAction(ISD::FROUND, MVT::f32, Legal);
217   }
218 
219   // PowerPC does not have BSWAP, CTPOP or CTTZ
220   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
221   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
222   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
223   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
224 
225   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
226     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
227     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
228   } else {
229     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
230     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
231   }
232 
233   // PowerPC does not have ROTR
234   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
235   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
236 
237   if (!Subtarget.useCRBits()) {
238     // PowerPC does not have Select
239     setOperationAction(ISD::SELECT, MVT::i32, Expand);
240     setOperationAction(ISD::SELECT, MVT::i64, Expand);
241     setOperationAction(ISD::SELECT, MVT::f32, Expand);
242     setOperationAction(ISD::SELECT, MVT::f64, Expand);
243   }
244 
245   // PowerPC wants to turn select_cc of FP into fsel when possible.
246   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
247   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
248 
249   // PowerPC wants to optimize integer setcc a bit
250   if (!Subtarget.useCRBits())
251     setOperationAction(ISD::SETCC, MVT::i32, Custom);
252 
253   // PowerPC does not have BRCOND which requires SetCC
254   if (!Subtarget.useCRBits())
255     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
256 
257   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
258 
259   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
260   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261 
262   // PowerPC does not have [U|S]INT_TO_FP
263   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
264   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
265 
266   if (Subtarget.hasDirectMove() && isPPC64) {
267     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
268     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
269     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
270     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
271   } else {
272     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
273     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
274     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
275     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
276   }
277 
278   // We cannot sextinreg(i1).  Expand to shifts.
279   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
280 
281   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
282   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
283   // support continuation, user-level threading, and etc.. As a result, no
284   // other SjLj exception interfaces are implemented and please don't build
285   // your own exception handling based on them.
286   // LLVM/Clang supports zero-cost DWARF exception handling.
287   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
288   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
289 
290   // We want to legalize GlobalAddress and ConstantPool nodes into the
291   // appropriate instructions to materialize the address.
292   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
293   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
294   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
295   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
296   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
297   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
298   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
299   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
300   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
301   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
302 
303   // TRAP is legal.
304   setOperationAction(ISD::TRAP, MVT::Other, Legal);
305 
306   // TRAMPOLINE is custom lowered.
307   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
308   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
309 
310   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
312 
313   if (Subtarget.isSVR4ABI()) {
314     if (isPPC64) {
315       // VAARG always uses double-word chunks, so promote anything smaller.
316       setOperationAction(ISD::VAARG, MVT::i1, Promote);
317       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
318       setOperationAction(ISD::VAARG, MVT::i8, Promote);
319       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
320       setOperationAction(ISD::VAARG, MVT::i16, Promote);
321       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
322       setOperationAction(ISD::VAARG, MVT::i32, Promote);
323       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
324       setOperationAction(ISD::VAARG, MVT::Other, Expand);
325     } else {
326       // VAARG is custom lowered with the 32-bit SVR4 ABI.
327       setOperationAction(ISD::VAARG, MVT::Other, Custom);
328       setOperationAction(ISD::VAARG, MVT::i64, Custom);
329     }
330   } else
331     setOperationAction(ISD::VAARG, MVT::Other, Expand);
332 
333   if (Subtarget.isSVR4ABI() && !isPPC64)
334     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
335     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
336   else
337     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
338 
339   // Use the default implementation.
340   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
341   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
342   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
343   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
344   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
345   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
346   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
347 
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     if (Subtarget.hasP9Vector()) {
669       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
670       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Legal);
671     }
672   }
673 
674   if (Subtarget.hasQPX()) {
675     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
676     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
677     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
678     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
679 
680     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
681     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
682 
683     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
684     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
685 
686     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
687     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
688 
689     if (!Subtarget.useCRBits())
690       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
691     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
692 
693     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
694     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
695     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
696     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
697     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
698     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
699     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
700 
701     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
702     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
703 
704     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
705     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
706     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
707 
708     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
709     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
710     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
711     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
712     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
713     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
714     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
715     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
716     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
717     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
718     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
719 
720     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
721     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
722 
723     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
724     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
725 
726     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
727 
728     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
729     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
730     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
731     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
732 
733     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
734     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
735 
736     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
737     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
738 
739     if (!Subtarget.useCRBits())
740       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
741     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
742 
743     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
744     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
745     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
746     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
747     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
748     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
749     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
750 
751     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
752     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
753 
754     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
755     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
756     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
757     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
758     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
759     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
760     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
761     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
762     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
763     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
764     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
768 
769     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
770     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
771 
772     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
773 
774     setOperationAction(ISD::AND , MVT::v4i1, Legal);
775     setOperationAction(ISD::OR , MVT::v4i1, Legal);
776     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
777 
778     if (!Subtarget.useCRBits())
779       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
780     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
781 
782     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
783     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
784 
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
786     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
787     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
788     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
789     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
790     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
791     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
792 
793     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
794     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
795 
796     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
797 
798     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
799     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
800     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
801     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
802 
803     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
804     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
805     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
806     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
807 
808     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
809     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
810 
811     // These need to set FE_INEXACT, and so cannot be vectorized here.
812     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
813     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
814 
815     if (TM.Options.UnsafeFPMath) {
816       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
817       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
818 
819       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
820       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
821     } else {
822       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
823       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
824 
825       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
826       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
827     }
828   }
829 
830   if (Subtarget.has64BitSupport())
831     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
832 
833   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
834 
835   if (!isPPC64) {
836     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
837     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
838   }
839 
840   setBooleanContents(ZeroOrOneBooleanContent);
841 
842   if (Subtarget.hasAltivec()) {
843     // Altivec instructions set fields to all zeros or all ones.
844     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
845   }
846 
847   if (!isPPC64) {
848     // These libcalls are not available in 32-bit.
849     setLibcallName(RTLIB::SHL_I128, nullptr);
850     setLibcallName(RTLIB::SRL_I128, nullptr);
851     setLibcallName(RTLIB::SRA_I128, nullptr);
852   }
853 
854   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
855 
856   // We have target-specific dag combine patterns for the following nodes:
857   setTargetDAGCombine(ISD::SINT_TO_FP);
858   setTargetDAGCombine(ISD::BUILD_VECTOR);
859   if (Subtarget.hasFPCVT())
860     setTargetDAGCombine(ISD::UINT_TO_FP);
861   setTargetDAGCombine(ISD::LOAD);
862   setTargetDAGCombine(ISD::STORE);
863   setTargetDAGCombine(ISD::BR_CC);
864   if (Subtarget.useCRBits())
865     setTargetDAGCombine(ISD::BRCOND);
866   setTargetDAGCombine(ISD::BSWAP);
867   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
868   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
869   setTargetDAGCombine(ISD::INTRINSIC_VOID);
870 
871   setTargetDAGCombine(ISD::SIGN_EXTEND);
872   setTargetDAGCombine(ISD::ZERO_EXTEND);
873   setTargetDAGCombine(ISD::ANY_EXTEND);
874 
875   if (Subtarget.useCRBits()) {
876     setTargetDAGCombine(ISD::TRUNCATE);
877     setTargetDAGCombine(ISD::SETCC);
878     setTargetDAGCombine(ISD::SELECT_CC);
879   }
880 
881   // Use reciprocal estimates.
882   if (TM.Options.UnsafeFPMath) {
883     setTargetDAGCombine(ISD::FDIV);
884     setTargetDAGCombine(ISD::FSQRT);
885   }
886 
887   // Darwin long double math library functions have $LDBL128 appended.
888   if (Subtarget.isDarwin()) {
889     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
890     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
891     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
892     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
893     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
894     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
895     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
896     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
897     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
898     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
899   }
900 
901   // With 32 condition bits, we don't need to sink (and duplicate) compares
902   // aggressively in CodeGenPrep.
903   if (Subtarget.useCRBits()) {
904     setHasMultipleConditionRegisters();
905     setJumpIsExpensive();
906   }
907 
908   setMinFunctionAlignment(2);
909   if (Subtarget.isDarwin())
910     setPrefFunctionAlignment(4);
911 
912   switch (Subtarget.getDarwinDirective()) {
913   default: break;
914   case PPC::DIR_970:
915   case PPC::DIR_A2:
916   case PPC::DIR_E500mc:
917   case PPC::DIR_E5500:
918   case PPC::DIR_PWR4:
919   case PPC::DIR_PWR5:
920   case PPC::DIR_PWR5X:
921   case PPC::DIR_PWR6:
922   case PPC::DIR_PWR6X:
923   case PPC::DIR_PWR7:
924   case PPC::DIR_PWR8:
925   case PPC::DIR_PWR9:
926     setPrefFunctionAlignment(4);
927     setPrefLoopAlignment(4);
928     break;
929   }
930 
931   if (Subtarget.enableMachineScheduler())
932     setSchedulingPreference(Sched::Source);
933   else
934     setSchedulingPreference(Sched::Hybrid);
935 
936   computeRegisterProperties(STI.getRegisterInfo());
937 
938   // The Freescale cores do better with aggressive inlining of memcpy and
939   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
940   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
941       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
942     MaxStoresPerMemset = 32;
943     MaxStoresPerMemsetOptSize = 16;
944     MaxStoresPerMemcpy = 32;
945     MaxStoresPerMemcpyOptSize = 8;
946     MaxStoresPerMemmove = 32;
947     MaxStoresPerMemmoveOptSize = 8;
948   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
949     // The A2 also benefits from (very) aggressive inlining of memcpy and
950     // friends. The overhead of a the function call, even when warm, can be
951     // over one hundred cycles.
952     MaxStoresPerMemset = 128;
953     MaxStoresPerMemcpy = 128;
954     MaxStoresPerMemmove = 128;
955   }
956 }
957 
958 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
959 /// the desired ByVal argument alignment.
960 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
961                              unsigned MaxMaxAlign) {
962   if (MaxAlign == MaxMaxAlign)
963     return;
964   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
965     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
966       MaxAlign = 32;
967     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
968       MaxAlign = 16;
969   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
970     unsigned EltAlign = 0;
971     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
972     if (EltAlign > MaxAlign)
973       MaxAlign = EltAlign;
974   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
975     for (auto *EltTy : STy->elements()) {
976       unsigned EltAlign = 0;
977       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
978       if (EltAlign > MaxAlign)
979         MaxAlign = EltAlign;
980       if (MaxAlign == MaxMaxAlign)
981         break;
982     }
983   }
984 }
985 
986 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
987 /// function arguments in the caller parameter area.
988 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
989                                                   const DataLayout &DL) const {
990   // Darwin passes everything on 4 byte boundary.
991   if (Subtarget.isDarwin())
992     return 4;
993 
994   // 16byte and wider vectors are passed on 16byte boundary.
995   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
996   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
997   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
998     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
999   return Align;
1000 }
1001 
1002 bool PPCTargetLowering::useSoftFloat() const {
1003   return Subtarget.useSoftFloat();
1004 }
1005 
1006 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007   switch ((PPCISD::NodeType)Opcode) {
1008   case PPCISD::FIRST_NUMBER:    break;
1009   case PPCISD::FSEL:            return "PPCISD::FSEL";
1010   case PPCISD::FCFID:           return "PPCISD::FCFID";
1011   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1012   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1013   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1014   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1015   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1016   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1017   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1018   case PPCISD::FRE:             return "PPCISD::FRE";
1019   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1020   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1021   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1022   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1023   case PPCISD::VPERM:           return "PPCISD::VPERM";
1024   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1025   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1026   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1027   case PPCISD::CMPB:            return "PPCISD::CMPB";
1028   case PPCISD::Hi:              return "PPCISD::Hi";
1029   case PPCISD::Lo:              return "PPCISD::Lo";
1030   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1031   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1032   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1033   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1034   case PPCISD::SRL:             return "PPCISD::SRL";
1035   case PPCISD::SRA:             return "PPCISD::SRA";
1036   case PPCISD::SHL:             return "PPCISD::SHL";
1037   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1038   case PPCISD::CALL:            return "PPCISD::CALL";
1039   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1040   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1041   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1042   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1043   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1044   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1045   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1046   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1047   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1048   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1049   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1050   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1051   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1052   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1053   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1054   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1055   case PPCISD::VCMP:            return "PPCISD::VCMP";
1056   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1057   case PPCISD::LBRX:            return "PPCISD::LBRX";
1058   case PPCISD::STBRX:           return "PPCISD::STBRX";
1059   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1060   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1061   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1062   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1063   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1064   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1065   case PPCISD::BDZ:             return "PPCISD::BDZ";
1066   case PPCISD::MFFS:            return "PPCISD::MFFS";
1067   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1068   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1069   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1070   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1071   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1072   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1073   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1074   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1075   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1076   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1077   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1078   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1079   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1080   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1081   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1082   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1083   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1084   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1085   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1086   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1087   case PPCISD::SC:              return "PPCISD::SC";
1088   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1089   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1090   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1091   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1092   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1093   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1094   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1095   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1096   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1097   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1098   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1099   }
1100   return nullptr;
1101 }
1102 
1103 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1104                                           EVT VT) const {
1105   if (!VT.isVector())
1106     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1107 
1108   if (Subtarget.hasQPX())
1109     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1110 
1111   return VT.changeVectorElementTypeToInteger();
1112 }
1113 
1114 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1115   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1116   return true;
1117 }
1118 
1119 //===----------------------------------------------------------------------===//
1120 // Node matching predicates, for use by the tblgen matching code.
1121 //===----------------------------------------------------------------------===//
1122 
1123 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1124 static bool isFloatingPointZero(SDValue Op) {
1125   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1126     return CFP->getValueAPF().isZero();
1127   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1128     // Maybe this has already been legalized into the constant pool?
1129     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1130       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1131         return CFP->getValueAPF().isZero();
1132   }
1133   return false;
1134 }
1135 
1136 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1137 /// true if Op is undef or if it matches the specified value.
1138 static bool isConstantOrUndef(int Op, int Val) {
1139   return Op < 0 || Op == Val;
1140 }
1141 
1142 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1143 /// VPKUHUM instruction.
1144 /// The ShuffleKind distinguishes between big-endian operations with
1145 /// two different inputs (0), either-endian operations with two identical
1146 /// inputs (1), and little-endian operations with two different inputs (2).
1147 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1148 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1149                                SelectionDAG &DAG) {
1150   bool IsLE = DAG.getDataLayout().isLittleEndian();
1151   if (ShuffleKind == 0) {
1152     if (IsLE)
1153       return false;
1154     for (unsigned i = 0; i != 16; ++i)
1155       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1156         return false;
1157   } else if (ShuffleKind == 2) {
1158     if (!IsLE)
1159       return false;
1160     for (unsigned i = 0; i != 16; ++i)
1161       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1162         return false;
1163   } else if (ShuffleKind == 1) {
1164     unsigned j = IsLE ? 0 : 1;
1165     for (unsigned i = 0; i != 8; ++i)
1166       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1167           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1168         return false;
1169   }
1170   return true;
1171 }
1172 
1173 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1174 /// VPKUWUM instruction.
1175 /// The ShuffleKind distinguishes between big-endian operations with
1176 /// two different inputs (0), either-endian operations with two identical
1177 /// inputs (1), and little-endian operations with two different inputs (2).
1178 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1179 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1180                                SelectionDAG &DAG) {
1181   bool IsLE = DAG.getDataLayout().isLittleEndian();
1182   if (ShuffleKind == 0) {
1183     if (IsLE)
1184       return false;
1185     for (unsigned i = 0; i != 16; i += 2)
1186       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1187           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1188         return false;
1189   } else if (ShuffleKind == 2) {
1190     if (!IsLE)
1191       return false;
1192     for (unsigned i = 0; i != 16; i += 2)
1193       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1194           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1195         return false;
1196   } else if (ShuffleKind == 1) {
1197     unsigned j = IsLE ? 0 : 2;
1198     for (unsigned i = 0; i != 8; i += 2)
1199       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1200           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1201           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1202           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1203         return false;
1204   }
1205   return true;
1206 }
1207 
1208 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1209 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1210 /// current subtarget.
1211 ///
1212 /// The ShuffleKind distinguishes between big-endian operations with
1213 /// two different inputs (0), either-endian operations with two identical
1214 /// inputs (1), and little-endian operations with two different inputs (2).
1215 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1216 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1217                                SelectionDAG &DAG) {
1218   const PPCSubtarget& Subtarget =
1219     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1220   if (!Subtarget.hasP8Vector())
1221     return false;
1222 
1223   bool IsLE = DAG.getDataLayout().isLittleEndian();
1224   if (ShuffleKind == 0) {
1225     if (IsLE)
1226       return false;
1227     for (unsigned i = 0; i != 16; i += 4)
1228       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1229           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1230           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1231           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1232         return false;
1233   } else if (ShuffleKind == 2) {
1234     if (!IsLE)
1235       return false;
1236     for (unsigned i = 0; i != 16; i += 4)
1237       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1238           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1239           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1240           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1241         return false;
1242   } else if (ShuffleKind == 1) {
1243     unsigned j = IsLE ? 0 : 4;
1244     for (unsigned i = 0; i != 8; i += 4)
1245       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1246           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1247           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1248           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1249           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1250           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1251           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1252           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1253         return false;
1254   }
1255   return true;
1256 }
1257 
1258 /// isVMerge - Common function, used to match vmrg* shuffles.
1259 ///
1260 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1261                      unsigned LHSStart, unsigned RHSStart) {
1262   if (N->getValueType(0) != MVT::v16i8)
1263     return false;
1264   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1265          "Unsupported merge size!");
1266 
1267   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1268     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1269       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1270                              LHSStart+j+i*UnitSize) ||
1271           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1272                              RHSStart+j+i*UnitSize))
1273         return false;
1274     }
1275   return true;
1276 }
1277 
1278 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1279 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1280 /// The ShuffleKind distinguishes between big-endian merges with two
1281 /// different inputs (0), either-endian merges with two identical inputs (1),
1282 /// and little-endian merges with two different inputs (2).  For the latter,
1283 /// the input operands are swapped (see PPCInstrAltivec.td).
1284 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1285                              unsigned ShuffleKind, SelectionDAG &DAG) {
1286   if (DAG.getDataLayout().isLittleEndian()) {
1287     if (ShuffleKind == 1) // unary
1288       return isVMerge(N, UnitSize, 0, 0);
1289     else if (ShuffleKind == 2) // swapped
1290       return isVMerge(N, UnitSize, 0, 16);
1291     else
1292       return false;
1293   } else {
1294     if (ShuffleKind == 1) // unary
1295       return isVMerge(N, UnitSize, 8, 8);
1296     else if (ShuffleKind == 0) // normal
1297       return isVMerge(N, UnitSize, 8, 24);
1298     else
1299       return false;
1300   }
1301 }
1302 
1303 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1304 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1305 /// The ShuffleKind distinguishes between big-endian merges with two
1306 /// different inputs (0), either-endian merges with two identical inputs (1),
1307 /// and little-endian merges with two different inputs (2).  For the latter,
1308 /// the input operands are swapped (see PPCInstrAltivec.td).
1309 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1310                              unsigned ShuffleKind, SelectionDAG &DAG) {
1311   if (DAG.getDataLayout().isLittleEndian()) {
1312     if (ShuffleKind == 1) // unary
1313       return isVMerge(N, UnitSize, 8, 8);
1314     else if (ShuffleKind == 2) // swapped
1315       return isVMerge(N, UnitSize, 8, 24);
1316     else
1317       return false;
1318   } else {
1319     if (ShuffleKind == 1) // unary
1320       return isVMerge(N, UnitSize, 0, 0);
1321     else if (ShuffleKind == 0) // normal
1322       return isVMerge(N, UnitSize, 0, 16);
1323     else
1324       return false;
1325   }
1326 }
1327 
1328 /**
1329  * \brief Common function used to match vmrgew and vmrgow shuffles
1330  *
1331  * The indexOffset determines whether to look for even or odd words in
1332  * the shuffle mask. This is based on the of the endianness of the target
1333  * machine.
1334  *   - Little Endian:
1335  *     - Use offset of 0 to check for odd elements
1336  *     - Use offset of 4 to check for even elements
1337  *   - Big Endian:
1338  *     - Use offset of 0 to check for even elements
1339  *     - Use offset of 4 to check for odd elements
1340  * A detailed description of the vector element ordering for little endian and
1341  * big endian can be found at
1342  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1343  * Targeting your applications - what little endian and big endian IBM XL C/C++
1344  * compiler differences mean to you
1345  *
1346  * The mask to the shuffle vector instruction specifies the indices of the
1347  * elements from the two input vectors to place in the result. The elements are
1348  * numbered in array-access order, starting with the first vector. These vectors
1349  * are always of type v16i8, thus each vector will contain 16 elements of size
1350  * 8. More info on the shuffle vector can be found in the
1351  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1352  * Language Reference.
1353  *
1354  * The RHSStartValue indicates whether the same input vectors are used (unary)
1355  * or two different input vectors are used, based on the following:
1356  *   - If the instruction uses the same vector for both inputs, the range of the
1357  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1358  *     be 0.
1359  *   - If the instruction has two different vectors then the range of the
1360  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1361  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1362  *     to 31 specify elements in the second vector).
1363  *
1364  * \param[in] N The shuffle vector SD Node to analyze
1365  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1366  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1367  * vector to the shuffle_vector instruction
1368  * \return true iff this shuffle vector represents an even or odd word merge
1369  */
1370 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1371                      unsigned RHSStartValue) {
1372   if (N->getValueType(0) != MVT::v16i8)
1373     return false;
1374 
1375   for (unsigned i = 0; i < 2; ++i)
1376     for (unsigned j = 0; j < 4; ++j)
1377       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1378                              i*RHSStartValue+j+IndexOffset) ||
1379           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1380                              i*RHSStartValue+j+IndexOffset+8))
1381         return false;
1382   return true;
1383 }
1384 
1385 /**
1386  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1387  * vmrgow instructions.
1388  *
1389  * \param[in] N The shuffle vector SD Node to analyze
1390  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1391  * \param[in] ShuffleKind Identify the type of merge:
1392  *   - 0 = big-endian merge with two different inputs;
1393  *   - 1 = either-endian merge with two identical inputs;
1394  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1395  *     little-endian merges).
1396  * \param[in] DAG The current SelectionDAG
1397  * \return true iff this shuffle mask
1398  */
1399 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1400                               unsigned ShuffleKind, SelectionDAG &DAG) {
1401   if (DAG.getDataLayout().isLittleEndian()) {
1402     unsigned indexOffset = CheckEven ? 4 : 0;
1403     if (ShuffleKind == 1) // Unary
1404       return isVMerge(N, indexOffset, 0);
1405     else if (ShuffleKind == 2) // swapped
1406       return isVMerge(N, indexOffset, 16);
1407     else
1408       return false;
1409   }
1410   else {
1411     unsigned indexOffset = CheckEven ? 0 : 4;
1412     if (ShuffleKind == 1) // Unary
1413       return isVMerge(N, indexOffset, 0);
1414     else if (ShuffleKind == 0) // Normal
1415       return isVMerge(N, indexOffset, 16);
1416     else
1417       return false;
1418   }
1419   return false;
1420 }
1421 
1422 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1423 /// amount, otherwise return -1.
1424 /// The ShuffleKind distinguishes between big-endian operations with two
1425 /// different inputs (0), either-endian operations with two identical inputs
1426 /// (1), and little-endian operations with two different inputs (2).  For the
1427 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1428 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1429                              SelectionDAG &DAG) {
1430   if (N->getValueType(0) != MVT::v16i8)
1431     return -1;
1432 
1433   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1434 
1435   // Find the first non-undef value in the shuffle mask.
1436   unsigned i;
1437   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1438     /*search*/;
1439 
1440   if (i == 16) return -1;  // all undef.
1441 
1442   // Otherwise, check to see if the rest of the elements are consecutively
1443   // numbered from this value.
1444   unsigned ShiftAmt = SVOp->getMaskElt(i);
1445   if (ShiftAmt < i) return -1;
1446 
1447   ShiftAmt -= i;
1448   bool isLE = DAG.getDataLayout().isLittleEndian();
1449 
1450   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1451     // Check the rest of the elements to see if they are consecutive.
1452     for (++i; i != 16; ++i)
1453       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1454         return -1;
1455   } else if (ShuffleKind == 1) {
1456     // Check the rest of the elements to see if they are consecutive.
1457     for (++i; i != 16; ++i)
1458       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1459         return -1;
1460   } else
1461     return -1;
1462 
1463   if (isLE)
1464     ShiftAmt = 16 - ShiftAmt;
1465 
1466   return ShiftAmt;
1467 }
1468 
1469 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1470 /// specifies a splat of a single element that is suitable for input to
1471 /// VSPLTB/VSPLTH/VSPLTW.
1472 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1473   assert(N->getValueType(0) == MVT::v16i8 &&
1474          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1475 
1476   // The consecutive indices need to specify an element, not part of two
1477   // different elements.  So abandon ship early if this isn't the case.
1478   if (N->getMaskElt(0) % EltSize != 0)
1479     return false;
1480 
1481   // This is a splat operation if each element of the permute is the same, and
1482   // if the value doesn't reference the second vector.
1483   unsigned ElementBase = N->getMaskElt(0);
1484 
1485   // FIXME: Handle UNDEF elements too!
1486   if (ElementBase >= 16)
1487     return false;
1488 
1489   // Check that the indices are consecutive, in the case of a multi-byte element
1490   // splatted with a v16i8 mask.
1491   for (unsigned i = 1; i != EltSize; ++i)
1492     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1493       return false;
1494 
1495   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1496     if (N->getMaskElt(i) < 0) continue;
1497     for (unsigned j = 0; j != EltSize; ++j)
1498       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1499         return false;
1500   }
1501   return true;
1502 }
1503 
1504 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1505                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1506 
1507   // Check that the mask is shuffling words
1508   for (unsigned i = 0; i < 4; ++i) {
1509     unsigned B0 = N->getMaskElt(i*4);
1510     unsigned B1 = N->getMaskElt(i*4+1);
1511     unsigned B2 = N->getMaskElt(i*4+2);
1512     unsigned B3 = N->getMaskElt(i*4+3);
1513     if (B0 % 4)
1514       return false;
1515     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1516       return false;
1517   }
1518 
1519   // Now we look at mask elements 0,4,8,12
1520   unsigned M0 = N->getMaskElt(0) / 4;
1521   unsigned M1 = N->getMaskElt(4) / 4;
1522   unsigned M2 = N->getMaskElt(8) / 4;
1523   unsigned M3 = N->getMaskElt(12) / 4;
1524   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1525   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1526 
1527   // Below, let H and L be arbitrary elements of the shuffle mask
1528   // where H is in the range [4,7] and L is in the range [0,3].
1529   // H, 1, 2, 3 or L, 5, 6, 7
1530   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1531       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1532     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1533     InsertAtByte = IsLE ? 12 : 0;
1534     Swap = M0 < 4;
1535     return true;
1536   }
1537   // 0, H, 2, 3 or 4, L, 6, 7
1538   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1539       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1540     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1541     InsertAtByte = IsLE ? 8 : 4;
1542     Swap = M1 < 4;
1543     return true;
1544   }
1545   // 0, 1, H, 3 or 4, 5, L, 7
1546   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1547       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1548     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1549     InsertAtByte = IsLE ? 4 : 8;
1550     Swap = M2 < 4;
1551     return true;
1552   }
1553   // 0, 1, 2, H or 4, 5, 6, L
1554   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1555       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1556     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1557     InsertAtByte = IsLE ? 0 : 12;
1558     Swap = M3 < 4;
1559     return true;
1560   }
1561 
1562   // If both vector operands for the shuffle are the same vector, the mask will
1563   // contain only elements from the first one and the second one will be undef.
1564   if (N->getOperand(1).isUndef()) {
1565     ShiftElts = 0;
1566     Swap = true;
1567     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1568     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1569       InsertAtByte = IsLE ? 12 : 0;
1570       return true;
1571     }
1572     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1573       InsertAtByte = IsLE ? 8 : 4;
1574       return true;
1575     }
1576     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1577       InsertAtByte = IsLE ? 4 : 8;
1578       return true;
1579     }
1580     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1581       InsertAtByte = IsLE ? 0 : 12;
1582       return true;
1583     }
1584   }
1585 
1586   return false;
1587 }
1588 
1589 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1590 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1591 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1592                                 SelectionDAG &DAG) {
1593   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1594   assert(isSplatShuffleMask(SVOp, EltSize));
1595   if (DAG.getDataLayout().isLittleEndian())
1596     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1597   else
1598     return SVOp->getMaskElt(0) / EltSize;
1599 }
1600 
1601 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1602 /// by using a vspltis[bhw] instruction of the specified element size, return
1603 /// the constant being splatted.  The ByteSize field indicates the number of
1604 /// bytes of each element [124] -> [bhw].
1605 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1606   SDValue OpVal(nullptr, 0);
1607 
1608   // If ByteSize of the splat is bigger than the element size of the
1609   // build_vector, then we have a case where we are checking for a splat where
1610   // multiple elements of the buildvector are folded together into a single
1611   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1612   unsigned EltSize = 16/N->getNumOperands();
1613   if (EltSize < ByteSize) {
1614     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1615     SDValue UniquedVals[4];
1616     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1617 
1618     // See if all of the elements in the buildvector agree across.
1619     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1620       if (N->getOperand(i).isUndef()) continue;
1621       // If the element isn't a constant, bail fully out.
1622       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1623 
1624 
1625       if (!UniquedVals[i&(Multiple-1)].getNode())
1626         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1627       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1628         return SDValue();  // no match.
1629     }
1630 
1631     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1632     // either constant or undef values that are identical for each chunk.  See
1633     // if these chunks can form into a larger vspltis*.
1634 
1635     // Check to see if all of the leading entries are either 0 or -1.  If
1636     // neither, then this won't fit into the immediate field.
1637     bool LeadingZero = true;
1638     bool LeadingOnes = true;
1639     for (unsigned i = 0; i != Multiple-1; ++i) {
1640       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1641 
1642       LeadingZero &= isNullConstant(UniquedVals[i]);
1643       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1644     }
1645     // Finally, check the least significant entry.
1646     if (LeadingZero) {
1647       if (!UniquedVals[Multiple-1].getNode())
1648         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1649       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1650       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1651         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1652     }
1653     if (LeadingOnes) {
1654       if (!UniquedVals[Multiple-1].getNode())
1655         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1656       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1657       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1658         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1659     }
1660 
1661     return SDValue();
1662   }
1663 
1664   // Check to see if this buildvec has a single non-undef value in its elements.
1665   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1666     if (N->getOperand(i).isUndef()) continue;
1667     if (!OpVal.getNode())
1668       OpVal = N->getOperand(i);
1669     else if (OpVal != N->getOperand(i))
1670       return SDValue();
1671   }
1672 
1673   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1674 
1675   unsigned ValSizeInBytes = EltSize;
1676   uint64_t Value = 0;
1677   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1678     Value = CN->getZExtValue();
1679   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1680     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1681     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1682   }
1683 
1684   // If the splat value is larger than the element value, then we can never do
1685   // this splat.  The only case that we could fit the replicated bits into our
1686   // immediate field for would be zero, and we prefer to use vxor for it.
1687   if (ValSizeInBytes < ByteSize) return SDValue();
1688 
1689   // If the element value is larger than the splat value, check if it consists
1690   // of a repeated bit pattern of size ByteSize.
1691   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1692     return SDValue();
1693 
1694   // Properly sign extend the value.
1695   int MaskVal = SignExtend32(Value, ByteSize * 8);
1696 
1697   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1698   if (MaskVal == 0) return SDValue();
1699 
1700   // Finally, if this value fits in a 5 bit sext field, return it
1701   if (SignExtend32<5>(MaskVal) == MaskVal)
1702     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1703   return SDValue();
1704 }
1705 
1706 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1707 /// amount, otherwise return -1.
1708 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1709   EVT VT = N->getValueType(0);
1710   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1711     return -1;
1712 
1713   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1714 
1715   // Find the first non-undef value in the shuffle mask.
1716   unsigned i;
1717   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1718     /*search*/;
1719 
1720   if (i == 4) return -1;  // all undef.
1721 
1722   // Otherwise, check to see if the rest of the elements are consecutively
1723   // numbered from this value.
1724   unsigned ShiftAmt = SVOp->getMaskElt(i);
1725   if (ShiftAmt < i) return -1;
1726   ShiftAmt -= i;
1727 
1728   // Check the rest of the elements to see if they are consecutive.
1729   for (++i; i != 4; ++i)
1730     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1731       return -1;
1732 
1733   return ShiftAmt;
1734 }
1735 
1736 //===----------------------------------------------------------------------===//
1737 //  Addressing Mode Selection
1738 //===----------------------------------------------------------------------===//
1739 
1740 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1741 /// or 64-bit immediate, and if the value can be accurately represented as a
1742 /// sign extension from a 16-bit value.  If so, this returns true and the
1743 /// immediate.
1744 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1745   if (!isa<ConstantSDNode>(N))
1746     return false;
1747 
1748   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1749   if (N->getValueType(0) == MVT::i32)
1750     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1751   else
1752     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1753 }
1754 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1755   return isIntS16Immediate(Op.getNode(), Imm);
1756 }
1757 
1758 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1759 /// can be represented as an indexed [r+r] operation.  Returns false if it
1760 /// can be more efficiently represented with [r+imm].
1761 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1762                                             SDValue &Index,
1763                                             SelectionDAG &DAG) const {
1764   short imm = 0;
1765   if (N.getOpcode() == ISD::ADD) {
1766     if (isIntS16Immediate(N.getOperand(1), imm))
1767       return false;    // r+i
1768     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1769       return false;    // r+i
1770 
1771     Base = N.getOperand(0);
1772     Index = N.getOperand(1);
1773     return true;
1774   } else if (N.getOpcode() == ISD::OR) {
1775     if (isIntS16Immediate(N.getOperand(1), imm))
1776       return false;    // r+i can fold it if we can.
1777 
1778     // If this is an or of disjoint bitfields, we can codegen this as an add
1779     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1780     // disjoint.
1781     APInt LHSKnownZero, LHSKnownOne;
1782     APInt RHSKnownZero, RHSKnownOne;
1783     DAG.computeKnownBits(N.getOperand(0),
1784                          LHSKnownZero, LHSKnownOne);
1785 
1786     if (LHSKnownZero.getBoolValue()) {
1787       DAG.computeKnownBits(N.getOperand(1),
1788                            RHSKnownZero, RHSKnownOne);
1789       // If all of the bits are known zero on the LHS or RHS, the add won't
1790       // carry.
1791       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1792         Base = N.getOperand(0);
1793         Index = N.getOperand(1);
1794         return true;
1795       }
1796     }
1797   }
1798 
1799   return false;
1800 }
1801 
1802 // If we happen to be doing an i64 load or store into a stack slot that has
1803 // less than a 4-byte alignment, then the frame-index elimination may need to
1804 // use an indexed load or store instruction (because the offset may not be a
1805 // multiple of 4). The extra register needed to hold the offset comes from the
1806 // register scavenger, and it is possible that the scavenger will need to use
1807 // an emergency spill slot. As a result, we need to make sure that a spill slot
1808 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1809 // stack slot.
1810 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1811   // FIXME: This does not handle the LWA case.
1812   if (VT != MVT::i64)
1813     return;
1814 
1815   // NOTE: We'll exclude negative FIs here, which come from argument
1816   // lowering, because there are no known test cases triggering this problem
1817   // using packed structures (or similar). We can remove this exclusion if
1818   // we find such a test case. The reason why this is so test-case driven is
1819   // because this entire 'fixup' is only to prevent crashes (from the
1820   // register scavenger) on not-really-valid inputs. For example, if we have:
1821   //   %a = alloca i1
1822   //   %b = bitcast i1* %a to i64*
1823   //   store i64* a, i64 b
1824   // then the store should really be marked as 'align 1', but is not. If it
1825   // were marked as 'align 1' then the indexed form would have been
1826   // instruction-selected initially, and the problem this 'fixup' is preventing
1827   // won't happen regardless.
1828   if (FrameIdx < 0)
1829     return;
1830 
1831   MachineFunction &MF = DAG.getMachineFunction();
1832   MachineFrameInfo &MFI = MF.getFrameInfo();
1833 
1834   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1835   if (Align >= 4)
1836     return;
1837 
1838   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1839   FuncInfo->setHasNonRISpills();
1840 }
1841 
1842 /// Returns true if the address N can be represented by a base register plus
1843 /// a signed 16-bit displacement [r+imm], and if it is not better
1844 /// represented as reg+reg.  If Aligned is true, only accept displacements
1845 /// suitable for STD and friends, i.e. multiples of 4.
1846 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1847                                             SDValue &Base,
1848                                             SelectionDAG &DAG,
1849                                             bool Aligned) const {
1850   // FIXME dl should come from parent load or store, not from address
1851   SDLoc dl(N);
1852   // If this can be more profitably realized as r+r, fail.
1853   if (SelectAddressRegReg(N, Disp, Base, DAG))
1854     return false;
1855 
1856   if (N.getOpcode() == ISD::ADD) {
1857     short imm = 0;
1858     if (isIntS16Immediate(N.getOperand(1), imm) &&
1859         (!Aligned || (imm & 3) == 0)) {
1860       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1861       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1862         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1863         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1864       } else {
1865         Base = N.getOperand(0);
1866       }
1867       return true; // [r+i]
1868     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1869       // Match LOAD (ADD (X, Lo(G))).
1870       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1871              && "Cannot handle constant offsets yet!");
1872       Disp = N.getOperand(1).getOperand(0);  // The global address.
1873       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1874              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1875              Disp.getOpcode() == ISD::TargetConstantPool ||
1876              Disp.getOpcode() == ISD::TargetJumpTable);
1877       Base = N.getOperand(0);
1878       return true;  // [&g+r]
1879     }
1880   } else if (N.getOpcode() == ISD::OR) {
1881     short imm = 0;
1882     if (isIntS16Immediate(N.getOperand(1), imm) &&
1883         (!Aligned || (imm & 3) == 0)) {
1884       // If this is an or of disjoint bitfields, we can codegen this as an add
1885       // (for better address arithmetic) if the LHS and RHS of the OR are
1886       // provably disjoint.
1887       APInt LHSKnownZero, LHSKnownOne;
1888       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1889 
1890       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1891         // If all of the bits are known zero on the LHS or RHS, the add won't
1892         // carry.
1893         if (FrameIndexSDNode *FI =
1894               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1895           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1896           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1897         } else {
1898           Base = N.getOperand(0);
1899         }
1900         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1901         return true;
1902       }
1903     }
1904   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1905     // Loading from a constant address.
1906 
1907     // If this address fits entirely in a 16-bit sext immediate field, codegen
1908     // this as "d, 0"
1909     short Imm;
1910     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1911       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1912       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1913                              CN->getValueType(0));
1914       return true;
1915     }
1916 
1917     // Handle 32-bit sext immediates with LIS + addr mode.
1918     if ((CN->getValueType(0) == MVT::i32 ||
1919          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1920         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1921       int Addr = (int)CN->getZExtValue();
1922 
1923       // Otherwise, break this down into an LIS + disp.
1924       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1925 
1926       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1927                                    MVT::i32);
1928       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1929       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1930       return true;
1931     }
1932   }
1933 
1934   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1935   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1936     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1937     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1938   } else
1939     Base = N;
1940   return true;      // [r+0]
1941 }
1942 
1943 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1944 /// represented as an indexed [r+r] operation.
1945 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1946                                                 SDValue &Index,
1947                                                 SelectionDAG &DAG) const {
1948   // Check to see if we can easily represent this as an [r+r] address.  This
1949   // will fail if it thinks that the address is more profitably represented as
1950   // reg+imm, e.g. where imm = 0.
1951   if (SelectAddressRegReg(N, Base, Index, DAG))
1952     return true;
1953 
1954   // If the operand is an addition, always emit this as [r+r], since this is
1955   // better (for code size, and execution, as the memop does the add for free)
1956   // than emitting an explicit add.
1957   if (N.getOpcode() == ISD::ADD) {
1958     Base = N.getOperand(0);
1959     Index = N.getOperand(1);
1960     return true;
1961   }
1962 
1963   // Otherwise, do it the hard way, using R0 as the base register.
1964   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1965                          N.getValueType());
1966   Index = N;
1967   return true;
1968 }
1969 
1970 /// getPreIndexedAddressParts - returns true by value, base pointer and
1971 /// offset pointer and addressing mode by reference if the node's address
1972 /// can be legally represented as pre-indexed load / store address.
1973 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1974                                                   SDValue &Offset,
1975                                                   ISD::MemIndexedMode &AM,
1976                                                   SelectionDAG &DAG) const {
1977   if (DisablePPCPreinc) return false;
1978 
1979   bool isLoad = true;
1980   SDValue Ptr;
1981   EVT VT;
1982   unsigned Alignment;
1983   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1984     Ptr = LD->getBasePtr();
1985     VT = LD->getMemoryVT();
1986     Alignment = LD->getAlignment();
1987   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1988     Ptr = ST->getBasePtr();
1989     VT  = ST->getMemoryVT();
1990     Alignment = ST->getAlignment();
1991     isLoad = false;
1992   } else
1993     return false;
1994 
1995   // PowerPC doesn't have preinc load/store instructions for vectors (except
1996   // for QPX, which does have preinc r+r forms).
1997   if (VT.isVector()) {
1998     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1999       return false;
2000     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2001       AM = ISD::PRE_INC;
2002       return true;
2003     }
2004   }
2005 
2006   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2007 
2008     // Common code will reject creating a pre-inc form if the base pointer
2009     // is a frame index, or if N is a store and the base pointer is either
2010     // the same as or a predecessor of the value being stored.  Check for
2011     // those situations here, and try with swapped Base/Offset instead.
2012     bool Swap = false;
2013 
2014     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2015       Swap = true;
2016     else if (!isLoad) {
2017       SDValue Val = cast<StoreSDNode>(N)->getValue();
2018       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2019         Swap = true;
2020     }
2021 
2022     if (Swap)
2023       std::swap(Base, Offset);
2024 
2025     AM = ISD::PRE_INC;
2026     return true;
2027   }
2028 
2029   // LDU/STU can only handle immediates that are a multiple of 4.
2030   if (VT != MVT::i64) {
2031     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2032       return false;
2033   } else {
2034     // LDU/STU need an address with at least 4-byte alignment.
2035     if (Alignment < 4)
2036       return false;
2037 
2038     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2039       return false;
2040   }
2041 
2042   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2043     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2044     // sext i32 to i64 when addr mode is r+i.
2045     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2046         LD->getExtensionType() == ISD::SEXTLOAD &&
2047         isa<ConstantSDNode>(Offset))
2048       return false;
2049   }
2050 
2051   AM = ISD::PRE_INC;
2052   return true;
2053 }
2054 
2055 //===----------------------------------------------------------------------===//
2056 //  LowerOperation implementation
2057 //===----------------------------------------------------------------------===//
2058 
2059 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2060 /// and LoOpFlags to the target MO flags.
2061 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2062                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2063                                const GlobalValue *GV = nullptr) {
2064   HiOpFlags = PPCII::MO_HA;
2065   LoOpFlags = PPCII::MO_LO;
2066 
2067   // Don't use the pic base if not in PIC relocation model.
2068   if (IsPIC) {
2069     HiOpFlags |= PPCII::MO_PIC_FLAG;
2070     LoOpFlags |= PPCII::MO_PIC_FLAG;
2071   }
2072 
2073   // If this is a reference to a global value that requires a non-lazy-ptr, make
2074   // sure that instruction lowering adds it.
2075   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2076     HiOpFlags |= PPCII::MO_NLP_FLAG;
2077     LoOpFlags |= PPCII::MO_NLP_FLAG;
2078 
2079     if (GV->hasHiddenVisibility()) {
2080       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2081       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2082     }
2083   }
2084 }
2085 
2086 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2087                              SelectionDAG &DAG) {
2088   SDLoc DL(HiPart);
2089   EVT PtrVT = HiPart.getValueType();
2090   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2091 
2092   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2093   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2094 
2095   // With PIC, the first instruction is actually "GR+hi(&G)".
2096   if (isPIC)
2097     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2098                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2099 
2100   // Generate non-pic code that has direct accesses to the constant pool.
2101   // The address of the global is just (hi(&g)+lo(&g)).
2102   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2103 }
2104 
2105 static void setUsesTOCBasePtr(MachineFunction &MF) {
2106   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2107   FuncInfo->setUsesTOCBasePtr();
2108 }
2109 
2110 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2111   setUsesTOCBasePtr(DAG.getMachineFunction());
2112 }
2113 
2114 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2115                            SDValue GA) {
2116   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2117   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2118                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2119 
2120   SDValue Ops[] = { GA, Reg };
2121   return DAG.getMemIntrinsicNode(
2122       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2123       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2124       false, 0);
2125 }
2126 
2127 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2128                                              SelectionDAG &DAG) const {
2129   EVT PtrVT = Op.getValueType();
2130   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2131   const Constant *C = CP->getConstVal();
2132 
2133   // 64-bit SVR4 ABI code is always position-independent.
2134   // The actual address of the GlobalValue is stored in the TOC.
2135   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2136     setUsesTOCBasePtr(DAG);
2137     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2138     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2139   }
2140 
2141   unsigned MOHiFlag, MOLoFlag;
2142   bool IsPIC = isPositionIndependent();
2143   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2144 
2145   if (IsPIC && Subtarget.isSVR4ABI()) {
2146     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2147                                            PPCII::MO_PIC_FLAG);
2148     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2149   }
2150 
2151   SDValue CPIHi =
2152     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2153   SDValue CPILo =
2154     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2155   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2156 }
2157 
2158 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2159   EVT PtrVT = Op.getValueType();
2160   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2161 
2162   // 64-bit SVR4 ABI code is always position-independent.
2163   // The actual address of the GlobalValue is stored in the TOC.
2164   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2165     setUsesTOCBasePtr(DAG);
2166     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2167     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2168   }
2169 
2170   unsigned MOHiFlag, MOLoFlag;
2171   bool IsPIC = isPositionIndependent();
2172   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2173 
2174   if (IsPIC && Subtarget.isSVR4ABI()) {
2175     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2176                                         PPCII::MO_PIC_FLAG);
2177     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2178   }
2179 
2180   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2181   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2182   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2183 }
2184 
2185 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2186                                              SelectionDAG &DAG) const {
2187   EVT PtrVT = Op.getValueType();
2188   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2189   const BlockAddress *BA = BASDN->getBlockAddress();
2190 
2191   // 64-bit SVR4 ABI code is always position-independent.
2192   // The actual BlockAddress is stored in the TOC.
2193   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2194     setUsesTOCBasePtr(DAG);
2195     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2196     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2197   }
2198 
2199   unsigned MOHiFlag, MOLoFlag;
2200   bool IsPIC = isPositionIndependent();
2201   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2202   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2203   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2204   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2205 }
2206 
2207 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2208                                               SelectionDAG &DAG) const {
2209 
2210   // FIXME: TLS addresses currently use medium model code sequences,
2211   // which is the most useful form.  Eventually support for small and
2212   // large models could be added if users need it, at the cost of
2213   // additional complexity.
2214   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2215   if (DAG.getTarget().Options.EmulatedTLS)
2216     return LowerToTLSEmulatedModel(GA, DAG);
2217 
2218   SDLoc dl(GA);
2219   const GlobalValue *GV = GA->getGlobal();
2220   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2221   bool is64bit = Subtarget.isPPC64();
2222   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2223   PICLevel::Level picLevel = M->getPICLevel();
2224 
2225   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2226 
2227   if (Model == TLSModel::LocalExec) {
2228     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2229                                                PPCII::MO_TPREL_HA);
2230     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2231                                                PPCII::MO_TPREL_LO);
2232     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2233                                      is64bit ? MVT::i64 : MVT::i32);
2234     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2235     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2236   }
2237 
2238   if (Model == TLSModel::InitialExec) {
2239     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2240     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2241                                                 PPCII::MO_TLS);
2242     SDValue GOTPtr;
2243     if (is64bit) {
2244       setUsesTOCBasePtr(DAG);
2245       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2246       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2247                            PtrVT, GOTReg, TGA);
2248     } else
2249       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2250     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2251                                    PtrVT, TGA, GOTPtr);
2252     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2253   }
2254 
2255   if (Model == TLSModel::GeneralDynamic) {
2256     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2257     SDValue GOTPtr;
2258     if (is64bit) {
2259       setUsesTOCBasePtr(DAG);
2260       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2261       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2262                                    GOTReg, TGA);
2263     } else {
2264       if (picLevel == PICLevel::SmallPIC)
2265         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2266       else
2267         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2268     }
2269     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2270                        GOTPtr, TGA, TGA);
2271   }
2272 
2273   if (Model == TLSModel::LocalDynamic) {
2274     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2275     SDValue GOTPtr;
2276     if (is64bit) {
2277       setUsesTOCBasePtr(DAG);
2278       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2279       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2280                            GOTReg, TGA);
2281     } else {
2282       if (picLevel == PICLevel::SmallPIC)
2283         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2284       else
2285         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2286     }
2287     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2288                                   PtrVT, GOTPtr, TGA, TGA);
2289     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2290                                       PtrVT, TLSAddr, TGA);
2291     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2292   }
2293 
2294   llvm_unreachable("Unknown TLS model!");
2295 }
2296 
2297 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2298                                               SelectionDAG &DAG) const {
2299   EVT PtrVT = Op.getValueType();
2300   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2301   SDLoc DL(GSDN);
2302   const GlobalValue *GV = GSDN->getGlobal();
2303 
2304   // 64-bit SVR4 ABI code is always position-independent.
2305   // The actual address of the GlobalValue is stored in the TOC.
2306   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2307     setUsesTOCBasePtr(DAG);
2308     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2309     return getTOCEntry(DAG, DL, true, GA);
2310   }
2311 
2312   unsigned MOHiFlag, MOLoFlag;
2313   bool IsPIC = isPositionIndependent();
2314   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2315 
2316   if (IsPIC && Subtarget.isSVR4ABI()) {
2317     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2318                                             GSDN->getOffset(),
2319                                             PPCII::MO_PIC_FLAG);
2320     return getTOCEntry(DAG, DL, false, GA);
2321   }
2322 
2323   SDValue GAHi =
2324     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2325   SDValue GALo =
2326     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2327 
2328   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2329 
2330   // If the global reference is actually to a non-lazy-pointer, we have to do an
2331   // extra load to get the address of the global.
2332   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2333     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2334   return Ptr;
2335 }
2336 
2337 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2338   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2339   SDLoc dl(Op);
2340 
2341   if (Op.getValueType() == MVT::v2i64) {
2342     // When the operands themselves are v2i64 values, we need to do something
2343     // special because VSX has no underlying comparison operations for these.
2344     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2345       // Equality can be handled by casting to the legal type for Altivec
2346       // comparisons, everything else needs to be expanded.
2347       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2348         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2349                  DAG.getSetCC(dl, MVT::v4i32,
2350                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2351                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2352                    CC));
2353       }
2354 
2355       return SDValue();
2356     }
2357 
2358     // We handle most of these in the usual way.
2359     return Op;
2360   }
2361 
2362   // If we're comparing for equality to zero, expose the fact that this is
2363   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2364   // fold the new nodes.
2365   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2366     return V;
2367 
2368   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2369     // Leave comparisons against 0 and -1 alone for now, since they're usually
2370     // optimized.  FIXME: revisit this when we can custom lower all setcc
2371     // optimizations.
2372     if (C->isAllOnesValue() || C->isNullValue())
2373       return SDValue();
2374   }
2375 
2376   // If we have an integer seteq/setne, turn it into a compare against zero
2377   // by xor'ing the rhs with the lhs, which is faster than setting a
2378   // condition register, reading it back out, and masking the correct bit.  The
2379   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2380   // the result to other bit-twiddling opportunities.
2381   EVT LHSVT = Op.getOperand(0).getValueType();
2382   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2383     EVT VT = Op.getValueType();
2384     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2385                                 Op.getOperand(1));
2386     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2387   }
2388   return SDValue();
2389 }
2390 
2391 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2392   SDNode *Node = Op.getNode();
2393   EVT VT = Node->getValueType(0);
2394   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2395   SDValue InChain = Node->getOperand(0);
2396   SDValue VAListPtr = Node->getOperand(1);
2397   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2398   SDLoc dl(Node);
2399 
2400   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2401 
2402   // gpr_index
2403   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2404                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2405   InChain = GprIndex.getValue(1);
2406 
2407   if (VT == MVT::i64) {
2408     // Check if GprIndex is even
2409     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2410                                  DAG.getConstant(1, dl, MVT::i32));
2411     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2412                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2413     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2414                                           DAG.getConstant(1, dl, MVT::i32));
2415     // Align GprIndex to be even if it isn't
2416     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2417                            GprIndex);
2418   }
2419 
2420   // fpr index is 1 byte after gpr
2421   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2422                                DAG.getConstant(1, dl, MVT::i32));
2423 
2424   // fpr
2425   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2426                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2427   InChain = FprIndex.getValue(1);
2428 
2429   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2430                                        DAG.getConstant(8, dl, MVT::i32));
2431 
2432   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2433                                         DAG.getConstant(4, dl, MVT::i32));
2434 
2435   // areas
2436   SDValue OverflowArea =
2437       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2438   InChain = OverflowArea.getValue(1);
2439 
2440   SDValue RegSaveArea =
2441       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2442   InChain = RegSaveArea.getValue(1);
2443 
2444   // select overflow_area if index > 8
2445   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2446                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2447 
2448   // adjustment constant gpr_index * 4/8
2449   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2450                                     VT.isInteger() ? GprIndex : FprIndex,
2451                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2452                                                     MVT::i32));
2453 
2454   // OurReg = RegSaveArea + RegConstant
2455   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2456                                RegConstant);
2457 
2458   // Floating types are 32 bytes into RegSaveArea
2459   if (VT.isFloatingPoint())
2460     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2461                          DAG.getConstant(32, dl, MVT::i32));
2462 
2463   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2464   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2465                                    VT.isInteger() ? GprIndex : FprIndex,
2466                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2467                                                    MVT::i32));
2468 
2469   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2470                               VT.isInteger() ? VAListPtr : FprPtr,
2471                               MachinePointerInfo(SV), MVT::i8);
2472 
2473   // determine if we should load from reg_save_area or overflow_area
2474   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2475 
2476   // increase overflow_area by 4/8 if gpr/fpr > 8
2477   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2478                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2479                                           dl, MVT::i32));
2480 
2481   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2482                              OverflowAreaPlusN);
2483 
2484   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2485                               MachinePointerInfo(), MVT::i32);
2486 
2487   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2488 }
2489 
2490 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2491   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2492 
2493   // We have to copy the entire va_list struct:
2494   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2495   return DAG.getMemcpy(Op.getOperand(0), Op,
2496                        Op.getOperand(1), Op.getOperand(2),
2497                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2498                        false, MachinePointerInfo(), MachinePointerInfo());
2499 }
2500 
2501 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2502                                                   SelectionDAG &DAG) const {
2503   return Op.getOperand(0);
2504 }
2505 
2506 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2507                                                 SelectionDAG &DAG) const {
2508   SDValue Chain = Op.getOperand(0);
2509   SDValue Trmp = Op.getOperand(1); // trampoline
2510   SDValue FPtr = Op.getOperand(2); // nested function
2511   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2512   SDLoc dl(Op);
2513 
2514   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2515   bool isPPC64 = (PtrVT == MVT::i64);
2516   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2517 
2518   TargetLowering::ArgListTy Args;
2519   TargetLowering::ArgListEntry Entry;
2520 
2521   Entry.Ty = IntPtrTy;
2522   Entry.Node = Trmp; Args.push_back(Entry);
2523 
2524   // TrampSize == (isPPC64 ? 48 : 40);
2525   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2526                                isPPC64 ? MVT::i64 : MVT::i32);
2527   Args.push_back(Entry);
2528 
2529   Entry.Node = FPtr; Args.push_back(Entry);
2530   Entry.Node = Nest; Args.push_back(Entry);
2531 
2532   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2533   TargetLowering::CallLoweringInfo CLI(DAG);
2534   CLI.setDebugLoc(dl).setChain(Chain)
2535     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2536                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2537                std::move(Args));
2538 
2539   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2540   return CallResult.second;
2541 }
2542 
2543 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2544   MachineFunction &MF = DAG.getMachineFunction();
2545   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2546   EVT PtrVT = getPointerTy(MF.getDataLayout());
2547 
2548   SDLoc dl(Op);
2549 
2550   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2551     // vastart just stores the address of the VarArgsFrameIndex slot into the
2552     // memory location argument.
2553     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2554     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2555     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2556                         MachinePointerInfo(SV));
2557   }
2558 
2559   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2560   // We suppose the given va_list is already allocated.
2561   //
2562   // typedef struct {
2563   //  char gpr;     /* index into the array of 8 GPRs
2564   //                 * stored in the register save area
2565   //                 * gpr=0 corresponds to r3,
2566   //                 * gpr=1 to r4, etc.
2567   //                 */
2568   //  char fpr;     /* index into the array of 8 FPRs
2569   //                 * stored in the register save area
2570   //                 * fpr=0 corresponds to f1,
2571   //                 * fpr=1 to f2, etc.
2572   //                 */
2573   //  char *overflow_arg_area;
2574   //                /* location on stack that holds
2575   //                 * the next overflow argument
2576   //                 */
2577   //  char *reg_save_area;
2578   //               /* where r3:r10 and f1:f8 (if saved)
2579   //                * are stored
2580   //                */
2581   // } va_list[1];
2582 
2583   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2584   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2585   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2586                                             PtrVT);
2587   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2588                                  PtrVT);
2589 
2590   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2591   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2592 
2593   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2594   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2595 
2596   uint64_t FPROffset = 1;
2597   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2598 
2599   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2600 
2601   // Store first byte : number of int regs
2602   SDValue firstStore =
2603       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2604                         MachinePointerInfo(SV), MVT::i8);
2605   uint64_t nextOffset = FPROffset;
2606   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2607                                   ConstFPROffset);
2608 
2609   // Store second byte : number of float regs
2610   SDValue secondStore =
2611       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2612                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2613   nextOffset += StackOffset;
2614   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2615 
2616   // Store second word : arguments given on stack
2617   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2618                                     MachinePointerInfo(SV, nextOffset));
2619   nextOffset += FrameOffset;
2620   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2621 
2622   // Store third word : arguments given in registers
2623   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2624                       MachinePointerInfo(SV, nextOffset));
2625 }
2626 
2627 #include "PPCGenCallingConv.inc"
2628 
2629 // Function whose sole purpose is to kill compiler warnings
2630 // stemming from unused functions included from PPCGenCallingConv.inc.
2631 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2632   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2633 }
2634 
2635 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2636                                       CCValAssign::LocInfo &LocInfo,
2637                                       ISD::ArgFlagsTy &ArgFlags,
2638                                       CCState &State) {
2639   return true;
2640 }
2641 
2642 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2643                                              MVT &LocVT,
2644                                              CCValAssign::LocInfo &LocInfo,
2645                                              ISD::ArgFlagsTy &ArgFlags,
2646                                              CCState &State) {
2647   static const MCPhysReg ArgRegs[] = {
2648     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2649     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2650   };
2651   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2652 
2653   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2654 
2655   // Skip one register if the first unallocated register has an even register
2656   // number and there are still argument registers available which have not been
2657   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2658   // need to skip a register if RegNum is odd.
2659   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2660     State.AllocateReg(ArgRegs[RegNum]);
2661   }
2662 
2663   // Always return false here, as this function only makes sure that the first
2664   // unallocated register has an odd register number and does not actually
2665   // allocate a register for the current argument.
2666   return false;
2667 }
2668 
2669 bool
2670 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2671                                                   MVT &LocVT,
2672                                                   CCValAssign::LocInfo &LocInfo,
2673                                                   ISD::ArgFlagsTy &ArgFlags,
2674                                                   CCState &State) {
2675   static const MCPhysReg ArgRegs[] = {
2676     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2677     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2678   };
2679   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2680 
2681   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2682   int RegsLeft = NumArgRegs - RegNum;
2683 
2684   // Skip if there is not enough registers left for long double type (4 gpr regs
2685   // in soft float mode) and put long double argument on the stack.
2686   if (RegNum != NumArgRegs && RegsLeft < 4) {
2687     for (int i = 0; i < RegsLeft; i++) {
2688       State.AllocateReg(ArgRegs[RegNum + i]);
2689     }
2690   }
2691 
2692   return false;
2693 }
2694 
2695 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2696                                                MVT &LocVT,
2697                                                CCValAssign::LocInfo &LocInfo,
2698                                                ISD::ArgFlagsTy &ArgFlags,
2699                                                CCState &State) {
2700   static const MCPhysReg ArgRegs[] = {
2701     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2702     PPC::F8
2703   };
2704 
2705   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2706 
2707   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2708 
2709   // If there is only one Floating-point register left we need to put both f64
2710   // values of a split ppc_fp128 value on the stack.
2711   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2712     State.AllocateReg(ArgRegs[RegNum]);
2713   }
2714 
2715   // Always return false here, as this function only makes sure that the two f64
2716   // values a ppc_fp128 value is split into are both passed in registers or both
2717   // passed on the stack and does not actually allocate a register for the
2718   // current argument.
2719   return false;
2720 }
2721 
2722 /// FPR - The set of FP registers that should be allocated for arguments,
2723 /// on Darwin.
2724 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2725                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2726                                 PPC::F11, PPC::F12, PPC::F13};
2727 
2728 /// QFPR - The set of QPX registers that should be allocated for arguments.
2729 static const MCPhysReg QFPR[] = {
2730     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2731     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2732 
2733 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2734 /// the stack.
2735 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2736                                        unsigned PtrByteSize) {
2737   unsigned ArgSize = ArgVT.getStoreSize();
2738   if (Flags.isByVal())
2739     ArgSize = Flags.getByValSize();
2740 
2741   // Round up to multiples of the pointer size, except for array members,
2742   // which are always packed.
2743   if (!Flags.isInConsecutiveRegs())
2744     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2745 
2746   return ArgSize;
2747 }
2748 
2749 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2750 /// on the stack.
2751 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2752                                             ISD::ArgFlagsTy Flags,
2753                                             unsigned PtrByteSize) {
2754   unsigned Align = PtrByteSize;
2755 
2756   // Altivec parameters are padded to a 16 byte boundary.
2757   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2758       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2759       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2760       ArgVT == MVT::v1i128)
2761     Align = 16;
2762   // QPX vector types stored in double-precision are padded to a 32 byte
2763   // boundary.
2764   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2765     Align = 32;
2766 
2767   // ByVal parameters are aligned as requested.
2768   if (Flags.isByVal()) {
2769     unsigned BVAlign = Flags.getByValAlign();
2770     if (BVAlign > PtrByteSize) {
2771       if (BVAlign % PtrByteSize != 0)
2772           llvm_unreachable(
2773             "ByVal alignment is not a multiple of the pointer size");
2774 
2775       Align = BVAlign;
2776     }
2777   }
2778 
2779   // Array members are always packed to their original alignment.
2780   if (Flags.isInConsecutiveRegs()) {
2781     // If the array member was split into multiple registers, the first
2782     // needs to be aligned to the size of the full type.  (Except for
2783     // ppcf128, which is only aligned as its f64 components.)
2784     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2785       Align = OrigVT.getStoreSize();
2786     else
2787       Align = ArgVT.getStoreSize();
2788   }
2789 
2790   return Align;
2791 }
2792 
2793 /// CalculateStackSlotUsed - Return whether this argument will use its
2794 /// stack slot (instead of being passed in registers).  ArgOffset,
2795 /// AvailableFPRs, and AvailableVRs must hold the current argument
2796 /// position, and will be updated to account for this argument.
2797 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2798                                    ISD::ArgFlagsTy Flags,
2799                                    unsigned PtrByteSize,
2800                                    unsigned LinkageSize,
2801                                    unsigned ParamAreaSize,
2802                                    unsigned &ArgOffset,
2803                                    unsigned &AvailableFPRs,
2804                                    unsigned &AvailableVRs, bool HasQPX) {
2805   bool UseMemory = false;
2806 
2807   // Respect alignment of argument on the stack.
2808   unsigned Align =
2809     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2810   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2811   // If there's no space left in the argument save area, we must
2812   // use memory (this check also catches zero-sized arguments).
2813   if (ArgOffset >= LinkageSize + ParamAreaSize)
2814     UseMemory = true;
2815 
2816   // Allocate argument on the stack.
2817   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2818   if (Flags.isInConsecutiveRegsLast())
2819     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2820   // If we overran the argument save area, we must use memory
2821   // (this check catches arguments passed partially in memory)
2822   if (ArgOffset > LinkageSize + ParamAreaSize)
2823     UseMemory = true;
2824 
2825   // However, if the argument is actually passed in an FPR or a VR,
2826   // we don't use memory after all.
2827   if (!Flags.isByVal()) {
2828     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2829         // QPX registers overlap with the scalar FP registers.
2830         (HasQPX && (ArgVT == MVT::v4f32 ||
2831                     ArgVT == MVT::v4f64 ||
2832                     ArgVT == MVT::v4i1)))
2833       if (AvailableFPRs > 0) {
2834         --AvailableFPRs;
2835         return false;
2836       }
2837     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2838         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2839         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2840         ArgVT == MVT::v1i128)
2841       if (AvailableVRs > 0) {
2842         --AvailableVRs;
2843         return false;
2844       }
2845   }
2846 
2847   return UseMemory;
2848 }
2849 
2850 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2851 /// ensure minimum alignment required for target.
2852 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2853                                      unsigned NumBytes) {
2854   unsigned TargetAlign = Lowering->getStackAlignment();
2855   unsigned AlignMask = TargetAlign - 1;
2856   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2857   return NumBytes;
2858 }
2859 
2860 SDValue PPCTargetLowering::LowerFormalArguments(
2861     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2862     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2863     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2864   if (Subtarget.isSVR4ABI()) {
2865     if (Subtarget.isPPC64())
2866       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2867                                          dl, DAG, InVals);
2868     else
2869       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2870                                          dl, DAG, InVals);
2871   } else {
2872     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2873                                        dl, DAG, InVals);
2874   }
2875 }
2876 
2877 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2878     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2879     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2880     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2881 
2882   // 32-bit SVR4 ABI Stack Frame Layout:
2883   //              +-----------------------------------+
2884   //        +-->  |            Back chain             |
2885   //        |     +-----------------------------------+
2886   //        |     | Floating-point register save area |
2887   //        |     +-----------------------------------+
2888   //        |     |    General register save area     |
2889   //        |     +-----------------------------------+
2890   //        |     |          CR save word             |
2891   //        |     +-----------------------------------+
2892   //        |     |         VRSAVE save word          |
2893   //        |     +-----------------------------------+
2894   //        |     |         Alignment padding         |
2895   //        |     +-----------------------------------+
2896   //        |     |     Vector register save area     |
2897   //        |     +-----------------------------------+
2898   //        |     |       Local variable space        |
2899   //        |     +-----------------------------------+
2900   //        |     |        Parameter list area        |
2901   //        |     +-----------------------------------+
2902   //        |     |           LR save word            |
2903   //        |     +-----------------------------------+
2904   // SP-->  +---  |            Back chain             |
2905   //              +-----------------------------------+
2906   //
2907   // Specifications:
2908   //   System V Application Binary Interface PowerPC Processor Supplement
2909   //   AltiVec Technology Programming Interface Manual
2910 
2911   MachineFunction &MF = DAG.getMachineFunction();
2912   MachineFrameInfo &MFI = MF.getFrameInfo();
2913   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2914 
2915   EVT PtrVT = getPointerTy(MF.getDataLayout());
2916   // Potential tail calls could cause overwriting of argument stack slots.
2917   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2918                        (CallConv == CallingConv::Fast));
2919   unsigned PtrByteSize = 4;
2920 
2921   // Assign locations to all of the incoming arguments.
2922   SmallVector<CCValAssign, 16> ArgLocs;
2923   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2924                  *DAG.getContext());
2925 
2926   // Reserve space for the linkage area on the stack.
2927   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2928   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2929   if (useSoftFloat())
2930     CCInfo.PreAnalyzeFormalArguments(Ins);
2931 
2932   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2933   CCInfo.clearWasPPCF128();
2934 
2935   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2936     CCValAssign &VA = ArgLocs[i];
2937 
2938     // Arguments stored in registers.
2939     if (VA.isRegLoc()) {
2940       const TargetRegisterClass *RC;
2941       EVT ValVT = VA.getValVT();
2942 
2943       switch (ValVT.getSimpleVT().SimpleTy) {
2944         default:
2945           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2946         case MVT::i1:
2947         case MVT::i32:
2948           RC = &PPC::GPRCRegClass;
2949           break;
2950         case MVT::f32:
2951           if (Subtarget.hasP8Vector())
2952             RC = &PPC::VSSRCRegClass;
2953           else
2954             RC = &PPC::F4RCRegClass;
2955           break;
2956         case MVT::f64:
2957           if (Subtarget.hasVSX())
2958             RC = &PPC::VSFRCRegClass;
2959           else
2960             RC = &PPC::F8RCRegClass;
2961           break;
2962         case MVT::v16i8:
2963         case MVT::v8i16:
2964         case MVT::v4i32:
2965           RC = &PPC::VRRCRegClass;
2966           break;
2967         case MVT::v4f32:
2968           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2969           break;
2970         case MVT::v2f64:
2971         case MVT::v2i64:
2972           RC = &PPC::VSHRCRegClass;
2973           break;
2974         case MVT::v4f64:
2975           RC = &PPC::QFRCRegClass;
2976           break;
2977         case MVT::v4i1:
2978           RC = &PPC::QBRCRegClass;
2979           break;
2980       }
2981 
2982       // Transform the arguments stored in physical registers into virtual ones.
2983       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2984       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2985                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2986 
2987       if (ValVT == MVT::i1)
2988         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2989 
2990       InVals.push_back(ArgValue);
2991     } else {
2992       // Argument stored in memory.
2993       assert(VA.isMemLoc());
2994 
2995       unsigned ArgSize = VA.getLocVT().getStoreSize();
2996       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2997                                      isImmutable);
2998 
2999       // Create load nodes to retrieve arguments from the stack.
3000       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3001       InVals.push_back(
3002           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3003     }
3004   }
3005 
3006   // Assign locations to all of the incoming aggregate by value arguments.
3007   // Aggregates passed by value are stored in the local variable space of the
3008   // caller's stack frame, right above the parameter list area.
3009   SmallVector<CCValAssign, 16> ByValArgLocs;
3010   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3011                       ByValArgLocs, *DAG.getContext());
3012 
3013   // Reserve stack space for the allocations in CCInfo.
3014   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3015 
3016   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3017 
3018   // Area that is at least reserved in the caller of this function.
3019   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3020   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3021 
3022   // Set the size that is at least reserved in caller of this function.  Tail
3023   // call optimized function's reserved stack space needs to be aligned so that
3024   // taking the difference between two stack areas will result in an aligned
3025   // stack.
3026   MinReservedArea =
3027       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3028   FuncInfo->setMinReservedArea(MinReservedArea);
3029 
3030   SmallVector<SDValue, 8> MemOps;
3031 
3032   // If the function takes variable number of arguments, make a frame index for
3033   // the start of the first vararg value... for expansion of llvm.va_start.
3034   if (isVarArg) {
3035     static const MCPhysReg GPArgRegs[] = {
3036       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3037       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3038     };
3039     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3040 
3041     static const MCPhysReg FPArgRegs[] = {
3042       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3043       PPC::F8
3044     };
3045     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3046 
3047     if (useSoftFloat())
3048        NumFPArgRegs = 0;
3049 
3050     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3051     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3052 
3053     // Make room for NumGPArgRegs and NumFPArgRegs.
3054     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3055                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3056 
3057     FuncInfo->setVarArgsStackOffset(
3058       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3059                             CCInfo.getNextStackOffset(), true));
3060 
3061     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3062     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3063 
3064     // The fixed integer arguments of a variadic function are stored to the
3065     // VarArgsFrameIndex on the stack so that they may be loaded by
3066     // dereferencing the result of va_next.
3067     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3068       // Get an existing live-in vreg, or add a new one.
3069       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3070       if (!VReg)
3071         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3072 
3073       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3074       SDValue Store =
3075           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3076       MemOps.push_back(Store);
3077       // Increment the address by four for the next argument to store
3078       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3079       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3080     }
3081 
3082     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3083     // is set.
3084     // The double arguments are stored to the VarArgsFrameIndex
3085     // on the stack.
3086     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3087       // Get an existing live-in vreg, or add a new one.
3088       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3089       if (!VReg)
3090         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3091 
3092       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3093       SDValue Store =
3094           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3095       MemOps.push_back(Store);
3096       // Increment the address by eight for the next argument to store
3097       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3098                                          PtrVT);
3099       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3100     }
3101   }
3102 
3103   if (!MemOps.empty())
3104     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3105 
3106   return Chain;
3107 }
3108 
3109 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3110 // value to MVT::i64 and then truncate to the correct register size.
3111 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3112                                              EVT ObjectVT, SelectionDAG &DAG,
3113                                              SDValue ArgVal,
3114                                              const SDLoc &dl) const {
3115   if (Flags.isSExt())
3116     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3117                          DAG.getValueType(ObjectVT));
3118   else if (Flags.isZExt())
3119     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3120                          DAG.getValueType(ObjectVT));
3121 
3122   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3123 }
3124 
3125 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3126     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3127     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3128     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3129   // TODO: add description of PPC stack frame format, or at least some docs.
3130   //
3131   bool isELFv2ABI = Subtarget.isELFv2ABI();
3132   bool isLittleEndian = Subtarget.isLittleEndian();
3133   MachineFunction &MF = DAG.getMachineFunction();
3134   MachineFrameInfo &MFI = MF.getFrameInfo();
3135   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3136 
3137   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3138          "fastcc not supported on varargs functions");
3139 
3140   EVT PtrVT = getPointerTy(MF.getDataLayout());
3141   // Potential tail calls could cause overwriting of argument stack slots.
3142   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3143                        (CallConv == CallingConv::Fast));
3144   unsigned PtrByteSize = 8;
3145   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3146 
3147   static const MCPhysReg GPR[] = {
3148     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3149     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3150   };
3151   static const MCPhysReg VR[] = {
3152     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3153     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3154   };
3155   static const MCPhysReg VSRH[] = {
3156     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3157     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3158   };
3159 
3160   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3161   const unsigned Num_FPR_Regs = 13;
3162   const unsigned Num_VR_Regs  = array_lengthof(VR);
3163   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3164 
3165   // Do a first pass over the arguments to determine whether the ABI
3166   // guarantees that our caller has allocated the parameter save area
3167   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3168   // in the ELFv2 ABI, it is true if this is a vararg function or if
3169   // any parameter is located in a stack slot.
3170 
3171   bool HasParameterArea = !isELFv2ABI || isVarArg;
3172   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3173   unsigned NumBytes = LinkageSize;
3174   unsigned AvailableFPRs = Num_FPR_Regs;
3175   unsigned AvailableVRs = Num_VR_Regs;
3176   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3177     if (Ins[i].Flags.isNest())
3178       continue;
3179 
3180     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3181                                PtrByteSize, LinkageSize, ParamAreaSize,
3182                                NumBytes, AvailableFPRs, AvailableVRs,
3183                                Subtarget.hasQPX()))
3184       HasParameterArea = true;
3185   }
3186 
3187   // Add DAG nodes to load the arguments or copy them out of registers.  On
3188   // entry to a function on PPC, the arguments start after the linkage area,
3189   // although the first ones are often in registers.
3190 
3191   unsigned ArgOffset = LinkageSize;
3192   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3193   unsigned &QFPR_idx = FPR_idx;
3194   SmallVector<SDValue, 8> MemOps;
3195   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3196   unsigned CurArgIdx = 0;
3197   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3198     SDValue ArgVal;
3199     bool needsLoad = false;
3200     EVT ObjectVT = Ins[ArgNo].VT;
3201     EVT OrigVT = Ins[ArgNo].ArgVT;
3202     unsigned ObjSize = ObjectVT.getStoreSize();
3203     unsigned ArgSize = ObjSize;
3204     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3205     if (Ins[ArgNo].isOrigArg()) {
3206       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3207       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3208     }
3209     // We re-align the argument offset for each argument, except when using the
3210     // fast calling convention, when we need to make sure we do that only when
3211     // we'll actually use a stack slot.
3212     unsigned CurArgOffset, Align;
3213     auto ComputeArgOffset = [&]() {
3214       /* Respect alignment of argument on the stack.  */
3215       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3216       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3217       CurArgOffset = ArgOffset;
3218     };
3219 
3220     if (CallConv != CallingConv::Fast) {
3221       ComputeArgOffset();
3222 
3223       /* Compute GPR index associated with argument offset.  */
3224       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3225       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3226     }
3227 
3228     // FIXME the codegen can be much improved in some cases.
3229     // We do not have to keep everything in memory.
3230     if (Flags.isByVal()) {
3231       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3232 
3233       if (CallConv == CallingConv::Fast)
3234         ComputeArgOffset();
3235 
3236       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3237       ObjSize = Flags.getByValSize();
3238       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3239       // Empty aggregate parameters do not take up registers.  Examples:
3240       //   struct { } a;
3241       //   union  { } b;
3242       //   int c[0];
3243       // etc.  However, we have to provide a place-holder in InVals, so
3244       // pretend we have an 8-byte item at the current address for that
3245       // purpose.
3246       if (!ObjSize) {
3247         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3248         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3249         InVals.push_back(FIN);
3250         continue;
3251       }
3252 
3253       // Create a stack object covering all stack doublewords occupied
3254       // by the argument.  If the argument is (fully or partially) on
3255       // the stack, or if the argument is fully in registers but the
3256       // caller has allocated the parameter save anyway, we can refer
3257       // directly to the caller's stack frame.  Otherwise, create a
3258       // local copy in our own frame.
3259       int FI;
3260       if (HasParameterArea ||
3261           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3262         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3263       else
3264         FI = MFI.CreateStackObject(ArgSize, Align, false);
3265       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3266 
3267       // Handle aggregates smaller than 8 bytes.
3268       if (ObjSize < PtrByteSize) {
3269         // The value of the object is its address, which differs from the
3270         // address of the enclosing doubleword on big-endian systems.
3271         SDValue Arg = FIN;
3272         if (!isLittleEndian) {
3273           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3274           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3275         }
3276         InVals.push_back(Arg);
3277 
3278         if (GPR_idx != Num_GPR_Regs) {
3279           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3280           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3281           SDValue Store;
3282 
3283           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3284             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3285                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3286             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3287                                       MachinePointerInfo(&*FuncArg), ObjType);
3288           } else {
3289             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3290             // store the whole register as-is to the parameter save area
3291             // slot.
3292             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3293                                  MachinePointerInfo(&*FuncArg));
3294           }
3295 
3296           MemOps.push_back(Store);
3297         }
3298         // Whether we copied from a register or not, advance the offset
3299         // into the parameter save area by a full doubleword.
3300         ArgOffset += PtrByteSize;
3301         continue;
3302       }
3303 
3304       // The value of the object is its address, which is the address of
3305       // its first stack doubleword.
3306       InVals.push_back(FIN);
3307 
3308       // Store whatever pieces of the object are in registers to memory.
3309       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3310         if (GPR_idx == Num_GPR_Regs)
3311           break;
3312 
3313         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3314         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3315         SDValue Addr = FIN;
3316         if (j) {
3317           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3318           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3319         }
3320         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3321                                      MachinePointerInfo(&*FuncArg, j));
3322         MemOps.push_back(Store);
3323         ++GPR_idx;
3324       }
3325       ArgOffset += ArgSize;
3326       continue;
3327     }
3328 
3329     switch (ObjectVT.getSimpleVT().SimpleTy) {
3330     default: llvm_unreachable("Unhandled argument type!");
3331     case MVT::i1:
3332     case MVT::i32:
3333     case MVT::i64:
3334       if (Flags.isNest()) {
3335         // The 'nest' parameter, if any, is passed in R11.
3336         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3337         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3338 
3339         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3340           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3341 
3342         break;
3343       }
3344 
3345       // These can be scalar arguments or elements of an integer array type
3346       // passed directly.  Clang may use those instead of "byval" aggregate
3347       // types to avoid forcing arguments to memory unnecessarily.
3348       if (GPR_idx != Num_GPR_Regs) {
3349         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3350         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3351 
3352         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3353           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3354           // value to MVT::i64 and then truncate to the correct register size.
3355           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3356       } else {
3357         if (CallConv == CallingConv::Fast)
3358           ComputeArgOffset();
3359 
3360         needsLoad = true;
3361         ArgSize = PtrByteSize;
3362       }
3363       if (CallConv != CallingConv::Fast || needsLoad)
3364         ArgOffset += 8;
3365       break;
3366 
3367     case MVT::f32:
3368     case MVT::f64:
3369       // These can be scalar arguments or elements of a float array type
3370       // passed directly.  The latter are used to implement ELFv2 homogenous
3371       // float aggregates.
3372       if (FPR_idx != Num_FPR_Regs) {
3373         unsigned VReg;
3374 
3375         if (ObjectVT == MVT::f32)
3376           VReg = MF.addLiveIn(FPR[FPR_idx],
3377                               Subtarget.hasP8Vector()
3378                                   ? &PPC::VSSRCRegClass
3379                                   : &PPC::F4RCRegClass);
3380         else
3381           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3382                                                 ? &PPC::VSFRCRegClass
3383                                                 : &PPC::F8RCRegClass);
3384 
3385         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3386         ++FPR_idx;
3387       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3388         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3389         // once we support fp <-> gpr moves.
3390 
3391         // This can only ever happen in the presence of f32 array types,
3392         // since otherwise we never run out of FPRs before running out
3393         // of GPRs.
3394         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3395         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3396 
3397         if (ObjectVT == MVT::f32) {
3398           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3399             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3400                                  DAG.getConstant(32, dl, MVT::i32));
3401           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3402         }
3403 
3404         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3405       } else {
3406         if (CallConv == CallingConv::Fast)
3407           ComputeArgOffset();
3408 
3409         needsLoad = true;
3410       }
3411 
3412       // When passing an array of floats, the array occupies consecutive
3413       // space in the argument area; only round up to the next doubleword
3414       // at the end of the array.  Otherwise, each float takes 8 bytes.
3415       if (CallConv != CallingConv::Fast || needsLoad) {
3416         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3417         ArgOffset += ArgSize;
3418         if (Flags.isInConsecutiveRegsLast())
3419           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3420       }
3421       break;
3422     case MVT::v4f32:
3423     case MVT::v4i32:
3424     case MVT::v8i16:
3425     case MVT::v16i8:
3426     case MVT::v2f64:
3427     case MVT::v2i64:
3428     case MVT::v1i128:
3429       if (!Subtarget.hasQPX()) {
3430       // These can be scalar arguments or elements of a vector array type
3431       // passed directly.  The latter are used to implement ELFv2 homogenous
3432       // vector aggregates.
3433       if (VR_idx != Num_VR_Regs) {
3434         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3435                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3436                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3437         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3438         ++VR_idx;
3439       } else {
3440         if (CallConv == CallingConv::Fast)
3441           ComputeArgOffset();
3442 
3443         needsLoad = true;
3444       }
3445       if (CallConv != CallingConv::Fast || needsLoad)
3446         ArgOffset += 16;
3447       break;
3448       } // not QPX
3449 
3450       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3451              "Invalid QPX parameter type");
3452       /* fall through */
3453 
3454     case MVT::v4f64:
3455     case MVT::v4i1:
3456       // QPX vectors are treated like their scalar floating-point subregisters
3457       // (except that they're larger).
3458       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3459       if (QFPR_idx != Num_QFPR_Regs) {
3460         const TargetRegisterClass *RC;
3461         switch (ObjectVT.getSimpleVT().SimpleTy) {
3462         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3463         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3464         default:         RC = &PPC::QBRCRegClass; break;
3465         }
3466 
3467         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3468         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3469         ++QFPR_idx;
3470       } else {
3471         if (CallConv == CallingConv::Fast)
3472           ComputeArgOffset();
3473         needsLoad = true;
3474       }
3475       if (CallConv != CallingConv::Fast || needsLoad)
3476         ArgOffset += Sz;
3477       break;
3478     }
3479 
3480     // We need to load the argument to a virtual register if we determined
3481     // above that we ran out of physical registers of the appropriate type.
3482     if (needsLoad) {
3483       if (ObjSize < ArgSize && !isLittleEndian)
3484         CurArgOffset += ArgSize - ObjSize;
3485       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3486       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3487       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3488     }
3489 
3490     InVals.push_back(ArgVal);
3491   }
3492 
3493   // Area that is at least reserved in the caller of this function.
3494   unsigned MinReservedArea;
3495   if (HasParameterArea)
3496     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3497   else
3498     MinReservedArea = LinkageSize;
3499 
3500   // Set the size that is at least reserved in caller of this function.  Tail
3501   // call optimized functions' reserved stack space needs to be aligned so that
3502   // taking the difference between two stack areas will result in an aligned
3503   // stack.
3504   MinReservedArea =
3505       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3506   FuncInfo->setMinReservedArea(MinReservedArea);
3507 
3508   // If the function takes variable number of arguments, make a frame index for
3509   // the start of the first vararg value... for expansion of llvm.va_start.
3510   if (isVarArg) {
3511     int Depth = ArgOffset;
3512 
3513     FuncInfo->setVarArgsFrameIndex(
3514       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3515     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3516 
3517     // If this function is vararg, store any remaining integer argument regs
3518     // to their spots on the stack so that they may be loaded by dereferencing
3519     // the result of va_next.
3520     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3521          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3522       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3523       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3524       SDValue Store =
3525           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3526       MemOps.push_back(Store);
3527       // Increment the address by four for the next argument to store
3528       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3529       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3530     }
3531   }
3532 
3533   if (!MemOps.empty())
3534     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3535 
3536   return Chain;
3537 }
3538 
3539 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3540     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3541     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3542     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3543   // TODO: add description of PPC stack frame format, or at least some docs.
3544   //
3545   MachineFunction &MF = DAG.getMachineFunction();
3546   MachineFrameInfo &MFI = MF.getFrameInfo();
3547   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3548 
3549   EVT PtrVT = getPointerTy(MF.getDataLayout());
3550   bool isPPC64 = PtrVT == MVT::i64;
3551   // Potential tail calls could cause overwriting of argument stack slots.
3552   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3553                        (CallConv == CallingConv::Fast));
3554   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3555   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3556   unsigned ArgOffset = LinkageSize;
3557   // Area that is at least reserved in caller of this function.
3558   unsigned MinReservedArea = ArgOffset;
3559 
3560   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3561     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3562     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3563   };
3564   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3565     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3566     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3567   };
3568   static const MCPhysReg VR[] = {
3569     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3570     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3571   };
3572 
3573   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3574   const unsigned Num_FPR_Regs = 13;
3575   const unsigned Num_VR_Regs  = array_lengthof( VR);
3576 
3577   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3578 
3579   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3580 
3581   // In 32-bit non-varargs functions, the stack space for vectors is after the
3582   // stack space for non-vectors.  We do not use this space unless we have
3583   // too many vectors to fit in registers, something that only occurs in
3584   // constructed examples:), but we have to walk the arglist to figure
3585   // that out...for the pathological case, compute VecArgOffset as the
3586   // start of the vector parameter area.  Computing VecArgOffset is the
3587   // entire point of the following loop.
3588   unsigned VecArgOffset = ArgOffset;
3589   if (!isVarArg && !isPPC64) {
3590     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3591          ++ArgNo) {
3592       EVT ObjectVT = Ins[ArgNo].VT;
3593       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3594 
3595       if (Flags.isByVal()) {
3596         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3597         unsigned ObjSize = Flags.getByValSize();
3598         unsigned ArgSize =
3599                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3600         VecArgOffset += ArgSize;
3601         continue;
3602       }
3603 
3604       switch(ObjectVT.getSimpleVT().SimpleTy) {
3605       default: llvm_unreachable("Unhandled argument type!");
3606       case MVT::i1:
3607       case MVT::i32:
3608       case MVT::f32:
3609         VecArgOffset += 4;
3610         break;
3611       case MVT::i64:  // PPC64
3612       case MVT::f64:
3613         // FIXME: We are guaranteed to be !isPPC64 at this point.
3614         // Does MVT::i64 apply?
3615         VecArgOffset += 8;
3616         break;
3617       case MVT::v4f32:
3618       case MVT::v4i32:
3619       case MVT::v8i16:
3620       case MVT::v16i8:
3621         // Nothing to do, we're only looking at Nonvector args here.
3622         break;
3623       }
3624     }
3625   }
3626   // We've found where the vector parameter area in memory is.  Skip the
3627   // first 12 parameters; these don't use that memory.
3628   VecArgOffset = ((VecArgOffset+15)/16)*16;
3629   VecArgOffset += 12*16;
3630 
3631   // Add DAG nodes to load the arguments or copy them out of registers.  On
3632   // entry to a function on PPC, the arguments start after the linkage area,
3633   // although the first ones are often in registers.
3634 
3635   SmallVector<SDValue, 8> MemOps;
3636   unsigned nAltivecParamsAtEnd = 0;
3637   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3638   unsigned CurArgIdx = 0;
3639   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3640     SDValue ArgVal;
3641     bool needsLoad = false;
3642     EVT ObjectVT = Ins[ArgNo].VT;
3643     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3644     unsigned ArgSize = ObjSize;
3645     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3646     if (Ins[ArgNo].isOrigArg()) {
3647       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3648       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3649     }
3650     unsigned CurArgOffset = ArgOffset;
3651 
3652     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3653     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3654         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3655       if (isVarArg || isPPC64) {
3656         MinReservedArea = ((MinReservedArea+15)/16)*16;
3657         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3658                                                   Flags,
3659                                                   PtrByteSize);
3660       } else  nAltivecParamsAtEnd++;
3661     } else
3662       // Calculate min reserved area.
3663       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3664                                                 Flags,
3665                                                 PtrByteSize);
3666 
3667     // FIXME the codegen can be much improved in some cases.
3668     // We do not have to keep everything in memory.
3669     if (Flags.isByVal()) {
3670       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3671 
3672       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3673       ObjSize = Flags.getByValSize();
3674       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3675       // Objects of size 1 and 2 are right justified, everything else is
3676       // left justified.  This means the memory address is adjusted forwards.
3677       if (ObjSize==1 || ObjSize==2) {
3678         CurArgOffset = CurArgOffset + (4 - ObjSize);
3679       }
3680       // The value of the object is its address.
3681       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3682       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3683       InVals.push_back(FIN);
3684       if (ObjSize==1 || ObjSize==2) {
3685         if (GPR_idx != Num_GPR_Regs) {
3686           unsigned VReg;
3687           if (isPPC64)
3688             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3689           else
3690             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3691           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3692           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3693           SDValue Store =
3694               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3695                                 MachinePointerInfo(&*FuncArg), ObjType);
3696           MemOps.push_back(Store);
3697           ++GPR_idx;
3698         }
3699 
3700         ArgOffset += PtrByteSize;
3701 
3702         continue;
3703       }
3704       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3705         // Store whatever pieces of the object are in registers
3706         // to memory.  ArgOffset will be the address of the beginning
3707         // of the object.
3708         if (GPR_idx != Num_GPR_Regs) {
3709           unsigned VReg;
3710           if (isPPC64)
3711             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3712           else
3713             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3714           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3715           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3716           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3717           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3718                                        MachinePointerInfo(&*FuncArg, j));
3719           MemOps.push_back(Store);
3720           ++GPR_idx;
3721           ArgOffset += PtrByteSize;
3722         } else {
3723           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3724           break;
3725         }
3726       }
3727       continue;
3728     }
3729 
3730     switch (ObjectVT.getSimpleVT().SimpleTy) {
3731     default: llvm_unreachable("Unhandled argument type!");
3732     case MVT::i1:
3733     case MVT::i32:
3734       if (!isPPC64) {
3735         if (GPR_idx != Num_GPR_Regs) {
3736           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3737           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3738 
3739           if (ObjectVT == MVT::i1)
3740             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3741 
3742           ++GPR_idx;
3743         } else {
3744           needsLoad = true;
3745           ArgSize = PtrByteSize;
3746         }
3747         // All int arguments reserve stack space in the Darwin ABI.
3748         ArgOffset += PtrByteSize;
3749         break;
3750       }
3751       LLVM_FALLTHROUGH;
3752     case MVT::i64:  // PPC64
3753       if (GPR_idx != Num_GPR_Regs) {
3754         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3755         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3756 
3757         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3758           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3759           // value to MVT::i64 and then truncate to the correct register size.
3760           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3761 
3762         ++GPR_idx;
3763       } else {
3764         needsLoad = true;
3765         ArgSize = PtrByteSize;
3766       }
3767       // All int arguments reserve stack space in the Darwin ABI.
3768       ArgOffset += 8;
3769       break;
3770 
3771     case MVT::f32:
3772     case MVT::f64:
3773       // Every 4 bytes of argument space consumes one of the GPRs available for
3774       // argument passing.
3775       if (GPR_idx != Num_GPR_Regs) {
3776         ++GPR_idx;
3777         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3778           ++GPR_idx;
3779       }
3780       if (FPR_idx != Num_FPR_Regs) {
3781         unsigned VReg;
3782 
3783         if (ObjectVT == MVT::f32)
3784           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3785         else
3786           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3787 
3788         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3789         ++FPR_idx;
3790       } else {
3791         needsLoad = true;
3792       }
3793 
3794       // All FP arguments reserve stack space in the Darwin ABI.
3795       ArgOffset += isPPC64 ? 8 : ObjSize;
3796       break;
3797     case MVT::v4f32:
3798     case MVT::v4i32:
3799     case MVT::v8i16:
3800     case MVT::v16i8:
3801       // Note that vector arguments in registers don't reserve stack space,
3802       // except in varargs functions.
3803       if (VR_idx != Num_VR_Regs) {
3804         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3805         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3806         if (isVarArg) {
3807           while ((ArgOffset % 16) != 0) {
3808             ArgOffset += PtrByteSize;
3809             if (GPR_idx != Num_GPR_Regs)
3810               GPR_idx++;
3811           }
3812           ArgOffset += 16;
3813           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3814         }
3815         ++VR_idx;
3816       } else {
3817         if (!isVarArg && !isPPC64) {
3818           // Vectors go after all the nonvectors.
3819           CurArgOffset = VecArgOffset;
3820           VecArgOffset += 16;
3821         } else {
3822           // Vectors are aligned.
3823           ArgOffset = ((ArgOffset+15)/16)*16;
3824           CurArgOffset = ArgOffset;
3825           ArgOffset += 16;
3826         }
3827         needsLoad = true;
3828       }
3829       break;
3830     }
3831 
3832     // We need to load the argument to a virtual register if we determined above
3833     // that we ran out of physical registers of the appropriate type.
3834     if (needsLoad) {
3835       int FI = MFI.CreateFixedObject(ObjSize,
3836                                      CurArgOffset + (ArgSize - ObjSize),
3837                                      isImmutable);
3838       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3839       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3840     }
3841 
3842     InVals.push_back(ArgVal);
3843   }
3844 
3845   // Allow for Altivec parameters at the end, if needed.
3846   if (nAltivecParamsAtEnd) {
3847     MinReservedArea = ((MinReservedArea+15)/16)*16;
3848     MinReservedArea += 16*nAltivecParamsAtEnd;
3849   }
3850 
3851   // Area that is at least reserved in the caller of this function.
3852   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3853 
3854   // Set the size that is at least reserved in caller of this function.  Tail
3855   // call optimized functions' reserved stack space needs to be aligned so that
3856   // taking the difference between two stack areas will result in an aligned
3857   // stack.
3858   MinReservedArea =
3859       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3860   FuncInfo->setMinReservedArea(MinReservedArea);
3861 
3862   // If the function takes variable number of arguments, make a frame index for
3863   // the start of the first vararg value... for expansion of llvm.va_start.
3864   if (isVarArg) {
3865     int Depth = ArgOffset;
3866 
3867     FuncInfo->setVarArgsFrameIndex(
3868       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3869                             Depth, true));
3870     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3871 
3872     // If this function is vararg, store any remaining integer argument regs
3873     // to their spots on the stack so that they may be loaded by dereferencing
3874     // the result of va_next.
3875     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3876       unsigned VReg;
3877 
3878       if (isPPC64)
3879         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3880       else
3881         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3882 
3883       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3884       SDValue Store =
3885           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3886       MemOps.push_back(Store);
3887       // Increment the address by four for the next argument to store
3888       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3889       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3890     }
3891   }
3892 
3893   if (!MemOps.empty())
3894     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3895 
3896   return Chain;
3897 }
3898 
3899 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3900 /// adjusted to accommodate the arguments for the tailcall.
3901 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3902                                    unsigned ParamSize) {
3903 
3904   if (!isTailCall) return 0;
3905 
3906   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3907   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3908   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3909   // Remember only if the new adjustement is bigger.
3910   if (SPDiff < FI->getTailCallSPDelta())
3911     FI->setTailCallSPDelta(SPDiff);
3912 
3913   return SPDiff;
3914 }
3915 
3916 static bool isFunctionGlobalAddress(SDValue Callee);
3917 
3918 static bool
3919 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3920   // If !G, Callee can be an external symbol.
3921   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3922   if (!G) return false;
3923 
3924   const GlobalValue *GV = G->getGlobal();
3925 
3926   if (GV->isDeclaration()) return false;
3927 
3928   switch(GV->getLinkage()) {
3929   default: llvm_unreachable("unknow linkage type");
3930   case GlobalValue::AvailableExternallyLinkage:
3931   case GlobalValue::ExternalWeakLinkage:
3932     return false;
3933 
3934   // Callee with weak linkage is allowed if it has hidden or protected
3935   // visibility
3936   case GlobalValue::LinkOnceAnyLinkage:
3937   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3938   case GlobalValue::WeakAnyLinkage:
3939   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3940     if (GV->hasDefaultVisibility())
3941       return false;
3942 
3943   case GlobalValue::ExternalLinkage:
3944   case GlobalValue::InternalLinkage:
3945   case GlobalValue::PrivateLinkage:
3946     break;
3947   }
3948 
3949   // With '-fPIC', calling default visiblity function need insert 'nop' after
3950   // function call, no matter that function resides in same module or not, so
3951   // we treat it as in different module.
3952   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3953     return false;
3954 
3955   return true;
3956 }
3957 
3958 static bool
3959 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3960                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3961   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3962 
3963   const unsigned PtrByteSize = 8;
3964   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3965 
3966   static const MCPhysReg GPR[] = {
3967     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3968     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3969   };
3970   static const MCPhysReg VR[] = {
3971     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3972     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3973   };
3974 
3975   const unsigned NumGPRs = array_lengthof(GPR);
3976   const unsigned NumFPRs = 13;
3977   const unsigned NumVRs = array_lengthof(VR);
3978   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3979 
3980   unsigned NumBytes = LinkageSize;
3981   unsigned AvailableFPRs = NumFPRs;
3982   unsigned AvailableVRs = NumVRs;
3983 
3984   for (const ISD::OutputArg& Param : Outs) {
3985     if (Param.Flags.isNest()) continue;
3986 
3987     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3988                                PtrByteSize, LinkageSize, ParamAreaSize,
3989                                NumBytes, AvailableFPRs, AvailableVRs,
3990                                Subtarget.hasQPX()))
3991       return true;
3992   }
3993   return false;
3994 }
3995 
3996 static bool
3997 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
3998   if (CS->arg_size() != CallerFn->getArgumentList().size())
3999     return false;
4000 
4001   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4002   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4003   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4004 
4005   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4006     const Value* CalleeArg = *CalleeArgIter;
4007     const Value* CallerArg = &(*CallerArgIter);
4008     if (CalleeArg == CallerArg)
4009       continue;
4010 
4011     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4012     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4013     //      }
4014     // 1st argument of callee is undef and has the same type as caller.
4015     if (CalleeArg->getType() == CallerArg->getType() &&
4016         isa<UndefValue>(CalleeArg))
4017       continue;
4018 
4019     return false;
4020   }
4021 
4022   return true;
4023 }
4024 
4025 bool
4026 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4027                                     SDValue Callee,
4028                                     CallingConv::ID CalleeCC,
4029                                     ImmutableCallSite *CS,
4030                                     bool isVarArg,
4031                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4032                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4033                                     SelectionDAG& DAG) const {
4034   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4035 
4036   if (DisableSCO && !TailCallOpt) return false;
4037 
4038   // Variadic argument functions are not supported.
4039   if (isVarArg) return false;
4040 
4041   MachineFunction &MF = DAG.getMachineFunction();
4042   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4043 
4044   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4045   // the same calling convention
4046   if (CallerCC != CalleeCC) return false;
4047 
4048   // SCO support C calling convention
4049   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4050     return false;
4051 
4052   // Caller contains any byval parameter is not supported.
4053   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4054     return false;
4055 
4056   // Callee contains any byval parameter is not supported, too.
4057   // Note: This is a quick work around, because in some cases, e.g.
4058   // caller's stack size > callee's stack size, we are still able to apply
4059   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4060   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4061     return false;
4062 
4063   // No TCO/SCO on indirect call because Caller have to restore its TOC
4064   if (!isFunctionGlobalAddress(Callee) &&
4065       !isa<ExternalSymbolSDNode>(Callee))
4066     return false;
4067 
4068   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4069   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4070   // module.
4071   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4072   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4073     return false;
4074 
4075   // TCO allows altering callee ABI, so we don't have to check further.
4076   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4077     return true;
4078 
4079   if (DisableSCO) return false;
4080 
4081   // If callee use the same argument list that caller is using, then we can
4082   // apply SCO on this case. If it is not, then we need to check if callee needs
4083   // stack for passing arguments.
4084   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4085       needStackSlotPassParameters(Subtarget, Outs)) {
4086     return false;
4087   }
4088 
4089   return true;
4090 }
4091 
4092 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4093 /// for tail call optimization. Targets which want to do tail call
4094 /// optimization should implement this function.
4095 bool
4096 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4097                                                      CallingConv::ID CalleeCC,
4098                                                      bool isVarArg,
4099                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4100                                                      SelectionDAG& DAG) const {
4101   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4102     return false;
4103 
4104   // Variable argument functions are not supported.
4105   if (isVarArg)
4106     return false;
4107 
4108   MachineFunction &MF = DAG.getMachineFunction();
4109   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4110   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4111     // Functions containing by val parameters are not supported.
4112     for (unsigned i = 0; i != Ins.size(); i++) {
4113        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4114        if (Flags.isByVal()) return false;
4115     }
4116 
4117     // Non-PIC/GOT tail calls are supported.
4118     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4119       return true;
4120 
4121     // At the moment we can only do local tail calls (in same module, hidden
4122     // or protected) if we are generating PIC.
4123     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4124       return G->getGlobal()->hasHiddenVisibility()
4125           || G->getGlobal()->hasProtectedVisibility();
4126   }
4127 
4128   return false;
4129 }
4130 
4131 /// isCallCompatibleAddress - Return the immediate to use if the specified
4132 /// 32-bit value is representable in the immediate field of a BxA instruction.
4133 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4135   if (!C) return nullptr;
4136 
4137   int Addr = C->getZExtValue();
4138   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4139       SignExtend32<26>(Addr) != Addr)
4140     return nullptr;  // Top 6 bits have to be sext of immediate.
4141 
4142   return DAG
4143       .getConstant(
4144           (int)C->getZExtValue() >> 2, SDLoc(Op),
4145           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4146       .getNode();
4147 }
4148 
4149 namespace {
4150 
4151 struct TailCallArgumentInfo {
4152   SDValue Arg;
4153   SDValue FrameIdxOp;
4154   int       FrameIdx;
4155 
4156   TailCallArgumentInfo() : FrameIdx(0) {}
4157 };
4158 }
4159 
4160 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4161 static void StoreTailCallArgumentsToStackSlot(
4162     SelectionDAG &DAG, SDValue Chain,
4163     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4164     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4165   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4166     SDValue Arg = TailCallArgs[i].Arg;
4167     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4168     int FI = TailCallArgs[i].FrameIdx;
4169     // Store relative to framepointer.
4170     MemOpChains.push_back(DAG.getStore(
4171         Chain, dl, Arg, FIN,
4172         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4173   }
4174 }
4175 
4176 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4177 /// the appropriate stack slot for the tail call optimized function call.
4178 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4179                                              SDValue OldRetAddr, SDValue OldFP,
4180                                              int SPDiff, const SDLoc &dl) {
4181   if (SPDiff) {
4182     // Calculate the new stack slot for the return address.
4183     MachineFunction &MF = DAG.getMachineFunction();
4184     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4185     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4186     bool isPPC64 = Subtarget.isPPC64();
4187     int SlotSize = isPPC64 ? 8 : 4;
4188     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4189     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4190                                                          NewRetAddrLoc, true);
4191     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4192     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4193     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4194                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4195 
4196     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4197     // slot as the FP is never overwritten.
4198     if (Subtarget.isDarwinABI()) {
4199       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4200       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4201                                                          true);
4202       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4203       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4204                            MachinePointerInfo::getFixedStack(
4205                                DAG.getMachineFunction(), NewFPIdx));
4206     }
4207   }
4208   return Chain;
4209 }
4210 
4211 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4212 /// the position of the argument.
4213 static void
4214 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4215                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4216                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4217   int Offset = ArgOffset + SPDiff;
4218   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4219   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4220   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4221   SDValue FIN = DAG.getFrameIndex(FI, VT);
4222   TailCallArgumentInfo Info;
4223   Info.Arg = Arg;
4224   Info.FrameIdxOp = FIN;
4225   Info.FrameIdx = FI;
4226   TailCallArguments.push_back(Info);
4227 }
4228 
4229 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4230 /// stack slot. Returns the chain as result and the loaded frame pointers in
4231 /// LROpOut/FPOpout. Used when tail calling.
4232 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4233     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4234     SDValue &FPOpOut, const SDLoc &dl) const {
4235   if (SPDiff) {
4236     // Load the LR and FP stack slot for later adjusting.
4237     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4238     LROpOut = getReturnAddrFrameIndex(DAG);
4239     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4240     Chain = SDValue(LROpOut.getNode(), 1);
4241 
4242     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4243     // slot as the FP is never overwritten.
4244     if (Subtarget.isDarwinABI()) {
4245       FPOpOut = getFramePointerFrameIndex(DAG);
4246       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4247       Chain = SDValue(FPOpOut.getNode(), 1);
4248     }
4249   }
4250   return Chain;
4251 }
4252 
4253 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4254 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4255 /// specified by the specific parameter attribute. The copy will be passed as
4256 /// a byval function parameter.
4257 /// Sometimes what we are copying is the end of a larger object, the part that
4258 /// does not fit in registers.
4259 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4260                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4261                                          SelectionDAG &DAG, const SDLoc &dl) {
4262   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4263   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4264                        false, false, false, MachinePointerInfo(),
4265                        MachinePointerInfo());
4266 }
4267 
4268 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4269 /// tail calls.
4270 static void LowerMemOpCallTo(
4271     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4272     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4273     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4274     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4275   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4276   if (!isTailCall) {
4277     if (isVector) {
4278       SDValue StackPtr;
4279       if (isPPC64)
4280         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4281       else
4282         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4283       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4284                            DAG.getConstant(ArgOffset, dl, PtrVT));
4285     }
4286     MemOpChains.push_back(
4287         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4288     // Calculate and remember argument location.
4289   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4290                                   TailCallArguments);
4291 }
4292 
4293 static void
4294 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4295                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4296                 SDValue FPOp,
4297                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4298   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4299   // might overwrite each other in case of tail call optimization.
4300   SmallVector<SDValue, 8> MemOpChains2;
4301   // Do not flag preceding copytoreg stuff together with the following stuff.
4302   InFlag = SDValue();
4303   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4304                                     MemOpChains2, dl);
4305   if (!MemOpChains2.empty())
4306     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4307 
4308   // Store the return address to the appropriate stack slot.
4309   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4310 
4311   // Emit callseq_end just before tailcall node.
4312   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4313                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4314   InFlag = Chain.getValue(1);
4315 }
4316 
4317 // Is this global address that of a function that can be called by name? (as
4318 // opposed to something that must hold a descriptor for an indirect call).
4319 static bool isFunctionGlobalAddress(SDValue Callee) {
4320   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4321     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4322         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4323       return false;
4324 
4325     return G->getGlobal()->getValueType()->isFunctionTy();
4326   }
4327 
4328   return false;
4329 }
4330 
4331 static unsigned
4332 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4333             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4334             bool isPatchPoint, bool hasNest,
4335             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4336             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4337             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4338 
4339   bool isPPC64 = Subtarget.isPPC64();
4340   bool isSVR4ABI = Subtarget.isSVR4ABI();
4341   bool isELFv2ABI = Subtarget.isELFv2ABI();
4342 
4343   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4344   NodeTys.push_back(MVT::Other);   // Returns a chain
4345   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4346 
4347   unsigned CallOpc = PPCISD::CALL;
4348 
4349   bool needIndirectCall = true;
4350   if (!isSVR4ABI || !isPPC64)
4351     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4352       // If this is an absolute destination address, use the munged value.
4353       Callee = SDValue(Dest, 0);
4354       needIndirectCall = false;
4355     }
4356 
4357   // PC-relative references to external symbols should go through $stub, unless
4358   // we're building with the leopard linker or later, which automatically
4359   // synthesizes these stubs.
4360   const TargetMachine &TM = DAG.getTarget();
4361   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4362   const GlobalValue *GV = nullptr;
4363   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4364     GV = G->getGlobal();
4365   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4366   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4367 
4368   if (isFunctionGlobalAddress(Callee)) {
4369     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4370     // A call to a TLS address is actually an indirect call to a
4371     // thread-specific pointer.
4372     unsigned OpFlags = 0;
4373     if (UsePlt)
4374       OpFlags = PPCII::MO_PLT;
4375 
4376     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4377     // every direct call is) turn it into a TargetGlobalAddress /
4378     // TargetExternalSymbol node so that legalize doesn't hack it.
4379     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4380                                         Callee.getValueType(), 0, OpFlags);
4381     needIndirectCall = false;
4382   }
4383 
4384   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4385     unsigned char OpFlags = 0;
4386 
4387     if (UsePlt)
4388       OpFlags = PPCII::MO_PLT;
4389 
4390     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4391                                          OpFlags);
4392     needIndirectCall = false;
4393   }
4394 
4395   if (isPatchPoint) {
4396     // We'll form an invalid direct call when lowering a patchpoint; the full
4397     // sequence for an indirect call is complicated, and many of the
4398     // instructions introduced might have side effects (and, thus, can't be
4399     // removed later). The call itself will be removed as soon as the
4400     // argument/return lowering is complete, so the fact that it has the wrong
4401     // kind of operands should not really matter.
4402     needIndirectCall = false;
4403   }
4404 
4405   if (needIndirectCall) {
4406     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4407     // to do the call, we can't use PPCISD::CALL.
4408     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4409 
4410     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4411       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4412       // entry point, but to the function descriptor (the function entry point
4413       // address is part of the function descriptor though).
4414       // The function descriptor is a three doubleword structure with the
4415       // following fields: function entry point, TOC base address and
4416       // environment pointer.
4417       // Thus for a call through a function pointer, the following actions need
4418       // to be performed:
4419       //   1. Save the TOC of the caller in the TOC save area of its stack
4420       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4421       //   2. Load the address of the function entry point from the function
4422       //      descriptor.
4423       //   3. Load the TOC of the callee from the function descriptor into r2.
4424       //   4. Load the environment pointer from the function descriptor into
4425       //      r11.
4426       //   5. Branch to the function entry point address.
4427       //   6. On return of the callee, the TOC of the caller needs to be
4428       //      restored (this is done in FinishCall()).
4429       //
4430       // The loads are scheduled at the beginning of the call sequence, and the
4431       // register copies are flagged together to ensure that no other
4432       // operations can be scheduled in between. E.g. without flagging the
4433       // copies together, a TOC access in the caller could be scheduled between
4434       // the assignment of the callee TOC and the branch to the callee, which
4435       // results in the TOC access going through the TOC of the callee instead
4436       // of going through the TOC of the caller, which leads to incorrect code.
4437 
4438       // Load the address of the function entry point from the function
4439       // descriptor.
4440       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4441       if (LDChain.getValueType() == MVT::Glue)
4442         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4443 
4444       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4445                           ? MachineMemOperand::MOInvariant
4446                           : MachineMemOperand::MONone;
4447 
4448       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4449       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4450                                         /* Alignment = */ 8, MMOFlags);
4451 
4452       // Load environment pointer into r11.
4453       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4454       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4455       SDValue LoadEnvPtr =
4456           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4457                       /* Alignment = */ 8, MMOFlags);
4458 
4459       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4460       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4461       SDValue TOCPtr =
4462           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4463                       /* Alignment = */ 8, MMOFlags);
4464 
4465       setUsesTOCBasePtr(DAG);
4466       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4467                                         InFlag);
4468       Chain = TOCVal.getValue(0);
4469       InFlag = TOCVal.getValue(1);
4470 
4471       // If the function call has an explicit 'nest' parameter, it takes the
4472       // place of the environment pointer.
4473       if (!hasNest) {
4474         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4475                                           InFlag);
4476 
4477         Chain = EnvVal.getValue(0);
4478         InFlag = EnvVal.getValue(1);
4479       }
4480 
4481       MTCTROps[0] = Chain;
4482       MTCTROps[1] = LoadFuncPtr;
4483       MTCTROps[2] = InFlag;
4484     }
4485 
4486     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4487                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4488     InFlag = Chain.getValue(1);
4489 
4490     NodeTys.clear();
4491     NodeTys.push_back(MVT::Other);
4492     NodeTys.push_back(MVT::Glue);
4493     Ops.push_back(Chain);
4494     CallOpc = PPCISD::BCTRL;
4495     Callee.setNode(nullptr);
4496     // Add use of X11 (holding environment pointer)
4497     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4498       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4499     // Add CTR register as callee so a bctr can be emitted later.
4500     if (isTailCall)
4501       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4502   }
4503 
4504   // If this is a direct call, pass the chain and the callee.
4505   if (Callee.getNode()) {
4506     Ops.push_back(Chain);
4507     Ops.push_back(Callee);
4508   }
4509   // If this is a tail call add stack pointer delta.
4510   if (isTailCall)
4511     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4512 
4513   // Add argument registers to the end of the list so that they are known live
4514   // into the call.
4515   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4516     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4517                                   RegsToPass[i].second.getValueType()));
4518 
4519   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4520   // into the call.
4521   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4522     setUsesTOCBasePtr(DAG);
4523     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4524   }
4525 
4526   return CallOpc;
4527 }
4528 
4529 static
4530 bool isLocalCall(const SDValue &Callee)
4531 {
4532   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4533     return G->getGlobal()->isStrongDefinitionForLinker();
4534   return false;
4535 }
4536 
4537 SDValue PPCTargetLowering::LowerCallResult(
4538     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4539     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4540     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4541 
4542   SmallVector<CCValAssign, 16> RVLocs;
4543   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4544                     *DAG.getContext());
4545   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4546 
4547   // Copy all of the result registers out of their specified physreg.
4548   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4549     CCValAssign &VA = RVLocs[i];
4550     assert(VA.isRegLoc() && "Can only return in registers!");
4551 
4552     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4553                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4554     Chain = Val.getValue(1);
4555     InFlag = Val.getValue(2);
4556 
4557     switch (VA.getLocInfo()) {
4558     default: llvm_unreachable("Unknown loc info!");
4559     case CCValAssign::Full: break;
4560     case CCValAssign::AExt:
4561       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4562       break;
4563     case CCValAssign::ZExt:
4564       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4565                         DAG.getValueType(VA.getValVT()));
4566       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4567       break;
4568     case CCValAssign::SExt:
4569       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4570                         DAG.getValueType(VA.getValVT()));
4571       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4572       break;
4573     }
4574 
4575     InVals.push_back(Val);
4576   }
4577 
4578   return Chain;
4579 }
4580 
4581 SDValue PPCTargetLowering::FinishCall(
4582     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4583     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4584     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4585     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4586     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4587     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4588 
4589   std::vector<EVT> NodeTys;
4590   SmallVector<SDValue, 8> Ops;
4591   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4592                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4593                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4594 
4595   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4596   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4597     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4598 
4599   // When performing tail call optimization the callee pops its arguments off
4600   // the stack. Account for this here so these bytes can be pushed back on in
4601   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4602   int BytesCalleePops =
4603     (CallConv == CallingConv::Fast &&
4604      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4605 
4606   // Add a register mask operand representing the call-preserved registers.
4607   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4608   const uint32_t *Mask =
4609       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4610   assert(Mask && "Missing call preserved mask for calling convention");
4611   Ops.push_back(DAG.getRegisterMask(Mask));
4612 
4613   if (InFlag.getNode())
4614     Ops.push_back(InFlag);
4615 
4616   // Emit tail call.
4617   if (isTailCall) {
4618     assert(((Callee.getOpcode() == ISD::Register &&
4619              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4620             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4621             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4622             isa<ConstantSDNode>(Callee)) &&
4623     "Expecting an global address, external symbol, absolute value or register");
4624 
4625     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4626     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4627   }
4628 
4629   // Add a NOP immediately after the branch instruction when using the 64-bit
4630   // SVR4 ABI. At link time, if caller and callee are in a different module and
4631   // thus have a different TOC, the call will be replaced with a call to a stub
4632   // function which saves the current TOC, loads the TOC of the callee and
4633   // branches to the callee. The NOP will be replaced with a load instruction
4634   // which restores the TOC of the caller from the TOC save slot of the current
4635   // stack frame. If caller and callee belong to the same module (and have the
4636   // same TOC), the NOP will remain unchanged.
4637 
4638   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4639       !isPatchPoint) {
4640     if (CallOpc == PPCISD::BCTRL) {
4641       // This is a call through a function pointer.
4642       // Restore the caller TOC from the save area into R2.
4643       // See PrepareCall() for more information about calls through function
4644       // pointers in the 64-bit SVR4 ABI.
4645       // We are using a target-specific load with r2 hard coded, because the
4646       // result of a target-independent load would never go directly into r2,
4647       // since r2 is a reserved register (which prevents the register allocator
4648       // from allocating it), resulting in an additional register being
4649       // allocated and an unnecessary move instruction being generated.
4650       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4651 
4652       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4653       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4654       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4655       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4656       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4657 
4658       // The address needs to go after the chain input but before the flag (or
4659       // any other variadic arguments).
4660       Ops.insert(std::next(Ops.begin()), AddTOC);
4661     } else if ((CallOpc == PPCISD::CALL) &&
4662                (!isLocalCall(Callee) ||
4663                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4664       // Otherwise insert NOP for non-local calls.
4665       CallOpc = PPCISD::CALL_NOP;
4666   }
4667 
4668   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4669   InFlag = Chain.getValue(1);
4670 
4671   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4672                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4673                              InFlag, dl);
4674   if (!Ins.empty())
4675     InFlag = Chain.getValue(1);
4676 
4677   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4678                          Ins, dl, DAG, InVals);
4679 }
4680 
4681 SDValue
4682 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4683                              SmallVectorImpl<SDValue> &InVals) const {
4684   SelectionDAG &DAG                     = CLI.DAG;
4685   SDLoc &dl                             = CLI.DL;
4686   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4687   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4688   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4689   SDValue Chain                         = CLI.Chain;
4690   SDValue Callee                        = CLI.Callee;
4691   bool &isTailCall                      = CLI.IsTailCall;
4692   CallingConv::ID CallConv              = CLI.CallConv;
4693   bool isVarArg                         = CLI.IsVarArg;
4694   bool isPatchPoint                     = CLI.IsPatchPoint;
4695   ImmutableCallSite *CS                 = CLI.CS;
4696 
4697   if (isTailCall) {
4698     if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4699       isTailCall =
4700         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4701                                                  isVarArg, Outs, Ins, DAG);
4702     else
4703       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4704                                                      Ins, DAG);
4705     if (isTailCall) {
4706       ++NumTailCalls;
4707       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4708         ++NumSiblingCalls;
4709 
4710       assert(isa<GlobalAddressSDNode>(Callee) &&
4711              "Callee should be an llvm::Function object.");
4712       DEBUG(
4713         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4714         const unsigned Width = 80 - strlen("TCO caller: ")
4715                                   - strlen(", callee linkage: 0, 0");
4716         dbgs() << "TCO caller: "
4717                << left_justify(DAG.getMachineFunction().getName(), Width)
4718                << ", callee linkage: "
4719                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4720       );
4721     }
4722   }
4723 
4724   if (!isTailCall && CS && CS->isMustTailCall())
4725     report_fatal_error("failed to perform tail call elimination on a call "
4726                        "site marked musttail");
4727 
4728   if (Subtarget.isSVR4ABI()) {
4729     if (Subtarget.isPPC64())
4730       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4731                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4732                               dl, DAG, InVals, CS);
4733     else
4734       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4735                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4736                               dl, DAG, InVals, CS);
4737   }
4738 
4739   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4740                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4741                           dl, DAG, InVals, CS);
4742 }
4743 
4744 SDValue PPCTargetLowering::LowerCall_32SVR4(
4745     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4746     bool isTailCall, bool isPatchPoint,
4747     const SmallVectorImpl<ISD::OutputArg> &Outs,
4748     const SmallVectorImpl<SDValue> &OutVals,
4749     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4750     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4751     ImmutableCallSite *CS) const {
4752   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4753   // of the 32-bit SVR4 ABI stack frame layout.
4754 
4755   assert((CallConv == CallingConv::C ||
4756           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4757 
4758   unsigned PtrByteSize = 4;
4759 
4760   MachineFunction &MF = DAG.getMachineFunction();
4761 
4762   // Mark this function as potentially containing a function that contains a
4763   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4764   // and restoring the callers stack pointer in this functions epilog. This is
4765   // done because by tail calling the called function might overwrite the value
4766   // in this function's (MF) stack pointer stack slot 0(SP).
4767   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4768       CallConv == CallingConv::Fast)
4769     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4770 
4771   // Count how many bytes are to be pushed on the stack, including the linkage
4772   // area, parameter list area and the part of the local variable space which
4773   // contains copies of aggregates which are passed by value.
4774 
4775   // Assign locations to all of the outgoing arguments.
4776   SmallVector<CCValAssign, 16> ArgLocs;
4777   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4778 
4779   // Reserve space for the linkage area on the stack.
4780   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4781                        PtrByteSize);
4782   if (useSoftFloat())
4783     CCInfo.PreAnalyzeCallOperands(Outs);
4784 
4785   if (isVarArg) {
4786     // Handle fixed and variable vector arguments differently.
4787     // Fixed vector arguments go into registers as long as registers are
4788     // available. Variable vector arguments always go into memory.
4789     unsigned NumArgs = Outs.size();
4790 
4791     for (unsigned i = 0; i != NumArgs; ++i) {
4792       MVT ArgVT = Outs[i].VT;
4793       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4794       bool Result;
4795 
4796       if (Outs[i].IsFixed) {
4797         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4798                                CCInfo);
4799       } else {
4800         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4801                                       ArgFlags, CCInfo);
4802       }
4803 
4804       if (Result) {
4805 #ifndef NDEBUG
4806         errs() << "Call operand #" << i << " has unhandled type "
4807              << EVT(ArgVT).getEVTString() << "\n";
4808 #endif
4809         llvm_unreachable(nullptr);
4810       }
4811     }
4812   } else {
4813     // All arguments are treated the same.
4814     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4815   }
4816   CCInfo.clearWasPPCF128();
4817 
4818   // Assign locations to all of the outgoing aggregate by value arguments.
4819   SmallVector<CCValAssign, 16> ByValArgLocs;
4820   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4821 
4822   // Reserve stack space for the allocations in CCInfo.
4823   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4824 
4825   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4826 
4827   // Size of the linkage area, parameter list area and the part of the local
4828   // space variable where copies of aggregates which are passed by value are
4829   // stored.
4830   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4831 
4832   // Calculate by how many bytes the stack has to be adjusted in case of tail
4833   // call optimization.
4834   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4835 
4836   // Adjust the stack pointer for the new arguments...
4837   // These operations are automatically eliminated by the prolog/epilog pass
4838   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4839                                dl);
4840   SDValue CallSeqStart = Chain;
4841 
4842   // Load the return address and frame pointer so it can be moved somewhere else
4843   // later.
4844   SDValue LROp, FPOp;
4845   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4846 
4847   // Set up a copy of the stack pointer for use loading and storing any
4848   // arguments that may not fit in the registers available for argument
4849   // passing.
4850   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4851 
4852   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4853   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4854   SmallVector<SDValue, 8> MemOpChains;
4855 
4856   bool seenFloatArg = false;
4857   // Walk the register/memloc assignments, inserting copies/loads.
4858   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4859        i != e;
4860        ++i) {
4861     CCValAssign &VA = ArgLocs[i];
4862     SDValue Arg = OutVals[i];
4863     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4864 
4865     if (Flags.isByVal()) {
4866       // Argument is an aggregate which is passed by value, thus we need to
4867       // create a copy of it in the local variable space of the current stack
4868       // frame (which is the stack frame of the caller) and pass the address of
4869       // this copy to the callee.
4870       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4871       CCValAssign &ByValVA = ByValArgLocs[j++];
4872       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4873 
4874       // Memory reserved in the local variable space of the callers stack frame.
4875       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4876 
4877       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4878       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4879                            StackPtr, PtrOff);
4880 
4881       // Create a copy of the argument in the local area of the current
4882       // stack frame.
4883       SDValue MemcpyCall =
4884         CreateCopyOfByValArgument(Arg, PtrOff,
4885                                   CallSeqStart.getNode()->getOperand(0),
4886                                   Flags, DAG, dl);
4887 
4888       // This must go outside the CALLSEQ_START..END.
4889       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4890                            CallSeqStart.getNode()->getOperand(1),
4891                            SDLoc(MemcpyCall));
4892       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4893                              NewCallSeqStart.getNode());
4894       Chain = CallSeqStart = NewCallSeqStart;
4895 
4896       // Pass the address of the aggregate copy on the stack either in a
4897       // physical register or in the parameter list area of the current stack
4898       // frame to the callee.
4899       Arg = PtrOff;
4900     }
4901 
4902     if (VA.isRegLoc()) {
4903       if (Arg.getValueType() == MVT::i1)
4904         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4905 
4906       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4907       // Put argument in a physical register.
4908       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4909     } else {
4910       // Put argument in the parameter list area of the current stack frame.
4911       assert(VA.isMemLoc());
4912       unsigned LocMemOffset = VA.getLocMemOffset();
4913 
4914       if (!isTailCall) {
4915         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4916         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4917                              StackPtr, PtrOff);
4918 
4919         MemOpChains.push_back(
4920             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4921       } else {
4922         // Calculate and remember argument location.
4923         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4924                                  TailCallArguments);
4925       }
4926     }
4927   }
4928 
4929   if (!MemOpChains.empty())
4930     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4931 
4932   // Build a sequence of copy-to-reg nodes chained together with token chain
4933   // and flag operands which copy the outgoing args into the appropriate regs.
4934   SDValue InFlag;
4935   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4936     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4937                              RegsToPass[i].second, InFlag);
4938     InFlag = Chain.getValue(1);
4939   }
4940 
4941   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4942   // registers.
4943   if (isVarArg) {
4944     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4945     SDValue Ops[] = { Chain, InFlag };
4946 
4947     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4948                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4949 
4950     InFlag = Chain.getValue(1);
4951   }
4952 
4953   if (isTailCall)
4954     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
4955                     TailCallArguments);
4956 
4957   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
4958                     /* unused except on PPC64 ELFv1 */ false, DAG,
4959                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4960                     NumBytes, Ins, InVals, CS);
4961 }
4962 
4963 // Copy an argument into memory, being careful to do this outside the
4964 // call sequence for the call to which the argument belongs.
4965 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4966     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4967     SelectionDAG &DAG, const SDLoc &dl) const {
4968   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4969                         CallSeqStart.getNode()->getOperand(0),
4970                         Flags, DAG, dl);
4971   // The MEMCPY must go outside the CALLSEQ_START..END.
4972   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4973                              CallSeqStart.getNode()->getOperand(1),
4974                              SDLoc(MemcpyCall));
4975   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4976                          NewCallSeqStart.getNode());
4977   return NewCallSeqStart;
4978 }
4979 
4980 SDValue PPCTargetLowering::LowerCall_64SVR4(
4981     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4982     bool isTailCall, bool isPatchPoint,
4983     const SmallVectorImpl<ISD::OutputArg> &Outs,
4984     const SmallVectorImpl<SDValue> &OutVals,
4985     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4986     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4987     ImmutableCallSite *CS) const {
4988 
4989   bool isELFv2ABI = Subtarget.isELFv2ABI();
4990   bool isLittleEndian = Subtarget.isLittleEndian();
4991   unsigned NumOps = Outs.size();
4992   bool hasNest = false;
4993   bool IsSibCall = false;
4994 
4995   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4996   unsigned PtrByteSize = 8;
4997 
4998   MachineFunction &MF = DAG.getMachineFunction();
4999 
5000   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5001     IsSibCall = true;
5002 
5003   // Mark this function as potentially containing a function that contains a
5004   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5005   // and restoring the callers stack pointer in this functions epilog. This is
5006   // done because by tail calling the called function might overwrite the value
5007   // in this function's (MF) stack pointer stack slot 0(SP).
5008   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5009       CallConv == CallingConv::Fast)
5010     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5011 
5012   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5013          "fastcc not supported on varargs functions");
5014 
5015   // Count how many bytes are to be pushed on the stack, including the linkage
5016   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5017   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5018   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5019   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5020   unsigned NumBytes = LinkageSize;
5021   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5022   unsigned &QFPR_idx = FPR_idx;
5023 
5024   static const MCPhysReg GPR[] = {
5025     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5026     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5027   };
5028   static const MCPhysReg VR[] = {
5029     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5030     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5031   };
5032   static const MCPhysReg VSRH[] = {
5033     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
5034     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
5035   };
5036 
5037   const unsigned NumGPRs = array_lengthof(GPR);
5038   const unsigned NumFPRs = 13;
5039   const unsigned NumVRs  = array_lengthof(VR);
5040   const unsigned NumQFPRs = NumFPRs;
5041 
5042   // When using the fast calling convention, we don't provide backing for
5043   // arguments that will be in registers.
5044   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5045 
5046   // Add up all the space actually used.
5047   for (unsigned i = 0; i != NumOps; ++i) {
5048     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5049     EVT ArgVT = Outs[i].VT;
5050     EVT OrigVT = Outs[i].ArgVT;
5051 
5052     if (Flags.isNest())
5053       continue;
5054 
5055     if (CallConv == CallingConv::Fast) {
5056       if (Flags.isByVal())
5057         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5058       else
5059         switch (ArgVT.getSimpleVT().SimpleTy) {
5060         default: llvm_unreachable("Unexpected ValueType for argument!");
5061         case MVT::i1:
5062         case MVT::i32:
5063         case MVT::i64:
5064           if (++NumGPRsUsed <= NumGPRs)
5065             continue;
5066           break;
5067         case MVT::v4i32:
5068         case MVT::v8i16:
5069         case MVT::v16i8:
5070         case MVT::v2f64:
5071         case MVT::v2i64:
5072         case MVT::v1i128:
5073           if (++NumVRsUsed <= NumVRs)
5074             continue;
5075           break;
5076         case MVT::v4f32:
5077           // When using QPX, this is handled like a FP register, otherwise, it
5078           // is an Altivec register.
5079           if (Subtarget.hasQPX()) {
5080             if (++NumFPRsUsed <= NumFPRs)
5081               continue;
5082           } else {
5083             if (++NumVRsUsed <= NumVRs)
5084               continue;
5085           }
5086           break;
5087         case MVT::f32:
5088         case MVT::f64:
5089         case MVT::v4f64: // QPX
5090         case MVT::v4i1:  // QPX
5091           if (++NumFPRsUsed <= NumFPRs)
5092             continue;
5093           break;
5094         }
5095     }
5096 
5097     /* Respect alignment of argument on the stack.  */
5098     unsigned Align =
5099       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5100     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5101 
5102     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5103     if (Flags.isInConsecutiveRegsLast())
5104       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5105   }
5106 
5107   unsigned NumBytesActuallyUsed = NumBytes;
5108 
5109   // The prolog code of the callee may store up to 8 GPR argument registers to
5110   // the stack, allowing va_start to index over them in memory if its varargs.
5111   // Because we cannot tell if this is needed on the caller side, we have to
5112   // conservatively assume that it is needed.  As such, make sure we have at
5113   // least enough stack space for the caller to store the 8 GPRs.
5114   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5115   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5116 
5117   // Tail call needs the stack to be aligned.
5118   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5119       CallConv == CallingConv::Fast)
5120     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5121 
5122   int SPDiff = 0;
5123 
5124   // Calculate by how many bytes the stack has to be adjusted in case of tail
5125   // call optimization.
5126   if (!IsSibCall)
5127     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5128 
5129   // To protect arguments on the stack from being clobbered in a tail call,
5130   // force all the loads to happen before doing any other lowering.
5131   if (isTailCall)
5132     Chain = DAG.getStackArgumentTokenFactor(Chain);
5133 
5134   // Adjust the stack pointer for the new arguments...
5135   // These operations are automatically eliminated by the prolog/epilog pass
5136   if (!IsSibCall)
5137     Chain = DAG.getCALLSEQ_START(Chain,
5138                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5139   SDValue CallSeqStart = Chain;
5140 
5141   // Load the return address and frame pointer so it can be move somewhere else
5142   // later.
5143   SDValue LROp, FPOp;
5144   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5145 
5146   // Set up a copy of the stack pointer for use loading and storing any
5147   // arguments that may not fit in the registers available for argument
5148   // passing.
5149   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5150 
5151   // Figure out which arguments are going to go in registers, and which in
5152   // memory.  Also, if this is a vararg function, floating point operations
5153   // must be stored to our stack, and loaded into integer regs as well, if
5154   // any integer regs are available for argument passing.
5155   unsigned ArgOffset = LinkageSize;
5156 
5157   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5158   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5159 
5160   SmallVector<SDValue, 8> MemOpChains;
5161   for (unsigned i = 0; i != NumOps; ++i) {
5162     SDValue Arg = OutVals[i];
5163     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5164     EVT ArgVT = Outs[i].VT;
5165     EVT OrigVT = Outs[i].ArgVT;
5166 
5167     // PtrOff will be used to store the current argument to the stack if a
5168     // register cannot be found for it.
5169     SDValue PtrOff;
5170 
5171     // We re-align the argument offset for each argument, except when using the
5172     // fast calling convention, when we need to make sure we do that only when
5173     // we'll actually use a stack slot.
5174     auto ComputePtrOff = [&]() {
5175       /* Respect alignment of argument on the stack.  */
5176       unsigned Align =
5177         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5178       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5179 
5180       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5181 
5182       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5183     };
5184 
5185     if (CallConv != CallingConv::Fast) {
5186       ComputePtrOff();
5187 
5188       /* Compute GPR index associated with argument offset.  */
5189       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5190       GPR_idx = std::min(GPR_idx, NumGPRs);
5191     }
5192 
5193     // Promote integers to 64-bit values.
5194     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5195       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5196       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5197       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5198     }
5199 
5200     // FIXME memcpy is used way more than necessary.  Correctness first.
5201     // Note: "by value" is code for passing a structure by value, not
5202     // basic types.
5203     if (Flags.isByVal()) {
5204       // Note: Size includes alignment padding, so
5205       //   struct x { short a; char b; }
5206       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5207       // These are the proper values we need for right-justifying the
5208       // aggregate in a parameter register.
5209       unsigned Size = Flags.getByValSize();
5210 
5211       // An empty aggregate parameter takes up no storage and no
5212       // registers.
5213       if (Size == 0)
5214         continue;
5215 
5216       if (CallConv == CallingConv::Fast)
5217         ComputePtrOff();
5218 
5219       // All aggregates smaller than 8 bytes must be passed right-justified.
5220       if (Size==1 || Size==2 || Size==4) {
5221         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5222         if (GPR_idx != NumGPRs) {
5223           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5224                                         MachinePointerInfo(), VT);
5225           MemOpChains.push_back(Load.getValue(1));
5226           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5227 
5228           ArgOffset += PtrByteSize;
5229           continue;
5230         }
5231       }
5232 
5233       if (GPR_idx == NumGPRs && Size < 8) {
5234         SDValue AddPtr = PtrOff;
5235         if (!isLittleEndian) {
5236           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5237                                           PtrOff.getValueType());
5238           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5239         }
5240         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5241                                                           CallSeqStart,
5242                                                           Flags, DAG, dl);
5243         ArgOffset += PtrByteSize;
5244         continue;
5245       }
5246       // Copy entire object into memory.  There are cases where gcc-generated
5247       // code assumes it is there, even if it could be put entirely into
5248       // registers.  (This is not what the doc says.)
5249 
5250       // FIXME: The above statement is likely due to a misunderstanding of the
5251       // documents.  All arguments must be copied into the parameter area BY
5252       // THE CALLEE in the event that the callee takes the address of any
5253       // formal argument.  That has not yet been implemented.  However, it is
5254       // reasonable to use the stack area as a staging area for the register
5255       // load.
5256 
5257       // Skip this for small aggregates, as we will use the same slot for a
5258       // right-justified copy, below.
5259       if (Size >= 8)
5260         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5261                                                           CallSeqStart,
5262                                                           Flags, DAG, dl);
5263 
5264       // When a register is available, pass a small aggregate right-justified.
5265       if (Size < 8 && GPR_idx != NumGPRs) {
5266         // The easiest way to get this right-justified in a register
5267         // is to copy the structure into the rightmost portion of a
5268         // local variable slot, then load the whole slot into the
5269         // register.
5270         // FIXME: The memcpy seems to produce pretty awful code for
5271         // small aggregates, particularly for packed ones.
5272         // FIXME: It would be preferable to use the slot in the
5273         // parameter save area instead of a new local variable.
5274         SDValue AddPtr = PtrOff;
5275         if (!isLittleEndian) {
5276           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5277           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5278         }
5279         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5280                                                           CallSeqStart,
5281                                                           Flags, DAG, dl);
5282 
5283         // Load the slot into the register.
5284         SDValue Load =
5285             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5286         MemOpChains.push_back(Load.getValue(1));
5287         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5288 
5289         // Done with this argument.
5290         ArgOffset += PtrByteSize;
5291         continue;
5292       }
5293 
5294       // For aggregates larger than PtrByteSize, copy the pieces of the
5295       // object that fit into registers from the parameter save area.
5296       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5297         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5298         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5299         if (GPR_idx != NumGPRs) {
5300           SDValue Load =
5301               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5302           MemOpChains.push_back(Load.getValue(1));
5303           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5304           ArgOffset += PtrByteSize;
5305         } else {
5306           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5307           break;
5308         }
5309       }
5310       continue;
5311     }
5312 
5313     switch (Arg.getSimpleValueType().SimpleTy) {
5314     default: llvm_unreachable("Unexpected ValueType for argument!");
5315     case MVT::i1:
5316     case MVT::i32:
5317     case MVT::i64:
5318       if (Flags.isNest()) {
5319         // The 'nest' parameter, if any, is passed in R11.
5320         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5321         hasNest = true;
5322         break;
5323       }
5324 
5325       // These can be scalar arguments or elements of an integer array type
5326       // passed directly.  Clang may use those instead of "byval" aggregate
5327       // types to avoid forcing arguments to memory unnecessarily.
5328       if (GPR_idx != NumGPRs) {
5329         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5330       } else {
5331         if (CallConv == CallingConv::Fast)
5332           ComputePtrOff();
5333 
5334         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5335                          true, isTailCall, false, MemOpChains,
5336                          TailCallArguments, dl);
5337         if (CallConv == CallingConv::Fast)
5338           ArgOffset += PtrByteSize;
5339       }
5340       if (CallConv != CallingConv::Fast)
5341         ArgOffset += PtrByteSize;
5342       break;
5343     case MVT::f32:
5344     case MVT::f64: {
5345       // These can be scalar arguments or elements of a float array type
5346       // passed directly.  The latter are used to implement ELFv2 homogenous
5347       // float aggregates.
5348 
5349       // Named arguments go into FPRs first, and once they overflow, the
5350       // remaining arguments go into GPRs and then the parameter save area.
5351       // Unnamed arguments for vararg functions always go to GPRs and
5352       // then the parameter save area.  For now, put all arguments to vararg
5353       // routines always in both locations (FPR *and* GPR or stack slot).
5354       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5355       bool NeededLoad = false;
5356 
5357       // First load the argument into the next available FPR.
5358       if (FPR_idx != NumFPRs)
5359         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5360 
5361       // Next, load the argument into GPR or stack slot if needed.
5362       if (!NeedGPROrStack)
5363         ;
5364       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5365         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5366         // once we support fp <-> gpr moves.
5367 
5368         // In the non-vararg case, this can only ever happen in the
5369         // presence of f32 array types, since otherwise we never run
5370         // out of FPRs before running out of GPRs.
5371         SDValue ArgVal;
5372 
5373         // Double values are always passed in a single GPR.
5374         if (Arg.getValueType() != MVT::f32) {
5375           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5376 
5377         // Non-array float values are extended and passed in a GPR.
5378         } else if (!Flags.isInConsecutiveRegs()) {
5379           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5380           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5381 
5382         // If we have an array of floats, we collect every odd element
5383         // together with its predecessor into one GPR.
5384         } else if (ArgOffset % PtrByteSize != 0) {
5385           SDValue Lo, Hi;
5386           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5387           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5388           if (!isLittleEndian)
5389             std::swap(Lo, Hi);
5390           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5391 
5392         // The final element, if even, goes into the first half of a GPR.
5393         } else if (Flags.isInConsecutiveRegsLast()) {
5394           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5395           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5396           if (!isLittleEndian)
5397             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5398                                  DAG.getConstant(32, dl, MVT::i32));
5399 
5400         // Non-final even elements are skipped; they will be handled
5401         // together the with subsequent argument on the next go-around.
5402         } else
5403           ArgVal = SDValue();
5404 
5405         if (ArgVal.getNode())
5406           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5407       } else {
5408         if (CallConv == CallingConv::Fast)
5409           ComputePtrOff();
5410 
5411         // Single-precision floating-point values are mapped to the
5412         // second (rightmost) word of the stack doubleword.
5413         if (Arg.getValueType() == MVT::f32 &&
5414             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5415           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5416           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5417         }
5418 
5419         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5420                          true, isTailCall, false, MemOpChains,
5421                          TailCallArguments, dl);
5422 
5423         NeededLoad = true;
5424       }
5425       // When passing an array of floats, the array occupies consecutive
5426       // space in the argument area; only round up to the next doubleword
5427       // at the end of the array.  Otherwise, each float takes 8 bytes.
5428       if (CallConv != CallingConv::Fast || NeededLoad) {
5429         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5430                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5431         if (Flags.isInConsecutiveRegsLast())
5432           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5433       }
5434       break;
5435     }
5436     case MVT::v4f32:
5437     case MVT::v4i32:
5438     case MVT::v8i16:
5439     case MVT::v16i8:
5440     case MVT::v2f64:
5441     case MVT::v2i64:
5442     case MVT::v1i128:
5443       if (!Subtarget.hasQPX()) {
5444       // These can be scalar arguments or elements of a vector array type
5445       // passed directly.  The latter are used to implement ELFv2 homogenous
5446       // vector aggregates.
5447 
5448       // For a varargs call, named arguments go into VRs or on the stack as
5449       // usual; unnamed arguments always go to the stack or the corresponding
5450       // GPRs when within range.  For now, we always put the value in both
5451       // locations (or even all three).
5452       if (isVarArg) {
5453         // We could elide this store in the case where the object fits
5454         // entirely in R registers.  Maybe later.
5455         SDValue Store =
5456             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5457         MemOpChains.push_back(Store);
5458         if (VR_idx != NumVRs) {
5459           SDValue Load =
5460               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5461           MemOpChains.push_back(Load.getValue(1));
5462 
5463           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5464                            Arg.getSimpleValueType() == MVT::v2i64) ?
5465                           VSRH[VR_idx] : VR[VR_idx];
5466           ++VR_idx;
5467 
5468           RegsToPass.push_back(std::make_pair(VReg, Load));
5469         }
5470         ArgOffset += 16;
5471         for (unsigned i=0; i<16; i+=PtrByteSize) {
5472           if (GPR_idx == NumGPRs)
5473             break;
5474           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5475                                    DAG.getConstant(i, dl, PtrVT));
5476           SDValue Load =
5477               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5478           MemOpChains.push_back(Load.getValue(1));
5479           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5480         }
5481         break;
5482       }
5483 
5484       // Non-varargs Altivec params go into VRs or on the stack.
5485       if (VR_idx != NumVRs) {
5486         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5487                          Arg.getSimpleValueType() == MVT::v2i64) ?
5488                         VSRH[VR_idx] : VR[VR_idx];
5489         ++VR_idx;
5490 
5491         RegsToPass.push_back(std::make_pair(VReg, Arg));
5492       } else {
5493         if (CallConv == CallingConv::Fast)
5494           ComputePtrOff();
5495 
5496         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5497                          true, isTailCall, true, MemOpChains,
5498                          TailCallArguments, dl);
5499         if (CallConv == CallingConv::Fast)
5500           ArgOffset += 16;
5501       }
5502 
5503       if (CallConv != CallingConv::Fast)
5504         ArgOffset += 16;
5505       break;
5506       } // not QPX
5507 
5508       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5509              "Invalid QPX parameter type");
5510 
5511       /* fall through */
5512     case MVT::v4f64:
5513     case MVT::v4i1: {
5514       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5515       if (isVarArg) {
5516         // We could elide this store in the case where the object fits
5517         // entirely in R registers.  Maybe later.
5518         SDValue Store =
5519             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5520         MemOpChains.push_back(Store);
5521         if (QFPR_idx != NumQFPRs) {
5522           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5523                                      PtrOff, MachinePointerInfo());
5524           MemOpChains.push_back(Load.getValue(1));
5525           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5526         }
5527         ArgOffset += (IsF32 ? 16 : 32);
5528         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5529           if (GPR_idx == NumGPRs)
5530             break;
5531           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5532                                    DAG.getConstant(i, dl, PtrVT));
5533           SDValue Load =
5534               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5535           MemOpChains.push_back(Load.getValue(1));
5536           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5537         }
5538         break;
5539       }
5540 
5541       // Non-varargs QPX params go into registers or on the stack.
5542       if (QFPR_idx != NumQFPRs) {
5543         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5544       } else {
5545         if (CallConv == CallingConv::Fast)
5546           ComputePtrOff();
5547 
5548         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5549                          true, isTailCall, true, MemOpChains,
5550                          TailCallArguments, dl);
5551         if (CallConv == CallingConv::Fast)
5552           ArgOffset += (IsF32 ? 16 : 32);
5553       }
5554 
5555       if (CallConv != CallingConv::Fast)
5556         ArgOffset += (IsF32 ? 16 : 32);
5557       break;
5558       }
5559     }
5560   }
5561 
5562   assert(NumBytesActuallyUsed == ArgOffset);
5563   (void)NumBytesActuallyUsed;
5564 
5565   if (!MemOpChains.empty())
5566     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5567 
5568   // Check if this is an indirect call (MTCTR/BCTRL).
5569   // See PrepareCall() for more information about calls through function
5570   // pointers in the 64-bit SVR4 ABI.
5571   if (!isTailCall && !isPatchPoint &&
5572       !isFunctionGlobalAddress(Callee) &&
5573       !isa<ExternalSymbolSDNode>(Callee)) {
5574     // Load r2 into a virtual register and store it to the TOC save area.
5575     setUsesTOCBasePtr(DAG);
5576     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5577     // TOC save area offset.
5578     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5579     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5580     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5581     Chain = DAG.getStore(
5582         Val.getValue(1), dl, Val, AddPtr,
5583         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5584     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5585     // This does not mean the MTCTR instruction must use R12; it's easier
5586     // to model this as an extra parameter, so do that.
5587     if (isELFv2ABI && !isPatchPoint)
5588       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5589   }
5590 
5591   // Build a sequence of copy-to-reg nodes chained together with token chain
5592   // and flag operands which copy the outgoing args into the appropriate regs.
5593   SDValue InFlag;
5594   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5595     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5596                              RegsToPass[i].second, InFlag);
5597     InFlag = Chain.getValue(1);
5598   }
5599 
5600   if (isTailCall && !IsSibCall)
5601     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5602                     TailCallArguments);
5603 
5604   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5605                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5606                     SPDiff, NumBytes, Ins, InVals, CS);
5607 }
5608 
5609 SDValue PPCTargetLowering::LowerCall_Darwin(
5610     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5611     bool isTailCall, bool isPatchPoint,
5612     const SmallVectorImpl<ISD::OutputArg> &Outs,
5613     const SmallVectorImpl<SDValue> &OutVals,
5614     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5615     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5616     ImmutableCallSite *CS) const {
5617 
5618   unsigned NumOps = Outs.size();
5619 
5620   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5621   bool isPPC64 = PtrVT == MVT::i64;
5622   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5623 
5624   MachineFunction &MF = DAG.getMachineFunction();
5625 
5626   // Mark this function as potentially containing a function that contains a
5627   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5628   // and restoring the callers stack pointer in this functions epilog. This is
5629   // done because by tail calling the called function might overwrite the value
5630   // in this function's (MF) stack pointer stack slot 0(SP).
5631   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5632       CallConv == CallingConv::Fast)
5633     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5634 
5635   // Count how many bytes are to be pushed on the stack, including the linkage
5636   // area, and parameter passing area.  We start with 24/48 bytes, which is
5637   // prereserved space for [SP][CR][LR][3 x unused].
5638   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5639   unsigned NumBytes = LinkageSize;
5640 
5641   // Add up all the space actually used.
5642   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5643   // they all go in registers, but we must reserve stack space for them for
5644   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5645   // assigned stack space in order, with padding so Altivec parameters are
5646   // 16-byte aligned.
5647   unsigned nAltivecParamsAtEnd = 0;
5648   for (unsigned i = 0; i != NumOps; ++i) {
5649     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5650     EVT ArgVT = Outs[i].VT;
5651     // Varargs Altivec parameters are padded to a 16 byte boundary.
5652     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5653         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5654         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5655       if (!isVarArg && !isPPC64) {
5656         // Non-varargs Altivec parameters go after all the non-Altivec
5657         // parameters; handle those later so we know how much padding we need.
5658         nAltivecParamsAtEnd++;
5659         continue;
5660       }
5661       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5662       NumBytes = ((NumBytes+15)/16)*16;
5663     }
5664     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5665   }
5666 
5667   // Allow for Altivec parameters at the end, if needed.
5668   if (nAltivecParamsAtEnd) {
5669     NumBytes = ((NumBytes+15)/16)*16;
5670     NumBytes += 16*nAltivecParamsAtEnd;
5671   }
5672 
5673   // The prolog code of the callee may store up to 8 GPR argument registers to
5674   // the stack, allowing va_start to index over them in memory if its varargs.
5675   // Because we cannot tell if this is needed on the caller side, we have to
5676   // conservatively assume that it is needed.  As such, make sure we have at
5677   // least enough stack space for the caller to store the 8 GPRs.
5678   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5679 
5680   // Tail call needs the stack to be aligned.
5681   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5682       CallConv == CallingConv::Fast)
5683     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5684 
5685   // Calculate by how many bytes the stack has to be adjusted in case of tail
5686   // call optimization.
5687   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5688 
5689   // To protect arguments on the stack from being clobbered in a tail call,
5690   // force all the loads to happen before doing any other lowering.
5691   if (isTailCall)
5692     Chain = DAG.getStackArgumentTokenFactor(Chain);
5693 
5694   // Adjust the stack pointer for the new arguments...
5695   // These operations are automatically eliminated by the prolog/epilog pass
5696   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5697                                dl);
5698   SDValue CallSeqStart = Chain;
5699 
5700   // Load the return address and frame pointer so it can be move somewhere else
5701   // later.
5702   SDValue LROp, FPOp;
5703   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5704 
5705   // Set up a copy of the stack pointer for use loading and storing any
5706   // arguments that may not fit in the registers available for argument
5707   // passing.
5708   SDValue StackPtr;
5709   if (isPPC64)
5710     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5711   else
5712     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5713 
5714   // Figure out which arguments are going to go in registers, and which in
5715   // memory.  Also, if this is a vararg function, floating point operations
5716   // must be stored to our stack, and loaded into integer regs as well, if
5717   // any integer regs are available for argument passing.
5718   unsigned ArgOffset = LinkageSize;
5719   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5720 
5721   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5722     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5723     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5724   };
5725   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5726     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5727     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5728   };
5729   static const MCPhysReg VR[] = {
5730     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5731     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5732   };
5733   const unsigned NumGPRs = array_lengthof(GPR_32);
5734   const unsigned NumFPRs = 13;
5735   const unsigned NumVRs  = array_lengthof(VR);
5736 
5737   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5738 
5739   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5740   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5741 
5742   SmallVector<SDValue, 8> MemOpChains;
5743   for (unsigned i = 0; i != NumOps; ++i) {
5744     SDValue Arg = OutVals[i];
5745     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5746 
5747     // PtrOff will be used to store the current argument to the stack if a
5748     // register cannot be found for it.
5749     SDValue PtrOff;
5750 
5751     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5752 
5753     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5754 
5755     // On PPC64, promote integers to 64-bit values.
5756     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5757       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5758       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5759       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5760     }
5761 
5762     // FIXME memcpy is used way more than necessary.  Correctness first.
5763     // Note: "by value" is code for passing a structure by value, not
5764     // basic types.
5765     if (Flags.isByVal()) {
5766       unsigned Size = Flags.getByValSize();
5767       // Very small objects are passed right-justified.  Everything else is
5768       // passed left-justified.
5769       if (Size==1 || Size==2) {
5770         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5771         if (GPR_idx != NumGPRs) {
5772           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5773                                         MachinePointerInfo(), VT);
5774           MemOpChains.push_back(Load.getValue(1));
5775           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5776 
5777           ArgOffset += PtrByteSize;
5778         } else {
5779           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5780                                           PtrOff.getValueType());
5781           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5782           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5783                                                             CallSeqStart,
5784                                                             Flags, DAG, dl);
5785           ArgOffset += PtrByteSize;
5786         }
5787         continue;
5788       }
5789       // Copy entire object into memory.  There are cases where gcc-generated
5790       // code assumes it is there, even if it could be put entirely into
5791       // registers.  (This is not what the doc says.)
5792       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5793                                                         CallSeqStart,
5794                                                         Flags, DAG, dl);
5795 
5796       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5797       // copy the pieces of the object that fit into registers from the
5798       // parameter save area.
5799       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5800         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5801         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5802         if (GPR_idx != NumGPRs) {
5803           SDValue Load =
5804               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5805           MemOpChains.push_back(Load.getValue(1));
5806           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5807           ArgOffset += PtrByteSize;
5808         } else {
5809           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5810           break;
5811         }
5812       }
5813       continue;
5814     }
5815 
5816     switch (Arg.getSimpleValueType().SimpleTy) {
5817     default: llvm_unreachable("Unexpected ValueType for argument!");
5818     case MVT::i1:
5819     case MVT::i32:
5820     case MVT::i64:
5821       if (GPR_idx != NumGPRs) {
5822         if (Arg.getValueType() == MVT::i1)
5823           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5824 
5825         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5826       } else {
5827         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5828                          isPPC64, isTailCall, false, MemOpChains,
5829                          TailCallArguments, dl);
5830       }
5831       ArgOffset += PtrByteSize;
5832       break;
5833     case MVT::f32:
5834     case MVT::f64:
5835       if (FPR_idx != NumFPRs) {
5836         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5837 
5838         if (isVarArg) {
5839           SDValue Store =
5840               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5841           MemOpChains.push_back(Store);
5842 
5843           // Float varargs are always shadowed in available integer registers
5844           if (GPR_idx != NumGPRs) {
5845             SDValue Load =
5846                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5847             MemOpChains.push_back(Load.getValue(1));
5848             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5849           }
5850           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5851             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5852             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5853             SDValue Load =
5854                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5855             MemOpChains.push_back(Load.getValue(1));
5856             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5857           }
5858         } else {
5859           // If we have any FPRs remaining, we may also have GPRs remaining.
5860           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5861           // GPRs.
5862           if (GPR_idx != NumGPRs)
5863             ++GPR_idx;
5864           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5865               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5866             ++GPR_idx;
5867         }
5868       } else
5869         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5870                          isPPC64, isTailCall, false, MemOpChains,
5871                          TailCallArguments, dl);
5872       if (isPPC64)
5873         ArgOffset += 8;
5874       else
5875         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5876       break;
5877     case MVT::v4f32:
5878     case MVT::v4i32:
5879     case MVT::v8i16:
5880     case MVT::v16i8:
5881       if (isVarArg) {
5882         // These go aligned on the stack, or in the corresponding R registers
5883         // when within range.  The Darwin PPC ABI doc claims they also go in
5884         // V registers; in fact gcc does this only for arguments that are
5885         // prototyped, not for those that match the ...  We do it for all
5886         // arguments, seems to work.
5887         while (ArgOffset % 16 !=0) {
5888           ArgOffset += PtrByteSize;
5889           if (GPR_idx != NumGPRs)
5890             GPR_idx++;
5891         }
5892         // We could elide this store in the case where the object fits
5893         // entirely in R registers.  Maybe later.
5894         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5895                              DAG.getConstant(ArgOffset, dl, PtrVT));
5896         SDValue Store =
5897             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5898         MemOpChains.push_back(Store);
5899         if (VR_idx != NumVRs) {
5900           SDValue Load =
5901               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5902           MemOpChains.push_back(Load.getValue(1));
5903           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5904         }
5905         ArgOffset += 16;
5906         for (unsigned i=0; i<16; i+=PtrByteSize) {
5907           if (GPR_idx == NumGPRs)
5908             break;
5909           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5910                                    DAG.getConstant(i, dl, PtrVT));
5911           SDValue Load =
5912               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5913           MemOpChains.push_back(Load.getValue(1));
5914           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5915         }
5916         break;
5917       }
5918 
5919       // Non-varargs Altivec params generally go in registers, but have
5920       // stack space allocated at the end.
5921       if (VR_idx != NumVRs) {
5922         // Doesn't have GPR space allocated.
5923         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5924       } else if (nAltivecParamsAtEnd==0) {
5925         // We are emitting Altivec params in order.
5926         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5927                          isPPC64, isTailCall, true, MemOpChains,
5928                          TailCallArguments, dl);
5929         ArgOffset += 16;
5930       }
5931       break;
5932     }
5933   }
5934   // If all Altivec parameters fit in registers, as they usually do,
5935   // they get stack space following the non-Altivec parameters.  We
5936   // don't track this here because nobody below needs it.
5937   // If there are more Altivec parameters than fit in registers emit
5938   // the stores here.
5939   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5940     unsigned j = 0;
5941     // Offset is aligned; skip 1st 12 params which go in V registers.
5942     ArgOffset = ((ArgOffset+15)/16)*16;
5943     ArgOffset += 12*16;
5944     for (unsigned i = 0; i != NumOps; ++i) {
5945       SDValue Arg = OutVals[i];
5946       EVT ArgType = Outs[i].VT;
5947       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5948           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5949         if (++j > NumVRs) {
5950           SDValue PtrOff;
5951           // We are emitting Altivec params in order.
5952           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5953                            isPPC64, isTailCall, true, MemOpChains,
5954                            TailCallArguments, dl);
5955           ArgOffset += 16;
5956         }
5957       }
5958     }
5959   }
5960 
5961   if (!MemOpChains.empty())
5962     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5963 
5964   // On Darwin, R12 must contain the address of an indirect callee.  This does
5965   // not mean the MTCTR instruction must use R12; it's easier to model this as
5966   // an extra parameter, so do that.
5967   if (!isTailCall &&
5968       !isFunctionGlobalAddress(Callee) &&
5969       !isa<ExternalSymbolSDNode>(Callee) &&
5970       !isBLACompatibleAddress(Callee, DAG))
5971     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5972                                                    PPC::R12), Callee));
5973 
5974   // Build a sequence of copy-to-reg nodes chained together with token chain
5975   // and flag operands which copy the outgoing args into the appropriate regs.
5976   SDValue InFlag;
5977   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5978     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5979                              RegsToPass[i].second, InFlag);
5980     InFlag = Chain.getValue(1);
5981   }
5982 
5983   if (isTailCall)
5984     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5985                     TailCallArguments);
5986 
5987   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5988                     /* unused except on PPC64 ELFv1 */ false, DAG,
5989                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5990                     NumBytes, Ins, InVals, CS);
5991 }
5992 
5993 bool
5994 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5995                                   MachineFunction &MF, bool isVarArg,
5996                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5997                                   LLVMContext &Context) const {
5998   SmallVector<CCValAssign, 16> RVLocs;
5999   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6000   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6001 }
6002 
6003 SDValue
6004 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6005                                bool isVarArg,
6006                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6007                                const SmallVectorImpl<SDValue> &OutVals,
6008                                const SDLoc &dl, SelectionDAG &DAG) const {
6009 
6010   SmallVector<CCValAssign, 16> RVLocs;
6011   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6012                  *DAG.getContext());
6013   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6014 
6015   SDValue Flag;
6016   SmallVector<SDValue, 4> RetOps(1, Chain);
6017 
6018   // Copy the result values into the output registers.
6019   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6020     CCValAssign &VA = RVLocs[i];
6021     assert(VA.isRegLoc() && "Can only return in registers!");
6022 
6023     SDValue Arg = OutVals[i];
6024 
6025     switch (VA.getLocInfo()) {
6026     default: llvm_unreachable("Unknown loc info!");
6027     case CCValAssign::Full: break;
6028     case CCValAssign::AExt:
6029       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6030       break;
6031     case CCValAssign::ZExt:
6032       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6033       break;
6034     case CCValAssign::SExt:
6035       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6036       break;
6037     }
6038 
6039     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6040     Flag = Chain.getValue(1);
6041     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6042   }
6043 
6044   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6045   const MCPhysReg *I =
6046     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6047   if (I) {
6048     for (; *I; ++I) {
6049 
6050       if (PPC::G8RCRegClass.contains(*I))
6051         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6052       else if (PPC::F8RCRegClass.contains(*I))
6053         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6054       else if (PPC::CRRCRegClass.contains(*I))
6055         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6056       else if (PPC::VRRCRegClass.contains(*I))
6057         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6058       else
6059         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6060     }
6061   }
6062 
6063   RetOps[0] = Chain;  // Update chain.
6064 
6065   // Add the flag if we have it.
6066   if (Flag.getNode())
6067     RetOps.push_back(Flag);
6068 
6069   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6070 }
6071 
6072 SDValue
6073 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6074                                                 SelectionDAG &DAG) const {
6075   SDLoc dl(Op);
6076 
6077   // Get the corect type for integers.
6078   EVT IntVT = Op.getValueType();
6079 
6080   // Get the inputs.
6081   SDValue Chain = Op.getOperand(0);
6082   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6083   // Build a DYNAREAOFFSET node.
6084   SDValue Ops[2] = {Chain, FPSIdx};
6085   SDVTList VTs = DAG.getVTList(IntVT);
6086   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6087 }
6088 
6089 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6090                                              SelectionDAG &DAG) const {
6091   // When we pop the dynamic allocation we need to restore the SP link.
6092   SDLoc dl(Op);
6093 
6094   // Get the corect type for pointers.
6095   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6096 
6097   // Construct the stack pointer operand.
6098   bool isPPC64 = Subtarget.isPPC64();
6099   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6100   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6101 
6102   // Get the operands for the STACKRESTORE.
6103   SDValue Chain = Op.getOperand(0);
6104   SDValue SaveSP = Op.getOperand(1);
6105 
6106   // Load the old link SP.
6107   SDValue LoadLinkSP =
6108       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6109 
6110   // Restore the stack pointer.
6111   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6112 
6113   // Store the old link SP.
6114   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6115 }
6116 
6117 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6118   MachineFunction &MF = DAG.getMachineFunction();
6119   bool isPPC64 = Subtarget.isPPC64();
6120   EVT PtrVT = getPointerTy(MF.getDataLayout());
6121 
6122   // Get current frame pointer save index.  The users of this index will be
6123   // primarily DYNALLOC instructions.
6124   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6125   int RASI = FI->getReturnAddrSaveIndex();
6126 
6127   // If the frame pointer save index hasn't been defined yet.
6128   if (!RASI) {
6129     // Find out what the fix offset of the frame pointer save area.
6130     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6131     // Allocate the frame index for frame pointer save area.
6132     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6133     // Save the result.
6134     FI->setReturnAddrSaveIndex(RASI);
6135   }
6136   return DAG.getFrameIndex(RASI, PtrVT);
6137 }
6138 
6139 SDValue
6140 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6141   MachineFunction &MF = DAG.getMachineFunction();
6142   bool isPPC64 = Subtarget.isPPC64();
6143   EVT PtrVT = getPointerTy(MF.getDataLayout());
6144 
6145   // Get current frame pointer save index.  The users of this index will be
6146   // primarily DYNALLOC instructions.
6147   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6148   int FPSI = FI->getFramePointerSaveIndex();
6149 
6150   // If the frame pointer save index hasn't been defined yet.
6151   if (!FPSI) {
6152     // Find out what the fix offset of the frame pointer save area.
6153     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6154     // Allocate the frame index for frame pointer save area.
6155     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6156     // Save the result.
6157     FI->setFramePointerSaveIndex(FPSI);
6158   }
6159   return DAG.getFrameIndex(FPSI, PtrVT);
6160 }
6161 
6162 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6163                                                    SelectionDAG &DAG) const {
6164   // Get the inputs.
6165   SDValue Chain = Op.getOperand(0);
6166   SDValue Size  = Op.getOperand(1);
6167   SDLoc dl(Op);
6168 
6169   // Get the corect type for pointers.
6170   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6171   // Negate the size.
6172   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6173                                 DAG.getConstant(0, dl, PtrVT), Size);
6174   // Construct a node for the frame pointer save index.
6175   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6176   // Build a DYNALLOC node.
6177   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6178   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6179   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6180 }
6181 
6182 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6183                                                SelectionDAG &DAG) const {
6184   SDLoc DL(Op);
6185   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6186                      DAG.getVTList(MVT::i32, MVT::Other),
6187                      Op.getOperand(0), Op.getOperand(1));
6188 }
6189 
6190 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6191                                                 SelectionDAG &DAG) const {
6192   SDLoc DL(Op);
6193   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6194                      Op.getOperand(0), Op.getOperand(1));
6195 }
6196 
6197 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6198   if (Op.getValueType().isVector())
6199     return LowerVectorLoad(Op, DAG);
6200 
6201   assert(Op.getValueType() == MVT::i1 &&
6202          "Custom lowering only for i1 loads");
6203 
6204   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6205 
6206   SDLoc dl(Op);
6207   LoadSDNode *LD = cast<LoadSDNode>(Op);
6208 
6209   SDValue Chain = LD->getChain();
6210   SDValue BasePtr = LD->getBasePtr();
6211   MachineMemOperand *MMO = LD->getMemOperand();
6212 
6213   SDValue NewLD =
6214       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6215                      BasePtr, MVT::i8, MMO);
6216   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6217 
6218   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6219   return DAG.getMergeValues(Ops, dl);
6220 }
6221 
6222 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6223   if (Op.getOperand(1).getValueType().isVector())
6224     return LowerVectorStore(Op, DAG);
6225 
6226   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6227          "Custom lowering only for i1 stores");
6228 
6229   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6230 
6231   SDLoc dl(Op);
6232   StoreSDNode *ST = cast<StoreSDNode>(Op);
6233 
6234   SDValue Chain = ST->getChain();
6235   SDValue BasePtr = ST->getBasePtr();
6236   SDValue Value = ST->getValue();
6237   MachineMemOperand *MMO = ST->getMemOperand();
6238 
6239   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6240                       Value);
6241   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6242 }
6243 
6244 // FIXME: Remove this once the ANDI glue bug is fixed:
6245 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6246   assert(Op.getValueType() == MVT::i1 &&
6247          "Custom lowering only for i1 results");
6248 
6249   SDLoc DL(Op);
6250   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6251                      Op.getOperand(0));
6252 }
6253 
6254 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6255 /// possible.
6256 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6257   // Not FP? Not a fsel.
6258   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6259       !Op.getOperand(2).getValueType().isFloatingPoint())
6260     return Op;
6261 
6262   // We might be able to do better than this under some circumstances, but in
6263   // general, fsel-based lowering of select is a finite-math-only optimization.
6264   // For more information, see section F.3 of the 2.06 ISA specification.
6265   if (!DAG.getTarget().Options.NoInfsFPMath ||
6266       !DAG.getTarget().Options.NoNaNsFPMath)
6267     return Op;
6268   // TODO: Propagate flags from the select rather than global settings.
6269   SDNodeFlags Flags;
6270   Flags.setNoInfs(true);
6271   Flags.setNoNaNs(true);
6272 
6273   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6274 
6275   EVT ResVT = Op.getValueType();
6276   EVT CmpVT = Op.getOperand(0).getValueType();
6277   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6278   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6279   SDLoc dl(Op);
6280 
6281   // If the RHS of the comparison is a 0.0, we don't need to do the
6282   // subtraction at all.
6283   SDValue Sel1;
6284   if (isFloatingPointZero(RHS))
6285     switch (CC) {
6286     default: break;       // SETUO etc aren't handled by fsel.
6287     case ISD::SETNE:
6288       std::swap(TV, FV);
6289     case ISD::SETEQ:
6290       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6291         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6292       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6293       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6294         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6295       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6296                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6297     case ISD::SETULT:
6298     case ISD::SETLT:
6299       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6300     case ISD::SETOGE:
6301     case ISD::SETGE:
6302       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6303         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6304       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6305     case ISD::SETUGT:
6306     case ISD::SETGT:
6307       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6308     case ISD::SETOLE:
6309     case ISD::SETLE:
6310       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6311         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6312       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6313                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6314     }
6315 
6316   SDValue Cmp;
6317   switch (CC) {
6318   default: break;       // SETUO etc aren't handled by fsel.
6319   case ISD::SETNE:
6320     std::swap(TV, FV);
6321   case ISD::SETEQ:
6322     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6323     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6324       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6325     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6326     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6327       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6328     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6329                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6330   case ISD::SETULT:
6331   case ISD::SETLT:
6332     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6333     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6334       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6335     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6336   case ISD::SETOGE:
6337   case ISD::SETGE:
6338     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6339     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6340       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6341     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6342   case ISD::SETUGT:
6343   case ISD::SETGT:
6344     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6345     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6346       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6347     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6348   case ISD::SETOLE:
6349   case ISD::SETLE:
6350     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6351     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6352       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6353     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6354   }
6355   return Op;
6356 }
6357 
6358 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6359                                                SelectionDAG &DAG,
6360                                                const SDLoc &dl) const {
6361   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6362   SDValue Src = Op.getOperand(0);
6363   if (Src.getValueType() == MVT::f32)
6364     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6365 
6366   SDValue Tmp;
6367   switch (Op.getSimpleValueType().SimpleTy) {
6368   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6369   case MVT::i32:
6370     Tmp = DAG.getNode(
6371         Op.getOpcode() == ISD::FP_TO_SINT
6372             ? PPCISD::FCTIWZ
6373             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6374         dl, MVT::f64, Src);
6375     break;
6376   case MVT::i64:
6377     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6378            "i64 FP_TO_UINT is supported only with FPCVT");
6379     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6380                                                         PPCISD::FCTIDUZ,
6381                       dl, MVT::f64, Src);
6382     break;
6383   }
6384 
6385   // Convert the FP value to an int value through memory.
6386   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6387     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6388   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6389   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6390   MachinePointerInfo MPI =
6391       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6392 
6393   // Emit a store to the stack slot.
6394   SDValue Chain;
6395   if (i32Stack) {
6396     MachineFunction &MF = DAG.getMachineFunction();
6397     MachineMemOperand *MMO =
6398       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6399     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6400     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6401               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6402   } else
6403     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6404 
6405   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6406   // add in a bias on big endian.
6407   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6408     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6409                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6410     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6411   }
6412 
6413   RLI.Chain = Chain;
6414   RLI.Ptr = FIPtr;
6415   RLI.MPI = MPI;
6416 }
6417 
6418 /// \brief Custom lowers floating point to integer conversions to use
6419 /// the direct move instructions available in ISA 2.07 to avoid the
6420 /// need for load/store combinations.
6421 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6422                                                     SelectionDAG &DAG,
6423                                                     const SDLoc &dl) const {
6424   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6425   SDValue Src = Op.getOperand(0);
6426 
6427   if (Src.getValueType() == MVT::f32)
6428     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6429 
6430   SDValue Tmp;
6431   switch (Op.getSimpleValueType().SimpleTy) {
6432   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6433   case MVT::i32:
6434     Tmp = DAG.getNode(
6435         Op.getOpcode() == ISD::FP_TO_SINT
6436             ? PPCISD::FCTIWZ
6437             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6438         dl, MVT::f64, Src);
6439     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6440     break;
6441   case MVT::i64:
6442     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6443            "i64 FP_TO_UINT is supported only with FPCVT");
6444     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6445                                                         PPCISD::FCTIDUZ,
6446                       dl, MVT::f64, Src);
6447     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6448     break;
6449   }
6450   return Tmp;
6451 }
6452 
6453 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6454                                           const SDLoc &dl) const {
6455   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6456     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6457 
6458   ReuseLoadInfo RLI;
6459   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6460 
6461   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6462                      RLI.Alignment,
6463                      RLI.IsInvariant ? MachineMemOperand::MOInvariant
6464                                      : MachineMemOperand::MONone,
6465                      RLI.AAInfo, RLI.Ranges);
6466 }
6467 
6468 // We're trying to insert a regular store, S, and then a load, L. If the
6469 // incoming value, O, is a load, we might just be able to have our load use the
6470 // address used by O. However, we don't know if anything else will store to
6471 // that address before we can load from it. To prevent this situation, we need
6472 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6473 // the same chain operand as O, we create a token factor from the chain results
6474 // of O and L, and we replace all uses of O's chain result with that token
6475 // factor (see spliceIntoChain below for this last part).
6476 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6477                                             ReuseLoadInfo &RLI,
6478                                             SelectionDAG &DAG,
6479                                             ISD::LoadExtType ET) const {
6480   SDLoc dl(Op);
6481   if (ET == ISD::NON_EXTLOAD &&
6482       (Op.getOpcode() == ISD::FP_TO_UINT ||
6483        Op.getOpcode() == ISD::FP_TO_SINT) &&
6484       isOperationLegalOrCustom(Op.getOpcode(),
6485                                Op.getOperand(0).getValueType())) {
6486 
6487     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6488     return true;
6489   }
6490 
6491   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6492   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6493       LD->isNonTemporal())
6494     return false;
6495   if (LD->getMemoryVT() != MemVT)
6496     return false;
6497 
6498   RLI.Ptr = LD->getBasePtr();
6499   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6500     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6501            "Non-pre-inc AM on PPC?");
6502     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6503                           LD->getOffset());
6504   }
6505 
6506   RLI.Chain = LD->getChain();
6507   RLI.MPI = LD->getPointerInfo();
6508   RLI.IsInvariant = LD->isInvariant();
6509   RLI.Alignment = LD->getAlignment();
6510   RLI.AAInfo = LD->getAAInfo();
6511   RLI.Ranges = LD->getRanges();
6512 
6513   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6514   return true;
6515 }
6516 
6517 // Given the head of the old chain, ResChain, insert a token factor containing
6518 // it and NewResChain, and make users of ResChain now be users of that token
6519 // factor.
6520 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6521                                         SDValue NewResChain,
6522                                         SelectionDAG &DAG) const {
6523   if (!ResChain)
6524     return;
6525 
6526   SDLoc dl(NewResChain);
6527 
6528   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6529                            NewResChain, DAG.getUNDEF(MVT::Other));
6530   assert(TF.getNode() != NewResChain.getNode() &&
6531          "A new TF really is required here");
6532 
6533   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6534   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6535 }
6536 
6537 /// \brief Analyze profitability of direct move
6538 /// prefer float load to int load plus direct move
6539 /// when there is no integer use of int load
6540 static bool directMoveIsProfitable(const SDValue &Op) {
6541   SDNode *Origin = Op.getOperand(0).getNode();
6542   if (Origin->getOpcode() != ISD::LOAD)
6543     return true;
6544 
6545   for (SDNode::use_iterator UI = Origin->use_begin(),
6546                             UE = Origin->use_end();
6547        UI != UE; ++UI) {
6548 
6549     // Only look at the users of the loaded value.
6550     if (UI.getUse().get().getResNo() != 0)
6551       continue;
6552 
6553     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6554         UI->getOpcode() != ISD::UINT_TO_FP)
6555       return true;
6556   }
6557 
6558   return false;
6559 }
6560 
6561 /// \brief Custom lowers integer to floating point conversions to use
6562 /// the direct move instructions available in ISA 2.07 to avoid the
6563 /// need for load/store combinations.
6564 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6565                                                     SelectionDAG &DAG,
6566                                                     const SDLoc &dl) const {
6567   assert((Op.getValueType() == MVT::f32 ||
6568           Op.getValueType() == MVT::f64) &&
6569          "Invalid floating point type as target of conversion");
6570   assert(Subtarget.hasFPCVT() &&
6571          "Int to FP conversions with direct moves require FPCVT");
6572   SDValue FP;
6573   SDValue Src = Op.getOperand(0);
6574   bool SinglePrec = Op.getValueType() == MVT::f32;
6575   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6576   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6577   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6578                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6579 
6580   if (WordInt) {
6581     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6582                      dl, MVT::f64, Src);
6583     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6584   }
6585   else {
6586     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6587     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6588   }
6589 
6590   return FP;
6591 }
6592 
6593 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6594                                           SelectionDAG &DAG) const {
6595   SDLoc dl(Op);
6596 
6597   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6598     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6599       return SDValue();
6600 
6601     SDValue Value = Op.getOperand(0);
6602     // The values are now known to be -1 (false) or 1 (true). To convert this
6603     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6604     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6605     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6606 
6607     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6608 
6609     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6610 
6611     if (Op.getValueType() != MVT::v4f64)
6612       Value = DAG.getNode(ISD::FP_ROUND, dl,
6613                           Op.getValueType(), Value,
6614                           DAG.getIntPtrConstant(1, dl));
6615     return Value;
6616   }
6617 
6618   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6619   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6620     return SDValue();
6621 
6622   if (Op.getOperand(0).getValueType() == MVT::i1)
6623     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6624                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6625                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6626 
6627   // If we have direct moves, we can do all the conversion, skip the store/load
6628   // however, without FPCVT we can't do most conversions.
6629   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6630       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6631     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6632 
6633   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6634          "UINT_TO_FP is supported only with FPCVT");
6635 
6636   // If we have FCFIDS, then use it when converting to single-precision.
6637   // Otherwise, convert to double-precision and then round.
6638   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6639                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6640                                                             : PPCISD::FCFIDS)
6641                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6642                                                             : PPCISD::FCFID);
6643   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6644                   ? MVT::f32
6645                   : MVT::f64;
6646 
6647   if (Op.getOperand(0).getValueType() == MVT::i64) {
6648     SDValue SINT = Op.getOperand(0);
6649     // When converting to single-precision, we actually need to convert
6650     // to double-precision first and then round to single-precision.
6651     // To avoid double-rounding effects during that operation, we have
6652     // to prepare the input operand.  Bits that might be truncated when
6653     // converting to double-precision are replaced by a bit that won't
6654     // be lost at this stage, but is below the single-precision rounding
6655     // position.
6656     //
6657     // However, if -enable-unsafe-fp-math is in effect, accept double
6658     // rounding to avoid the extra overhead.
6659     if (Op.getValueType() == MVT::f32 &&
6660         !Subtarget.hasFPCVT() &&
6661         !DAG.getTarget().Options.UnsafeFPMath) {
6662 
6663       // Twiddle input to make sure the low 11 bits are zero.  (If this
6664       // is the case, we are guaranteed the value will fit into the 53 bit
6665       // mantissa of an IEEE double-precision value without rounding.)
6666       // If any of those low 11 bits were not zero originally, make sure
6667       // bit 12 (value 2048) is set instead, so that the final rounding
6668       // to single-precision gets the correct result.
6669       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6670                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6671       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6672                           Round, DAG.getConstant(2047, dl, MVT::i64));
6673       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6674       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6675                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6676 
6677       // However, we cannot use that value unconditionally: if the magnitude
6678       // of the input value is small, the bit-twiddling we did above might
6679       // end up visibly changing the output.  Fortunately, in that case, we
6680       // don't need to twiddle bits since the original input will convert
6681       // exactly to double-precision floating-point already.  Therefore,
6682       // construct a conditional to use the original value if the top 11
6683       // bits are all sign-bit copies, and use the rounded value computed
6684       // above otherwise.
6685       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6686                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6687       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6688                          Cond, DAG.getConstant(1, dl, MVT::i64));
6689       Cond = DAG.getSetCC(dl, MVT::i32,
6690                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6691 
6692       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6693     }
6694 
6695     ReuseLoadInfo RLI;
6696     SDValue Bits;
6697 
6698     MachineFunction &MF = DAG.getMachineFunction();
6699     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6700       Bits =
6701           DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, RLI.Alignment,
6702                       RLI.IsInvariant ? MachineMemOperand::MOInvariant
6703                                       : MachineMemOperand::MONone,
6704                       RLI.AAInfo, RLI.Ranges);
6705       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6706     } else if (Subtarget.hasLFIWAX() &&
6707                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6708       MachineMemOperand *MMO =
6709         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6710                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6711       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6712       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6713                                      DAG.getVTList(MVT::f64, MVT::Other),
6714                                      Ops, MVT::i32, MMO);
6715       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6716     } else if (Subtarget.hasFPCVT() &&
6717                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6718       MachineMemOperand *MMO =
6719         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6720                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6721       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6722       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6723                                      DAG.getVTList(MVT::f64, MVT::Other),
6724                                      Ops, MVT::i32, MMO);
6725       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6726     } else if (((Subtarget.hasLFIWAX() &&
6727                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6728                 (Subtarget.hasFPCVT() &&
6729                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6730                SINT.getOperand(0).getValueType() == MVT::i32) {
6731       MachineFrameInfo &MFI = MF.getFrameInfo();
6732       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6733 
6734       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6735       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6736 
6737       SDValue Store =
6738           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6739                        MachinePointerInfo::getFixedStack(
6740                            DAG.getMachineFunction(), FrameIdx));
6741 
6742       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6743              "Expected an i32 store");
6744 
6745       RLI.Ptr = FIdx;
6746       RLI.Chain = Store;
6747       RLI.MPI =
6748           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6749       RLI.Alignment = 4;
6750 
6751       MachineMemOperand *MMO =
6752         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6753                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6754       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6755       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6756                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6757                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6758                                      Ops, MVT::i32, MMO);
6759     } else
6760       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6761 
6762     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6763 
6764     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6765       FP = DAG.getNode(ISD::FP_ROUND, dl,
6766                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6767     return FP;
6768   }
6769 
6770   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6771          "Unhandled INT_TO_FP type in custom expander!");
6772   // Since we only generate this in 64-bit mode, we can take advantage of
6773   // 64-bit registers.  In particular, sign extend the input value into the
6774   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6775   // then lfd it and fcfid it.
6776   MachineFunction &MF = DAG.getMachineFunction();
6777   MachineFrameInfo &MFI = MF.getFrameInfo();
6778   EVT PtrVT = getPointerTy(MF.getDataLayout());
6779 
6780   SDValue Ld;
6781   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6782     ReuseLoadInfo RLI;
6783     bool ReusingLoad;
6784     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6785                                             DAG))) {
6786       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6787       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6788 
6789       SDValue Store =
6790           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6791                        MachinePointerInfo::getFixedStack(
6792                            DAG.getMachineFunction(), FrameIdx));
6793 
6794       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6795              "Expected an i32 store");
6796 
6797       RLI.Ptr = FIdx;
6798       RLI.Chain = Store;
6799       RLI.MPI =
6800           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6801       RLI.Alignment = 4;
6802     }
6803 
6804     MachineMemOperand *MMO =
6805       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6806                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6807     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6808     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6809                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6810                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6811                                  Ops, MVT::i32, MMO);
6812     if (ReusingLoad)
6813       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6814   } else {
6815     assert(Subtarget.isPPC64() &&
6816            "i32->FP without LFIWAX supported only on PPC64");
6817 
6818     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6819     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6820 
6821     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6822                                 Op.getOperand(0));
6823 
6824     // STD the extended value into the stack slot.
6825     SDValue Store = DAG.getStore(
6826         DAG.getEntryNode(), dl, Ext64, FIdx,
6827         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6828 
6829     // Load the value as a double.
6830     Ld = DAG.getLoad(
6831         MVT::f64, dl, Store, FIdx,
6832         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6833   }
6834 
6835   // FCFID it and return it.
6836   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6837   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6838     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6839                      DAG.getIntPtrConstant(0, dl));
6840   return FP;
6841 }
6842 
6843 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6844                                             SelectionDAG &DAG) const {
6845   SDLoc dl(Op);
6846   /*
6847    The rounding mode is in bits 30:31 of FPSR, and has the following
6848    settings:
6849      00 Round to nearest
6850      01 Round to 0
6851      10 Round to +inf
6852      11 Round to -inf
6853 
6854   FLT_ROUNDS, on the other hand, expects the following:
6855     -1 Undefined
6856      0 Round to 0
6857      1 Round to nearest
6858      2 Round to +inf
6859      3 Round to -inf
6860 
6861   To perform the conversion, we do:
6862     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6863   */
6864 
6865   MachineFunction &MF = DAG.getMachineFunction();
6866   EVT VT = Op.getValueType();
6867   EVT PtrVT = getPointerTy(MF.getDataLayout());
6868 
6869   // Save FP Control Word to register
6870   EVT NodeTys[] = {
6871     MVT::f64,    // return register
6872     MVT::Glue    // unused in this context
6873   };
6874   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6875 
6876   // Save FP register to stack slot
6877   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
6878   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6879   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
6880                                MachinePointerInfo());
6881 
6882   // Load FP Control Word from low 32 bits of stack slot.
6883   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6884   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6885   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
6886 
6887   // Transform as necessary
6888   SDValue CWD1 =
6889     DAG.getNode(ISD::AND, dl, MVT::i32,
6890                 CWD, DAG.getConstant(3, dl, MVT::i32));
6891   SDValue CWD2 =
6892     DAG.getNode(ISD::SRL, dl, MVT::i32,
6893                 DAG.getNode(ISD::AND, dl, MVT::i32,
6894                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6895                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6896                             DAG.getConstant(3, dl, MVT::i32)),
6897                 DAG.getConstant(1, dl, MVT::i32));
6898 
6899   SDValue RetVal =
6900     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6901 
6902   return DAG.getNode((VT.getSizeInBits() < 16 ?
6903                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6904 }
6905 
6906 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6907   EVT VT = Op.getValueType();
6908   unsigned BitWidth = VT.getSizeInBits();
6909   SDLoc dl(Op);
6910   assert(Op.getNumOperands() == 3 &&
6911          VT == Op.getOperand(1).getValueType() &&
6912          "Unexpected SHL!");
6913 
6914   // Expand into a bunch of logical ops.  Note that these ops
6915   // depend on the PPC behavior for oversized shift amounts.
6916   SDValue Lo = Op.getOperand(0);
6917   SDValue Hi = Op.getOperand(1);
6918   SDValue Amt = Op.getOperand(2);
6919   EVT AmtVT = Amt.getValueType();
6920 
6921   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6922                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6923   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6924   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6925   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6926   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6927                              DAG.getConstant(-BitWidth, dl, AmtVT));
6928   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6929   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6930   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6931   SDValue OutOps[] = { OutLo, OutHi };
6932   return DAG.getMergeValues(OutOps, dl);
6933 }
6934 
6935 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6936   EVT VT = Op.getValueType();
6937   SDLoc dl(Op);
6938   unsigned BitWidth = VT.getSizeInBits();
6939   assert(Op.getNumOperands() == 3 &&
6940          VT == Op.getOperand(1).getValueType() &&
6941          "Unexpected SRL!");
6942 
6943   // Expand into a bunch of logical ops.  Note that these ops
6944   // depend on the PPC behavior for oversized shift amounts.
6945   SDValue Lo = Op.getOperand(0);
6946   SDValue Hi = Op.getOperand(1);
6947   SDValue Amt = Op.getOperand(2);
6948   EVT AmtVT = Amt.getValueType();
6949 
6950   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6951                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6952   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6953   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6954   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6955   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6956                              DAG.getConstant(-BitWidth, dl, AmtVT));
6957   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6958   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6959   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6960   SDValue OutOps[] = { OutLo, OutHi };
6961   return DAG.getMergeValues(OutOps, dl);
6962 }
6963 
6964 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6965   SDLoc dl(Op);
6966   EVT VT = Op.getValueType();
6967   unsigned BitWidth = VT.getSizeInBits();
6968   assert(Op.getNumOperands() == 3 &&
6969          VT == Op.getOperand(1).getValueType() &&
6970          "Unexpected SRA!");
6971 
6972   // Expand into a bunch of logical ops, followed by a select_cc.
6973   SDValue Lo = Op.getOperand(0);
6974   SDValue Hi = Op.getOperand(1);
6975   SDValue Amt = Op.getOperand(2);
6976   EVT AmtVT = Amt.getValueType();
6977 
6978   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6979                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6980   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6981   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6982   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6983   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6984                              DAG.getConstant(-BitWidth, dl, AmtVT));
6985   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6986   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6987   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6988                                   Tmp4, Tmp6, ISD::SETLE);
6989   SDValue OutOps[] = { OutLo, OutHi };
6990   return DAG.getMergeValues(OutOps, dl);
6991 }
6992 
6993 //===----------------------------------------------------------------------===//
6994 // Vector related lowering.
6995 //
6996 
6997 /// BuildSplatI - Build a canonical splati of Val with an element size of
6998 /// SplatSize.  Cast the result to VT.
6999 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7000                            SelectionDAG &DAG, const SDLoc &dl) {
7001   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7002 
7003   static const MVT VTys[] = { // canonical VT to use for each size.
7004     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7005   };
7006 
7007   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7008 
7009   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7010   if (Val == -1)
7011     SplatSize = 1;
7012 
7013   EVT CanonicalVT = VTys[SplatSize-1];
7014 
7015   // Build a canonical splat for this value.
7016   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7017 }
7018 
7019 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7020 /// specified intrinsic ID.
7021 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7022                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7023   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7024   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7025                      DAG.getConstant(IID, dl, MVT::i32), Op);
7026 }
7027 
7028 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7029 /// specified intrinsic ID.
7030 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7031                                 SelectionDAG &DAG, const SDLoc &dl,
7032                                 EVT DestVT = MVT::Other) {
7033   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7034   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7035                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7036 }
7037 
7038 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7039 /// specified intrinsic ID.
7040 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7041                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7042                                 EVT DestVT = MVT::Other) {
7043   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7044   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7045                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7046 }
7047 
7048 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7049 /// amount.  The result has the specified value type.
7050 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7051                            SelectionDAG &DAG, const SDLoc &dl) {
7052   // Force LHS/RHS to be the right type.
7053   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7054   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7055 
7056   int Ops[16];
7057   for (unsigned i = 0; i != 16; ++i)
7058     Ops[i] = i + Amt;
7059   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7060   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7061 }
7062 
7063 // If this is a case we can't handle, return null and let the default
7064 // expansion code take care of it.  If we CAN select this case, and if it
7065 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7066 // this case more efficiently than a constant pool load, lower it to the
7067 // sequence of ops that should be used.
7068 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7069                                              SelectionDAG &DAG) const {
7070   SDLoc dl(Op);
7071   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7072   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7073 
7074   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7075     // We first build an i32 vector, load it into a QPX register,
7076     // then convert it to a floating-point vector and compare it
7077     // to a zero vector to get the boolean result.
7078     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7079     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7080     MachinePointerInfo PtrInfo =
7081         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7082     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7083     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7084 
7085     assert(BVN->getNumOperands() == 4 &&
7086       "BUILD_VECTOR for v4i1 does not have 4 operands");
7087 
7088     bool IsConst = true;
7089     for (unsigned i = 0; i < 4; ++i) {
7090       if (BVN->getOperand(i).isUndef()) continue;
7091       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7092         IsConst = false;
7093         break;
7094       }
7095     }
7096 
7097     if (IsConst) {
7098       Constant *One =
7099         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7100       Constant *NegOne =
7101         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7102 
7103       Constant *CV[4];
7104       for (unsigned i = 0; i < 4; ++i) {
7105         if (BVN->getOperand(i).isUndef())
7106           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7107         else if (isNullConstant(BVN->getOperand(i)))
7108           CV[i] = NegOne;
7109         else
7110           CV[i] = One;
7111       }
7112 
7113       Constant *CP = ConstantVector::get(CV);
7114       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7115                                           16 /* alignment */);
7116 
7117       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7118       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7119       return DAG.getMemIntrinsicNode(
7120           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7121           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7122     }
7123 
7124     SmallVector<SDValue, 4> Stores;
7125     for (unsigned i = 0; i < 4; ++i) {
7126       if (BVN->getOperand(i).isUndef()) continue;
7127 
7128       unsigned Offset = 4*i;
7129       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7130       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7131 
7132       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7133       if (StoreSize > 4) {
7134         Stores.push_back(
7135             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7136                               PtrInfo.getWithOffset(Offset), MVT::i32));
7137       } else {
7138         SDValue StoreValue = BVN->getOperand(i);
7139         if (StoreSize < 4)
7140           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7141 
7142         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7143                                       PtrInfo.getWithOffset(Offset)));
7144       }
7145     }
7146 
7147     SDValue StoreChain;
7148     if (!Stores.empty())
7149       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7150     else
7151       StoreChain = DAG.getEntryNode();
7152 
7153     // Now load from v4i32 into the QPX register; this will extend it to
7154     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7155     // is typed as v4f64 because the QPX register integer states are not
7156     // explicitly represented.
7157 
7158     SDValue Ops[] = {StoreChain,
7159                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7160                      FIdx};
7161     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7162 
7163     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7164       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7165     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7166       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7167       LoadedVect);
7168 
7169     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7170 
7171     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7172   }
7173 
7174   // All other QPX vectors are handled by generic code.
7175   if (Subtarget.hasQPX())
7176     return SDValue();
7177 
7178   // Check if this is a splat of a constant value.
7179   APInt APSplatBits, APSplatUndef;
7180   unsigned SplatBitSize;
7181   bool HasAnyUndefs;
7182   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7183                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7184       SplatBitSize > 32)
7185     return SDValue();
7186 
7187   unsigned SplatBits = APSplatBits.getZExtValue();
7188   unsigned SplatUndef = APSplatUndef.getZExtValue();
7189   unsigned SplatSize = SplatBitSize / 8;
7190 
7191   // First, handle single instruction cases.
7192 
7193   // All zeros?
7194   if (SplatBits == 0) {
7195     // Canonicalize all zero vectors to be v4i32.
7196     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7197       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7198       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7199     }
7200     return Op;
7201   }
7202 
7203   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7204   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7205                     (32-SplatBitSize));
7206   if (SextVal >= -16 && SextVal <= 15)
7207     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7208 
7209   // Two instruction sequences.
7210 
7211   // If this value is in the range [-32,30] and is even, use:
7212   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7213   // If this value is in the range [17,31] and is odd, use:
7214   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7215   // If this value is in the range [-31,-17] and is odd, use:
7216   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7217   // Note the last two are three-instruction sequences.
7218   if (SextVal >= -32 && SextVal <= 31) {
7219     // To avoid having these optimizations undone by constant folding,
7220     // we convert to a pseudo that will be expanded later into one of
7221     // the above forms.
7222     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7223     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7224               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7225     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7226     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7227     if (VT == Op.getValueType())
7228       return RetVal;
7229     else
7230       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7231   }
7232 
7233   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7234   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7235   // for fneg/fabs.
7236   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7237     // Make -1 and vspltisw -1:
7238     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7239 
7240     // Make the VSLW intrinsic, computing 0x8000_0000.
7241     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7242                                    OnesV, DAG, dl);
7243 
7244     // xor by OnesV to invert it.
7245     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7246     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7247   }
7248 
7249   // Check to see if this is a wide variety of vsplti*, binop self cases.
7250   static const signed char SplatCsts[] = {
7251     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7252     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7253   };
7254 
7255   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7256     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7257     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7258     int i = SplatCsts[idx];
7259 
7260     // Figure out what shift amount will be used by altivec if shifted by i in
7261     // this splat size.
7262     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7263 
7264     // vsplti + shl self.
7265     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7266       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7267       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7268         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7269         Intrinsic::ppc_altivec_vslw
7270       };
7271       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7272       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7273     }
7274 
7275     // vsplti + srl self.
7276     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7277       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7278       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7279         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7280         Intrinsic::ppc_altivec_vsrw
7281       };
7282       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7283       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7284     }
7285 
7286     // vsplti + sra self.
7287     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7288       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7289       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7290         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7291         Intrinsic::ppc_altivec_vsraw
7292       };
7293       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7294       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7295     }
7296 
7297     // vsplti + rol self.
7298     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7299                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7300       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7301       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7302         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7303         Intrinsic::ppc_altivec_vrlw
7304       };
7305       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7306       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7307     }
7308 
7309     // t = vsplti c, result = vsldoi t, t, 1
7310     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7311       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7312       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7313       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7314     }
7315     // t = vsplti c, result = vsldoi t, t, 2
7316     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7317       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7318       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7319       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7320     }
7321     // t = vsplti c, result = vsldoi t, t, 3
7322     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7323       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7324       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7325       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7326     }
7327   }
7328 
7329   return SDValue();
7330 }
7331 
7332 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7333 /// the specified operations to build the shuffle.
7334 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7335                                       SDValue RHS, SelectionDAG &DAG,
7336                                       const SDLoc &dl) {
7337   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7338   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7339   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7340 
7341   enum {
7342     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7343     OP_VMRGHW,
7344     OP_VMRGLW,
7345     OP_VSPLTISW0,
7346     OP_VSPLTISW1,
7347     OP_VSPLTISW2,
7348     OP_VSPLTISW3,
7349     OP_VSLDOI4,
7350     OP_VSLDOI8,
7351     OP_VSLDOI12
7352   };
7353 
7354   if (OpNum == OP_COPY) {
7355     if (LHSID == (1*9+2)*9+3) return LHS;
7356     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7357     return RHS;
7358   }
7359 
7360   SDValue OpLHS, OpRHS;
7361   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7362   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7363 
7364   int ShufIdxs[16];
7365   switch (OpNum) {
7366   default: llvm_unreachable("Unknown i32 permute!");
7367   case OP_VMRGHW:
7368     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7369     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7370     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7371     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7372     break;
7373   case OP_VMRGLW:
7374     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7375     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7376     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7377     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7378     break;
7379   case OP_VSPLTISW0:
7380     for (unsigned i = 0; i != 16; ++i)
7381       ShufIdxs[i] = (i&3)+0;
7382     break;
7383   case OP_VSPLTISW1:
7384     for (unsigned i = 0; i != 16; ++i)
7385       ShufIdxs[i] = (i&3)+4;
7386     break;
7387   case OP_VSPLTISW2:
7388     for (unsigned i = 0; i != 16; ++i)
7389       ShufIdxs[i] = (i&3)+8;
7390     break;
7391   case OP_VSPLTISW3:
7392     for (unsigned i = 0; i != 16; ++i)
7393       ShufIdxs[i] = (i&3)+12;
7394     break;
7395   case OP_VSLDOI4:
7396     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7397   case OP_VSLDOI8:
7398     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7399   case OP_VSLDOI12:
7400     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7401   }
7402   EVT VT = OpLHS.getValueType();
7403   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7404   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7405   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7406   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7407 }
7408 
7409 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7410 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7411 /// return the code it can be lowered into.  Worst case, it can always be
7412 /// lowered into a vperm.
7413 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7414                                                SelectionDAG &DAG) const {
7415   SDLoc dl(Op);
7416   SDValue V1 = Op.getOperand(0);
7417   SDValue V2 = Op.getOperand(1);
7418   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7419   EVT VT = Op.getValueType();
7420   bool isLittleEndian = Subtarget.isLittleEndian();
7421 
7422   unsigned ShiftElts, InsertAtByte;
7423   bool Swap;
7424   if (Subtarget.hasP9Vector() &&
7425       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7426                            isLittleEndian)) {
7427     if (Swap)
7428       std::swap(V1, V2);
7429     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7430     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7431     if (ShiftElts) {
7432       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7433                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7434       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7435                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7436       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7437     }
7438     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7439                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7440     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7441   }
7442 
7443   if (Subtarget.hasVSX()) {
7444     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7445       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7446       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7447       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7448                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7449       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7450     }
7451 
7452     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7453     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7454       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7455       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7456       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7457     }
7458 
7459   }
7460 
7461   if (Subtarget.hasQPX()) {
7462     if (VT.getVectorNumElements() != 4)
7463       return SDValue();
7464 
7465     if (V2.isUndef()) V2 = V1;
7466 
7467     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7468     if (AlignIdx != -1) {
7469       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7470                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7471     } else if (SVOp->isSplat()) {
7472       int SplatIdx = SVOp->getSplatIndex();
7473       if (SplatIdx >= 4) {
7474         std::swap(V1, V2);
7475         SplatIdx -= 4;
7476       }
7477 
7478       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7479                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7480     }
7481 
7482     // Lower this into a qvgpci/qvfperm pair.
7483 
7484     // Compute the qvgpci literal
7485     unsigned idx = 0;
7486     for (unsigned i = 0; i < 4; ++i) {
7487       int m = SVOp->getMaskElt(i);
7488       unsigned mm = m >= 0 ? (unsigned) m : i;
7489       idx |= mm << (3-i)*3;
7490     }
7491 
7492     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7493                              DAG.getConstant(idx, dl, MVT::i32));
7494     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7495   }
7496 
7497   // Cases that are handled by instructions that take permute immediates
7498   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7499   // selected by the instruction selector.
7500   if (V2.isUndef()) {
7501     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7502         PPC::isSplatShuffleMask(SVOp, 2) ||
7503         PPC::isSplatShuffleMask(SVOp, 4) ||
7504         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7505         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7506         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7507         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7508         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7509         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7510         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7511         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7512         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7513         (Subtarget.hasP8Altivec() && (
7514          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7515          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7516          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7517       return Op;
7518     }
7519   }
7520 
7521   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7522   // and produce a fixed permutation.  If any of these match, do not lower to
7523   // VPERM.
7524   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7525   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7526       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7527       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7528       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7529       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7530       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7531       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7532       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7533       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7534       (Subtarget.hasP8Altivec() && (
7535        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7536        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7537        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7538     return Op;
7539 
7540   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7541   // perfect shuffle table to emit an optimal matching sequence.
7542   ArrayRef<int> PermMask = SVOp->getMask();
7543 
7544   unsigned PFIndexes[4];
7545   bool isFourElementShuffle = true;
7546   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7547     unsigned EltNo = 8;   // Start out undef.
7548     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7549       if (PermMask[i*4+j] < 0)
7550         continue;   // Undef, ignore it.
7551 
7552       unsigned ByteSource = PermMask[i*4+j];
7553       if ((ByteSource & 3) != j) {
7554         isFourElementShuffle = false;
7555         break;
7556       }
7557 
7558       if (EltNo == 8) {
7559         EltNo = ByteSource/4;
7560       } else if (EltNo != ByteSource/4) {
7561         isFourElementShuffle = false;
7562         break;
7563       }
7564     }
7565     PFIndexes[i] = EltNo;
7566   }
7567 
7568   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7569   // perfect shuffle vector to determine if it is cost effective to do this as
7570   // discrete instructions, or whether we should use a vperm.
7571   // For now, we skip this for little endian until such time as we have a
7572   // little-endian perfect shuffle table.
7573   if (isFourElementShuffle && !isLittleEndian) {
7574     // Compute the index in the perfect shuffle table.
7575     unsigned PFTableIndex =
7576       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7577 
7578     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7579     unsigned Cost  = (PFEntry >> 30);
7580 
7581     // Determining when to avoid vperm is tricky.  Many things affect the cost
7582     // of vperm, particularly how many times the perm mask needs to be computed.
7583     // For example, if the perm mask can be hoisted out of a loop or is already
7584     // used (perhaps because there are multiple permutes with the same shuffle
7585     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7586     // the loop requires an extra register.
7587     //
7588     // As a compromise, we only emit discrete instructions if the shuffle can be
7589     // generated in 3 or fewer operations.  When we have loop information
7590     // available, if this block is within a loop, we should avoid using vperm
7591     // for 3-operation perms and use a constant pool load instead.
7592     if (Cost < 3)
7593       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7594   }
7595 
7596   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7597   // vector that will get spilled to the constant pool.
7598   if (V2.isUndef()) V2 = V1;
7599 
7600   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7601   // that it is in input element units, not in bytes.  Convert now.
7602 
7603   // For little endian, the order of the input vectors is reversed, and
7604   // the permutation mask is complemented with respect to 31.  This is
7605   // necessary to produce proper semantics with the big-endian-biased vperm
7606   // instruction.
7607   EVT EltVT = V1.getValueType().getVectorElementType();
7608   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7609 
7610   SmallVector<SDValue, 16> ResultMask;
7611   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7612     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7613 
7614     for (unsigned j = 0; j != BytesPerElement; ++j)
7615       if (isLittleEndian)
7616         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7617                                              dl, MVT::i32));
7618       else
7619         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7620                                              MVT::i32));
7621   }
7622 
7623   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7624   if (isLittleEndian)
7625     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7626                        V2, V1, VPermMask);
7627   else
7628     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7629                        V1, V2, VPermMask);
7630 }
7631 
7632 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7633 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7634 /// information about the intrinsic.
7635 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7636                                  bool &isDot, const PPCSubtarget &Subtarget) {
7637   unsigned IntrinsicID =
7638     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7639   CompareOpc = -1;
7640   isDot = false;
7641   switch (IntrinsicID) {
7642   default: return false;
7643     // Comparison predicates.
7644   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7645   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7646   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7647   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7648   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7649   case Intrinsic::ppc_altivec_vcmpequd_p:
7650     if (Subtarget.hasP8Altivec()) {
7651       CompareOpc = 199;
7652       isDot = 1;
7653     } else
7654       return false;
7655 
7656     break;
7657   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7658   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7659   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7660   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7661   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7662   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7663     if (Subtarget.hasP8Altivec()) {
7664       CompareOpc = 967;
7665       isDot = 1;
7666     } else
7667       return false;
7668 
7669     break;
7670   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7671   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7672   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7673   case Intrinsic::ppc_altivec_vcmpgtud_p:
7674     if (Subtarget.hasP8Altivec()) {
7675       CompareOpc = 711;
7676       isDot = 1;
7677     } else
7678       return false;
7679 
7680     break;
7681     // VSX predicate comparisons use the same infrastructure
7682   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7683   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7684   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7685   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7686   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7687   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7688     if (Subtarget.hasVSX()) {
7689       switch (IntrinsicID) {
7690       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7691       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7692       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7693       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7694       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7695       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7696       }
7697       isDot = 1;
7698     }
7699     else
7700       return false;
7701 
7702     break;
7703 
7704     // Normal Comparisons.
7705   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7706   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7707   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7708   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7709   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7710   case Intrinsic::ppc_altivec_vcmpequd:
7711     if (Subtarget.hasP8Altivec()) {
7712       CompareOpc = 199;
7713       isDot = 0;
7714     } else
7715       return false;
7716 
7717     break;
7718   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7719   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7720   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7721   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7722   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7723   case Intrinsic::ppc_altivec_vcmpgtsd:
7724     if (Subtarget.hasP8Altivec()) {
7725       CompareOpc = 967;
7726       isDot = 0;
7727     } else
7728       return false;
7729 
7730     break;
7731   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7732   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7733   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7734   case Intrinsic::ppc_altivec_vcmpgtud:
7735     if (Subtarget.hasP8Altivec()) {
7736       CompareOpc = 711;
7737       isDot = 0;
7738     } else
7739       return false;
7740 
7741     break;
7742   }
7743   return true;
7744 }
7745 
7746 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7747 /// lower, do it, otherwise return null.
7748 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7749                                                    SelectionDAG &DAG) const {
7750   unsigned IntrinsicID =
7751     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7752 
7753   if (IntrinsicID == Intrinsic::thread_pointer) {
7754     // Reads the thread pointer register, used for __builtin_thread_pointer.
7755     bool is64bit = Subtarget.isPPC64();
7756     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7757                            is64bit ? MVT::i64 : MVT::i32);
7758   }
7759 
7760   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7761   // opcode number of the comparison.
7762   SDLoc dl(Op);
7763   int CompareOpc;
7764   bool isDot;
7765   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7766     return SDValue();    // Don't custom lower most intrinsics.
7767 
7768   // If this is a non-dot comparison, make the VCMP node and we are done.
7769   if (!isDot) {
7770     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7771                               Op.getOperand(1), Op.getOperand(2),
7772                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7773     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7774   }
7775 
7776   // Create the PPCISD altivec 'dot' comparison node.
7777   SDValue Ops[] = {
7778     Op.getOperand(2),  // LHS
7779     Op.getOperand(3),  // RHS
7780     DAG.getConstant(CompareOpc, dl, MVT::i32)
7781   };
7782   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7783   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7784 
7785   // Now that we have the comparison, emit a copy from the CR to a GPR.
7786   // This is flagged to the above dot comparison.
7787   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7788                                 DAG.getRegister(PPC::CR6, MVT::i32),
7789                                 CompNode.getValue(1));
7790 
7791   // Unpack the result based on how the target uses it.
7792   unsigned BitNo;   // Bit # of CR6.
7793   bool InvertBit;   // Invert result?
7794   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7795   default:  // Can't happen, don't crash on invalid number though.
7796   case 0:   // Return the value of the EQ bit of CR6.
7797     BitNo = 0; InvertBit = false;
7798     break;
7799   case 1:   // Return the inverted value of the EQ bit of CR6.
7800     BitNo = 0; InvertBit = true;
7801     break;
7802   case 2:   // Return the value of the LT bit of CR6.
7803     BitNo = 2; InvertBit = false;
7804     break;
7805   case 3:   // Return the inverted value of the LT bit of CR6.
7806     BitNo = 2; InvertBit = true;
7807     break;
7808   }
7809 
7810   // Shift the bit into the low position.
7811   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7812                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7813   // Isolate the bit.
7814   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7815                       DAG.getConstant(1, dl, MVT::i32));
7816 
7817   // If we are supposed to, toggle the bit.
7818   if (InvertBit)
7819     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7820                         DAG.getConstant(1, dl, MVT::i32));
7821   return Flags;
7822 }
7823 
7824 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7825                                                   SelectionDAG &DAG) const {
7826   SDLoc dl(Op);
7827   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7828   // instructions), but for smaller types, we need to first extend up to v2i32
7829   // before doing going farther.
7830   if (Op.getValueType() == MVT::v2i64) {
7831     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7832     if (ExtVT != MVT::v2i32) {
7833       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7834       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7835                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7836                                         ExtVT.getVectorElementType(), 4)));
7837       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7838       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7839                        DAG.getValueType(MVT::v2i32));
7840     }
7841 
7842     return Op;
7843   }
7844 
7845   return SDValue();
7846 }
7847 
7848 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7849                                                    SelectionDAG &DAG) const {
7850   SDLoc dl(Op);
7851   // Create a stack slot that is 16-byte aligned.
7852   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7853   int FrameIdx = MFI.CreateStackObject(16, 16, false);
7854   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7855   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7856 
7857   // Store the input value into Value#0 of the stack slot.
7858   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7859                                MachinePointerInfo());
7860   // Load it out.
7861   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
7862 }
7863 
7864 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7865                                                    SelectionDAG &DAG) const {
7866   SDLoc dl(Op);
7867   SDNode *N = Op.getNode();
7868 
7869   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7870          "Unknown extract_vector_elt type");
7871 
7872   SDValue Value = N->getOperand(0);
7873 
7874   // The first part of this is like the store lowering except that we don't
7875   // need to track the chain.
7876 
7877   // The values are now known to be -1 (false) or 1 (true). To convert this
7878   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7879   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7880   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7881 
7882   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7883   // understand how to form the extending load.
7884   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7885 
7886   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7887 
7888   // Now convert to an integer and store.
7889   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7890     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7891     Value);
7892 
7893   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7894   int FrameIdx = MFI.CreateStackObject(16, 16, false);
7895   MachinePointerInfo PtrInfo =
7896       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7897   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7898   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7899 
7900   SDValue StoreChain = DAG.getEntryNode();
7901   SDValue Ops[] = {StoreChain,
7902                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7903                    Value, FIdx};
7904   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7905 
7906   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7907     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7908 
7909   // Extract the value requested.
7910   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7911   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7912   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7913 
7914   SDValue IntVal =
7915       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
7916 
7917   if (!Subtarget.useCRBits())
7918     return IntVal;
7919 
7920   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7921 }
7922 
7923 /// Lowering for QPX v4i1 loads
7924 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7925                                            SelectionDAG &DAG) const {
7926   SDLoc dl(Op);
7927   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7928   SDValue LoadChain = LN->getChain();
7929   SDValue BasePtr = LN->getBasePtr();
7930 
7931   if (Op.getValueType() == MVT::v4f64 ||
7932       Op.getValueType() == MVT::v4f32) {
7933     EVT MemVT = LN->getMemoryVT();
7934     unsigned Alignment = LN->getAlignment();
7935 
7936     // If this load is properly aligned, then it is legal.
7937     if (Alignment >= MemVT.getStoreSize())
7938       return Op;
7939 
7940     EVT ScalarVT = Op.getValueType().getScalarType(),
7941         ScalarMemVT = MemVT.getScalarType();
7942     unsigned Stride = ScalarMemVT.getStoreSize();
7943 
7944     SDValue Vals[4], LoadChains[4];
7945     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7946       SDValue Load;
7947       if (ScalarVT != ScalarMemVT)
7948         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7949                               BasePtr,
7950                               LN->getPointerInfo().getWithOffset(Idx * Stride),
7951                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
7952                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
7953       else
7954         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7955                            LN->getPointerInfo().getWithOffset(Idx * Stride),
7956                            MinAlign(Alignment, Idx * Stride),
7957                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
7958 
7959       if (Idx == 0 && LN->isIndexed()) {
7960         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7961                "Unknown addressing mode on vector load");
7962         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7963                                   LN->getAddressingMode());
7964       }
7965 
7966       Vals[Idx] = Load;
7967       LoadChains[Idx] = Load.getValue(1);
7968 
7969       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7970                             DAG.getConstant(Stride, dl,
7971                                             BasePtr.getValueType()));
7972     }
7973 
7974     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7975     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7976 
7977     if (LN->isIndexed()) {
7978       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7979       return DAG.getMergeValues(RetOps, dl);
7980     }
7981 
7982     SDValue RetOps[] = { Value, TF };
7983     return DAG.getMergeValues(RetOps, dl);
7984   }
7985 
7986   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7987   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7988 
7989   // To lower v4i1 from a byte array, we load the byte elements of the
7990   // vector and then reuse the BUILD_VECTOR logic.
7991 
7992   SDValue VectElmts[4], VectElmtChains[4];
7993   for (unsigned i = 0; i < 4; ++i) {
7994     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7995     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7996 
7997     VectElmts[i] = DAG.getExtLoad(
7998         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
7999         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8000         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8001     VectElmtChains[i] = VectElmts[i].getValue(1);
8002   }
8003 
8004   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8005   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8006 
8007   SDValue RVals[] = { Value, LoadChain };
8008   return DAG.getMergeValues(RVals, dl);
8009 }
8010 
8011 /// Lowering for QPX v4i1 stores
8012 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8013                                             SelectionDAG &DAG) const {
8014   SDLoc dl(Op);
8015   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8016   SDValue StoreChain = SN->getChain();
8017   SDValue BasePtr = SN->getBasePtr();
8018   SDValue Value = SN->getValue();
8019 
8020   if (Value.getValueType() == MVT::v4f64 ||
8021       Value.getValueType() == MVT::v4f32) {
8022     EVT MemVT = SN->getMemoryVT();
8023     unsigned Alignment = SN->getAlignment();
8024 
8025     // If this store is properly aligned, then it is legal.
8026     if (Alignment >= MemVT.getStoreSize())
8027       return Op;
8028 
8029     EVT ScalarVT = Value.getValueType().getScalarType(),
8030         ScalarMemVT = MemVT.getScalarType();
8031     unsigned Stride = ScalarMemVT.getStoreSize();
8032 
8033     SDValue Stores[4];
8034     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8035       SDValue Ex = DAG.getNode(
8036           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8037           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8038       SDValue Store;
8039       if (ScalarVT != ScalarMemVT)
8040         Store =
8041             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8042                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8043                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8044                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8045       else
8046         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8047                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8048                              MinAlign(Alignment, Idx * Stride),
8049                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8050 
8051       if (Idx == 0 && SN->isIndexed()) {
8052         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8053                "Unknown addressing mode on vector store");
8054         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8055                                     SN->getAddressingMode());
8056       }
8057 
8058       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8059                             DAG.getConstant(Stride, dl,
8060                                             BasePtr.getValueType()));
8061       Stores[Idx] = Store;
8062     }
8063 
8064     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8065 
8066     if (SN->isIndexed()) {
8067       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8068       return DAG.getMergeValues(RetOps, dl);
8069     }
8070 
8071     return TF;
8072   }
8073 
8074   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8075   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8076 
8077   // The values are now known to be -1 (false) or 1 (true). To convert this
8078   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8079   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8080   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8081 
8082   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8083   // understand how to form the extending load.
8084   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8085 
8086   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8087 
8088   // Now convert to an integer and store.
8089   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8090     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8091     Value);
8092 
8093   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8094   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8095   MachinePointerInfo PtrInfo =
8096       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8097   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8098   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8099 
8100   SDValue Ops[] = {StoreChain,
8101                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8102                    Value, FIdx};
8103   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8104 
8105   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8106     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8107 
8108   // Move data into the byte array.
8109   SDValue Loads[4], LoadChains[4];
8110   for (unsigned i = 0; i < 4; ++i) {
8111     unsigned Offset = 4*i;
8112     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8113     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8114 
8115     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8116                            PtrInfo.getWithOffset(Offset));
8117     LoadChains[i] = Loads[i].getValue(1);
8118   }
8119 
8120   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8121 
8122   SDValue Stores[4];
8123   for (unsigned i = 0; i < 4; ++i) {
8124     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8125     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8126 
8127     Stores[i] = DAG.getTruncStore(
8128         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8129         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8130         SN->getAAInfo());
8131   }
8132 
8133   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8134 
8135   return StoreChain;
8136 }
8137 
8138 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8139   SDLoc dl(Op);
8140   if (Op.getValueType() == MVT::v4i32) {
8141     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8142 
8143     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8144     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8145 
8146     SDValue RHSSwap =   // = vrlw RHS, 16
8147       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8148 
8149     // Shrinkify inputs to v8i16.
8150     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8151     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8152     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8153 
8154     // Low parts multiplied together, generating 32-bit results (we ignore the
8155     // top parts).
8156     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8157                                         LHS, RHS, DAG, dl, MVT::v4i32);
8158 
8159     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8160                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8161     // Shift the high parts up 16 bits.
8162     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8163                               Neg16, DAG, dl);
8164     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8165   } else if (Op.getValueType() == MVT::v8i16) {
8166     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8167 
8168     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8169 
8170     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8171                             LHS, RHS, Zero, DAG, dl);
8172   } else if (Op.getValueType() == MVT::v16i8) {
8173     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8174     bool isLittleEndian = Subtarget.isLittleEndian();
8175 
8176     // Multiply the even 8-bit parts, producing 16-bit sums.
8177     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8178                                            LHS, RHS, DAG, dl, MVT::v8i16);
8179     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8180 
8181     // Multiply the odd 8-bit parts, producing 16-bit sums.
8182     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8183                                           LHS, RHS, DAG, dl, MVT::v8i16);
8184     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8185 
8186     // Merge the results together.  Because vmuleub and vmuloub are
8187     // instructions with a big-endian bias, we must reverse the
8188     // element numbering and reverse the meaning of "odd" and "even"
8189     // when generating little endian code.
8190     int Ops[16];
8191     for (unsigned i = 0; i != 8; ++i) {
8192       if (isLittleEndian) {
8193         Ops[i*2  ] = 2*i;
8194         Ops[i*2+1] = 2*i+16;
8195       } else {
8196         Ops[i*2  ] = 2*i+1;
8197         Ops[i*2+1] = 2*i+1+16;
8198       }
8199     }
8200     if (isLittleEndian)
8201       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8202     else
8203       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8204   } else {
8205     llvm_unreachable("Unknown mul to lower!");
8206   }
8207 }
8208 
8209 /// LowerOperation - Provide custom lowering hooks for some operations.
8210 ///
8211 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8212   switch (Op.getOpcode()) {
8213   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8214   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8215   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8216   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8217   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8218   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8219   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8220   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8221   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8222   case ISD::VASTART:
8223     return LowerVASTART(Op, DAG);
8224 
8225   case ISD::VAARG:
8226     return LowerVAARG(Op, DAG);
8227 
8228   case ISD::VACOPY:
8229     return LowerVACOPY(Op, DAG);
8230 
8231   case ISD::STACKRESTORE:
8232     return LowerSTACKRESTORE(Op, DAG);
8233 
8234   case ISD::DYNAMIC_STACKALLOC:
8235     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8236 
8237   case ISD::GET_DYNAMIC_AREA_OFFSET:
8238     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8239 
8240   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8241   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8242 
8243   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8244   case ISD::STORE:              return LowerSTORE(Op, DAG);
8245   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8246   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8247   case ISD::FP_TO_UINT:
8248   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8249                                                       SDLoc(Op));
8250   case ISD::UINT_TO_FP:
8251   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8252   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8253 
8254   // Lower 64-bit shifts.
8255   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8256   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8257   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8258 
8259   // Vector-related lowering.
8260   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8261   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8262   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8263   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8264   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8265   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8266   case ISD::MUL:                return LowerMUL(Op, DAG);
8267 
8268   // For counter-based loop handling.
8269   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8270 
8271   // Frame & Return address.
8272   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8273   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8274   }
8275 }
8276 
8277 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8278                                            SmallVectorImpl<SDValue>&Results,
8279                                            SelectionDAG &DAG) const {
8280   SDLoc dl(N);
8281   switch (N->getOpcode()) {
8282   default:
8283     llvm_unreachable("Do not know how to custom type legalize this operation!");
8284   case ISD::READCYCLECOUNTER: {
8285     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8286     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8287 
8288     Results.push_back(RTB);
8289     Results.push_back(RTB.getValue(1));
8290     Results.push_back(RTB.getValue(2));
8291     break;
8292   }
8293   case ISD::INTRINSIC_W_CHAIN: {
8294     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8295         Intrinsic::ppc_is_decremented_ctr_nonzero)
8296       break;
8297 
8298     assert(N->getValueType(0) == MVT::i1 &&
8299            "Unexpected result type for CTR decrement intrinsic");
8300     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8301                                  N->getValueType(0));
8302     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8303     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8304                                  N->getOperand(1));
8305 
8306     Results.push_back(NewInt);
8307     Results.push_back(NewInt.getValue(1));
8308     break;
8309   }
8310   case ISD::VAARG: {
8311     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8312       return;
8313 
8314     EVT VT = N->getValueType(0);
8315 
8316     if (VT == MVT::i64) {
8317       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8318 
8319       Results.push_back(NewNode);
8320       Results.push_back(NewNode.getValue(1));
8321     }
8322     return;
8323   }
8324   case ISD::FP_ROUND_INREG: {
8325     assert(N->getValueType(0) == MVT::ppcf128);
8326     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8327     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8328                              MVT::f64, N->getOperand(0),
8329                              DAG.getIntPtrConstant(0, dl));
8330     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8331                              MVT::f64, N->getOperand(0),
8332                              DAG.getIntPtrConstant(1, dl));
8333 
8334     // Add the two halves of the long double in round-to-zero mode.
8335     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8336 
8337     // We know the low half is about to be thrown away, so just use something
8338     // convenient.
8339     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8340                                 FPreg, FPreg));
8341     return;
8342   }
8343   case ISD::FP_TO_SINT:
8344   case ISD::FP_TO_UINT:
8345     // LowerFP_TO_INT() can only handle f32 and f64.
8346     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8347       return;
8348     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8349     return;
8350   }
8351 }
8352 
8353 //===----------------------------------------------------------------------===//
8354 //  Other Lowering Code
8355 //===----------------------------------------------------------------------===//
8356 
8357 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8358   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8359   Function *Func = Intrinsic::getDeclaration(M, Id);
8360   return Builder.CreateCall(Func, {});
8361 }
8362 
8363 // The mappings for emitLeading/TrailingFence is taken from
8364 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8365 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8366                                          AtomicOrdering Ord, bool IsStore,
8367                                          bool IsLoad) const {
8368   if (Ord == AtomicOrdering::SequentiallyConsistent)
8369     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8370   if (isReleaseOrStronger(Ord))
8371     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8372   return nullptr;
8373 }
8374 
8375 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8376                                           AtomicOrdering Ord, bool IsStore,
8377                                           bool IsLoad) const {
8378   if (IsLoad && isAcquireOrStronger(Ord))
8379     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8380   // FIXME: this is too conservative, a dependent branch + isync is enough.
8381   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8382   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8383   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8384   return nullptr;
8385 }
8386 
8387 MachineBasicBlock *
8388 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8389                                     unsigned AtomicSize,
8390                                     unsigned BinOpcode,
8391                                     unsigned CmpOpcode,
8392                                     unsigned CmpPred) const {
8393   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8394   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8395 
8396   auto LoadMnemonic = PPC::LDARX;
8397   auto StoreMnemonic = PPC::STDCX;
8398   switch (AtomicSize) {
8399   default:
8400     llvm_unreachable("Unexpected size of atomic entity");
8401   case 1:
8402     LoadMnemonic = PPC::LBARX;
8403     StoreMnemonic = PPC::STBCX;
8404     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8405     break;
8406   case 2:
8407     LoadMnemonic = PPC::LHARX;
8408     StoreMnemonic = PPC::STHCX;
8409     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8410     break;
8411   case 4:
8412     LoadMnemonic = PPC::LWARX;
8413     StoreMnemonic = PPC::STWCX;
8414     break;
8415   case 8:
8416     LoadMnemonic = PPC::LDARX;
8417     StoreMnemonic = PPC::STDCX;
8418     break;
8419   }
8420 
8421   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8422   MachineFunction *F = BB->getParent();
8423   MachineFunction::iterator It = ++BB->getIterator();
8424 
8425   unsigned dest = MI.getOperand(0).getReg();
8426   unsigned ptrA = MI.getOperand(1).getReg();
8427   unsigned ptrB = MI.getOperand(2).getReg();
8428   unsigned incr = MI.getOperand(3).getReg();
8429   DebugLoc dl = MI.getDebugLoc();
8430 
8431   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8432   MachineBasicBlock *loop2MBB =
8433     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8434   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8435   F->insert(It, loopMBB);
8436   if (CmpOpcode)
8437     F->insert(It, loop2MBB);
8438   F->insert(It, exitMBB);
8439   exitMBB->splice(exitMBB->begin(), BB,
8440                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8441   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8442 
8443   MachineRegisterInfo &RegInfo = F->getRegInfo();
8444   unsigned TmpReg = (!BinOpcode) ? incr :
8445     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8446                                            : &PPC::GPRCRegClass);
8447 
8448   //  thisMBB:
8449   //   ...
8450   //   fallthrough --> loopMBB
8451   BB->addSuccessor(loopMBB);
8452 
8453   //  loopMBB:
8454   //   l[wd]arx dest, ptr
8455   //   add r0, dest, incr
8456   //   st[wd]cx. r0, ptr
8457   //   bne- loopMBB
8458   //   fallthrough --> exitMBB
8459 
8460   // For max/min...
8461   //  loopMBB:
8462   //   l[wd]arx dest, ptr
8463   //   cmpl?[wd] incr, dest
8464   //   bgt exitMBB
8465   //  loop2MBB:
8466   //   st[wd]cx. dest, ptr
8467   //   bne- loopMBB
8468   //   fallthrough --> exitMBB
8469 
8470   BB = loopMBB;
8471   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8472     .addReg(ptrA).addReg(ptrB);
8473   if (BinOpcode)
8474     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8475   if (CmpOpcode) {
8476     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8477       .addReg(incr).addReg(dest);
8478     BuildMI(BB, dl, TII->get(PPC::BCC))
8479       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8480     BB->addSuccessor(loop2MBB);
8481     BB->addSuccessor(exitMBB);
8482     BB = loop2MBB;
8483   }
8484   BuildMI(BB, dl, TII->get(StoreMnemonic))
8485     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8486   BuildMI(BB, dl, TII->get(PPC::BCC))
8487     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8488   BB->addSuccessor(loopMBB);
8489   BB->addSuccessor(exitMBB);
8490 
8491   //  exitMBB:
8492   //   ...
8493   BB = exitMBB;
8494   return BB;
8495 }
8496 
8497 MachineBasicBlock *
8498 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8499                                             MachineBasicBlock *BB,
8500                                             bool is8bit, // operation
8501                                             unsigned BinOpcode,
8502                                             unsigned CmpOpcode,
8503                                             unsigned CmpPred) const {
8504   // If we support part-word atomic mnemonics, just use them
8505   if (Subtarget.hasPartwordAtomics())
8506     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8507                             CmpOpcode, CmpPred);
8508 
8509   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8510   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8511   // In 64 bit mode we have to use 64 bits for addresses, even though the
8512   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8513   // registers without caring whether they're 32 or 64, but here we're
8514   // doing actual arithmetic on the addresses.
8515   bool is64bit = Subtarget.isPPC64();
8516   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8517 
8518   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8519   MachineFunction *F = BB->getParent();
8520   MachineFunction::iterator It = ++BB->getIterator();
8521 
8522   unsigned dest = MI.getOperand(0).getReg();
8523   unsigned ptrA = MI.getOperand(1).getReg();
8524   unsigned ptrB = MI.getOperand(2).getReg();
8525   unsigned incr = MI.getOperand(3).getReg();
8526   DebugLoc dl = MI.getDebugLoc();
8527 
8528   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8529   MachineBasicBlock *loop2MBB =
8530     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8531   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8532   F->insert(It, loopMBB);
8533   if (CmpOpcode)
8534     F->insert(It, loop2MBB);
8535   F->insert(It, exitMBB);
8536   exitMBB->splice(exitMBB->begin(), BB,
8537                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8538   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8539 
8540   MachineRegisterInfo &RegInfo = F->getRegInfo();
8541   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8542                                           : &PPC::GPRCRegClass;
8543   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8544   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8545   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8546   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8547   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8548   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8549   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8550   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8551   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8552   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8553   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8554   unsigned Ptr1Reg;
8555   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8556 
8557   //  thisMBB:
8558   //   ...
8559   //   fallthrough --> loopMBB
8560   BB->addSuccessor(loopMBB);
8561 
8562   // The 4-byte load must be aligned, while a char or short may be
8563   // anywhere in the word.  Hence all this nasty bookkeeping code.
8564   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8565   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8566   //   xori shift, shift1, 24 [16]
8567   //   rlwinm ptr, ptr1, 0, 0, 29
8568   //   slw incr2, incr, shift
8569   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8570   //   slw mask, mask2, shift
8571   //  loopMBB:
8572   //   lwarx tmpDest, ptr
8573   //   add tmp, tmpDest, incr2
8574   //   andc tmp2, tmpDest, mask
8575   //   and tmp3, tmp, mask
8576   //   or tmp4, tmp3, tmp2
8577   //   stwcx. tmp4, ptr
8578   //   bne- loopMBB
8579   //   fallthrough --> exitMBB
8580   //   srw dest, tmpDest, shift
8581   if (ptrA != ZeroReg) {
8582     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8583     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8584       .addReg(ptrA).addReg(ptrB);
8585   } else {
8586     Ptr1Reg = ptrB;
8587   }
8588   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8589       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8590   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8591       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8592   if (is64bit)
8593     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8594       .addReg(Ptr1Reg).addImm(0).addImm(61);
8595   else
8596     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8597       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8598   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8599       .addReg(incr).addReg(ShiftReg);
8600   if (is8bit)
8601     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8602   else {
8603     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8604     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8605   }
8606   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8607       .addReg(Mask2Reg).addReg(ShiftReg);
8608 
8609   BB = loopMBB;
8610   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8611     .addReg(ZeroReg).addReg(PtrReg);
8612   if (BinOpcode)
8613     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8614       .addReg(Incr2Reg).addReg(TmpDestReg);
8615   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8616     .addReg(TmpDestReg).addReg(MaskReg);
8617   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8618     .addReg(TmpReg).addReg(MaskReg);
8619   if (CmpOpcode) {
8620     // For unsigned comparisons, we can directly compare the shifted values.
8621     // For signed comparisons we shift and sign extend.
8622     unsigned SReg = RegInfo.createVirtualRegister(RC);
8623     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
8624       .addReg(TmpDestReg).addReg(MaskReg);
8625     unsigned ValueReg = SReg;
8626     unsigned CmpReg = Incr2Reg;
8627     if (CmpOpcode == PPC::CMPW) {
8628       ValueReg = RegInfo.createVirtualRegister(RC);
8629       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
8630         .addReg(SReg).addReg(ShiftReg);
8631       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
8632       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
8633         .addReg(ValueReg);
8634       ValueReg = ValueSReg;
8635       CmpReg = incr;
8636     }
8637     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8638       .addReg(CmpReg).addReg(ValueReg);
8639     BuildMI(BB, dl, TII->get(PPC::BCC))
8640       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8641     BB->addSuccessor(loop2MBB);
8642     BB->addSuccessor(exitMBB);
8643     BB = loop2MBB;
8644   }
8645   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8646     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8647   BuildMI(BB, dl, TII->get(PPC::STWCX))
8648     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8649   BuildMI(BB, dl, TII->get(PPC::BCC))
8650     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8651   BB->addSuccessor(loopMBB);
8652   BB->addSuccessor(exitMBB);
8653 
8654   //  exitMBB:
8655   //   ...
8656   BB = exitMBB;
8657   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8658     .addReg(ShiftReg);
8659   return BB;
8660 }
8661 
8662 llvm::MachineBasicBlock *
8663 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8664                                     MachineBasicBlock *MBB) const {
8665   DebugLoc DL = MI.getDebugLoc();
8666   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8667 
8668   MachineFunction *MF = MBB->getParent();
8669   MachineRegisterInfo &MRI = MF->getRegInfo();
8670 
8671   const BasicBlock *BB = MBB->getBasicBlock();
8672   MachineFunction::iterator I = ++MBB->getIterator();
8673 
8674   // Memory Reference
8675   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8676   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8677 
8678   unsigned DstReg = MI.getOperand(0).getReg();
8679   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8680   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8681   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8682   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8683 
8684   MVT PVT = getPointerTy(MF->getDataLayout());
8685   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8686          "Invalid Pointer Size!");
8687   // For v = setjmp(buf), we generate
8688   //
8689   // thisMBB:
8690   //  SjLjSetup mainMBB
8691   //  bl mainMBB
8692   //  v_restore = 1
8693   //  b sinkMBB
8694   //
8695   // mainMBB:
8696   //  buf[LabelOffset] = LR
8697   //  v_main = 0
8698   //
8699   // sinkMBB:
8700   //  v = phi(main, restore)
8701   //
8702 
8703   MachineBasicBlock *thisMBB = MBB;
8704   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8705   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8706   MF->insert(I, mainMBB);
8707   MF->insert(I, sinkMBB);
8708 
8709   MachineInstrBuilder MIB;
8710 
8711   // Transfer the remainder of BB and its successor edges to sinkMBB.
8712   sinkMBB->splice(sinkMBB->begin(), MBB,
8713                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8714   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8715 
8716   // Note that the structure of the jmp_buf used here is not compatible
8717   // with that used by libc, and is not designed to be. Specifically, it
8718   // stores only those 'reserved' registers that LLVM does not otherwise
8719   // understand how to spill. Also, by convention, by the time this
8720   // intrinsic is called, Clang has already stored the frame address in the
8721   // first slot of the buffer and stack address in the third. Following the
8722   // X86 target code, we'll store the jump address in the second slot. We also
8723   // need to save the TOC pointer (R2) to handle jumps between shared
8724   // libraries, and that will be stored in the fourth slot. The thread
8725   // identifier (R13) is not affected.
8726 
8727   // thisMBB:
8728   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8729   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8730   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8731 
8732   // Prepare IP either in reg.
8733   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8734   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8735   unsigned BufReg = MI.getOperand(1).getReg();
8736 
8737   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8738     setUsesTOCBasePtr(*MBB->getParent());
8739     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8740             .addReg(PPC::X2)
8741             .addImm(TOCOffset)
8742             .addReg(BufReg);
8743     MIB.setMemRefs(MMOBegin, MMOEnd);
8744   }
8745 
8746   // Naked functions never have a base pointer, and so we use r1. For all
8747   // other functions, this decision must be delayed until during PEI.
8748   unsigned BaseReg;
8749   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8750     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8751   else
8752     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8753 
8754   MIB = BuildMI(*thisMBB, MI, DL,
8755                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8756             .addReg(BaseReg)
8757             .addImm(BPOffset)
8758             .addReg(BufReg);
8759   MIB.setMemRefs(MMOBegin, MMOEnd);
8760 
8761   // Setup
8762   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8763   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8764   MIB.addRegMask(TRI->getNoPreservedMask());
8765 
8766   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8767 
8768   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8769           .addMBB(mainMBB);
8770   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8771 
8772   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8773   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8774 
8775   // mainMBB:
8776   //  mainDstReg = 0
8777   MIB =
8778       BuildMI(mainMBB, DL,
8779               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8780 
8781   // Store IP
8782   if (Subtarget.isPPC64()) {
8783     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8784             .addReg(LabelReg)
8785             .addImm(LabelOffset)
8786             .addReg(BufReg);
8787   } else {
8788     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8789             .addReg(LabelReg)
8790             .addImm(LabelOffset)
8791             .addReg(BufReg);
8792   }
8793 
8794   MIB.setMemRefs(MMOBegin, MMOEnd);
8795 
8796   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8797   mainMBB->addSuccessor(sinkMBB);
8798 
8799   // sinkMBB:
8800   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8801           TII->get(PPC::PHI), DstReg)
8802     .addReg(mainDstReg).addMBB(mainMBB)
8803     .addReg(restoreDstReg).addMBB(thisMBB);
8804 
8805   MI.eraseFromParent();
8806   return sinkMBB;
8807 }
8808 
8809 MachineBasicBlock *
8810 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8811                                      MachineBasicBlock *MBB) const {
8812   DebugLoc DL = MI.getDebugLoc();
8813   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8814 
8815   MachineFunction *MF = MBB->getParent();
8816   MachineRegisterInfo &MRI = MF->getRegInfo();
8817 
8818   // Memory Reference
8819   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8820   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8821 
8822   MVT PVT = getPointerTy(MF->getDataLayout());
8823   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8824          "Invalid Pointer Size!");
8825 
8826   const TargetRegisterClass *RC =
8827     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8828   unsigned Tmp = MRI.createVirtualRegister(RC);
8829   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8830   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8831   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8832   unsigned BP =
8833       (PVT == MVT::i64)
8834           ? PPC::X30
8835           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
8836                                                               : PPC::R30);
8837 
8838   MachineInstrBuilder MIB;
8839 
8840   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8841   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8842   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8843   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8844 
8845   unsigned BufReg = MI.getOperand(0).getReg();
8846 
8847   // Reload FP (the jumped-to function may not have had a
8848   // frame pointer, and if so, then its r31 will be restored
8849   // as necessary).
8850   if (PVT == MVT::i64) {
8851     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8852             .addImm(0)
8853             .addReg(BufReg);
8854   } else {
8855     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8856             .addImm(0)
8857             .addReg(BufReg);
8858   }
8859   MIB.setMemRefs(MMOBegin, MMOEnd);
8860 
8861   // Reload IP
8862   if (PVT == MVT::i64) {
8863     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8864             .addImm(LabelOffset)
8865             .addReg(BufReg);
8866   } else {
8867     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8868             .addImm(LabelOffset)
8869             .addReg(BufReg);
8870   }
8871   MIB.setMemRefs(MMOBegin, MMOEnd);
8872 
8873   // Reload SP
8874   if (PVT == MVT::i64) {
8875     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8876             .addImm(SPOffset)
8877             .addReg(BufReg);
8878   } else {
8879     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8880             .addImm(SPOffset)
8881             .addReg(BufReg);
8882   }
8883   MIB.setMemRefs(MMOBegin, MMOEnd);
8884 
8885   // Reload BP
8886   if (PVT == MVT::i64) {
8887     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8888             .addImm(BPOffset)
8889             .addReg(BufReg);
8890   } else {
8891     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8892             .addImm(BPOffset)
8893             .addReg(BufReg);
8894   }
8895   MIB.setMemRefs(MMOBegin, MMOEnd);
8896 
8897   // Reload TOC
8898   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8899     setUsesTOCBasePtr(*MBB->getParent());
8900     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8901             .addImm(TOCOffset)
8902             .addReg(BufReg);
8903 
8904     MIB.setMemRefs(MMOBegin, MMOEnd);
8905   }
8906 
8907   // Jump
8908   BuildMI(*MBB, MI, DL,
8909           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8910   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8911 
8912   MI.eraseFromParent();
8913   return MBB;
8914 }
8915 
8916 MachineBasicBlock *
8917 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8918                                                MachineBasicBlock *BB) const {
8919   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
8920       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8921     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8922         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8923       // Call lowering should have added an r2 operand to indicate a dependence
8924       // on the TOC base pointer value. It can't however, because there is no
8925       // way to mark the dependence as implicit there, and so the stackmap code
8926       // will confuse it with a regular operand. Instead, add the dependence
8927       // here.
8928       setUsesTOCBasePtr(*BB->getParent());
8929       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8930     }
8931 
8932     return emitPatchPoint(MI, BB);
8933   }
8934 
8935   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8936       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
8937     return emitEHSjLjSetJmp(MI, BB);
8938   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8939              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
8940     return emitEHSjLjLongJmp(MI, BB);
8941   }
8942 
8943   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8944 
8945   // To "insert" these instructions we actually have to insert their
8946   // control-flow patterns.
8947   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8948   MachineFunction::iterator It = ++BB->getIterator();
8949 
8950   MachineFunction *F = BB->getParent();
8951 
8952   if (Subtarget.hasISEL() &&
8953       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8954        MI.getOpcode() == PPC::SELECT_CC_I8 ||
8955        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
8956     SmallVector<MachineOperand, 2> Cond;
8957     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8958         MI.getOpcode() == PPC::SELECT_CC_I8)
8959       Cond.push_back(MI.getOperand(4));
8960     else
8961       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8962     Cond.push_back(MI.getOperand(1));
8963 
8964     DebugLoc dl = MI.getDebugLoc();
8965     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
8966                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
8967   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8968              MI.getOpcode() == PPC::SELECT_CC_I8 ||
8969              MI.getOpcode() == PPC::SELECT_CC_F4 ||
8970              MI.getOpcode() == PPC::SELECT_CC_F8 ||
8971              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
8972              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
8973              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
8974              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
8975              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
8976              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
8977              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
8978              MI.getOpcode() == PPC::SELECT_I4 ||
8979              MI.getOpcode() == PPC::SELECT_I8 ||
8980              MI.getOpcode() == PPC::SELECT_F4 ||
8981              MI.getOpcode() == PPC::SELECT_F8 ||
8982              MI.getOpcode() == PPC::SELECT_QFRC ||
8983              MI.getOpcode() == PPC::SELECT_QSRC ||
8984              MI.getOpcode() == PPC::SELECT_QBRC ||
8985              MI.getOpcode() == PPC::SELECT_VRRC ||
8986              MI.getOpcode() == PPC::SELECT_VSFRC ||
8987              MI.getOpcode() == PPC::SELECT_VSSRC ||
8988              MI.getOpcode() == PPC::SELECT_VSRC) {
8989     // The incoming instruction knows the destination vreg to set, the
8990     // condition code register to branch on, the true/false values to
8991     // select between, and a branch opcode to use.
8992 
8993     //  thisMBB:
8994     //  ...
8995     //   TrueVal = ...
8996     //   cmpTY ccX, r1, r2
8997     //   bCC copy1MBB
8998     //   fallthrough --> copy0MBB
8999     MachineBasicBlock *thisMBB = BB;
9000     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9001     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9002     DebugLoc dl = MI.getDebugLoc();
9003     F->insert(It, copy0MBB);
9004     F->insert(It, sinkMBB);
9005 
9006     // Transfer the remainder of BB and its successor edges to sinkMBB.
9007     sinkMBB->splice(sinkMBB->begin(), BB,
9008                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9009     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9010 
9011     // Next, add the true and fallthrough blocks as its successors.
9012     BB->addSuccessor(copy0MBB);
9013     BB->addSuccessor(sinkMBB);
9014 
9015     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9016         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9017         MI.getOpcode() == PPC::SELECT_QFRC ||
9018         MI.getOpcode() == PPC::SELECT_QSRC ||
9019         MI.getOpcode() == PPC::SELECT_QBRC ||
9020         MI.getOpcode() == PPC::SELECT_VRRC ||
9021         MI.getOpcode() == PPC::SELECT_VSFRC ||
9022         MI.getOpcode() == PPC::SELECT_VSSRC ||
9023         MI.getOpcode() == PPC::SELECT_VSRC) {
9024       BuildMI(BB, dl, TII->get(PPC::BC))
9025           .addReg(MI.getOperand(1).getReg())
9026           .addMBB(sinkMBB);
9027     } else {
9028       unsigned SelectPred = MI.getOperand(4).getImm();
9029       BuildMI(BB, dl, TII->get(PPC::BCC))
9030           .addImm(SelectPred)
9031           .addReg(MI.getOperand(1).getReg())
9032           .addMBB(sinkMBB);
9033     }
9034 
9035     //  copy0MBB:
9036     //   %FalseValue = ...
9037     //   # fallthrough to sinkMBB
9038     BB = copy0MBB;
9039 
9040     // Update machine-CFG edges
9041     BB->addSuccessor(sinkMBB);
9042 
9043     //  sinkMBB:
9044     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9045     //  ...
9046     BB = sinkMBB;
9047     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9048         .addReg(MI.getOperand(3).getReg())
9049         .addMBB(copy0MBB)
9050         .addReg(MI.getOperand(2).getReg())
9051         .addMBB(thisMBB);
9052   } else if (MI.getOpcode() == PPC::ReadTB) {
9053     // To read the 64-bit time-base register on a 32-bit target, we read the
9054     // two halves. Should the counter have wrapped while it was being read, we
9055     // need to try again.
9056     // ...
9057     // readLoop:
9058     // mfspr Rx,TBU # load from TBU
9059     // mfspr Ry,TB  # load from TB
9060     // mfspr Rz,TBU # load from TBU
9061     // cmpw crX,Rx,Rz # check if 'old'='new'
9062     // bne readLoop   # branch if they're not equal
9063     // ...
9064 
9065     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9066     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9067     DebugLoc dl = MI.getDebugLoc();
9068     F->insert(It, readMBB);
9069     F->insert(It, sinkMBB);
9070 
9071     // Transfer the remainder of BB and its successor edges to sinkMBB.
9072     sinkMBB->splice(sinkMBB->begin(), BB,
9073                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9074     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9075 
9076     BB->addSuccessor(readMBB);
9077     BB = readMBB;
9078 
9079     MachineRegisterInfo &RegInfo = F->getRegInfo();
9080     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9081     unsigned LoReg = MI.getOperand(0).getReg();
9082     unsigned HiReg = MI.getOperand(1).getReg();
9083 
9084     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9085     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9086     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9087 
9088     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9089 
9090     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9091       .addReg(HiReg).addReg(ReadAgainReg);
9092     BuildMI(BB, dl, TII->get(PPC::BCC))
9093       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9094 
9095     BB->addSuccessor(readMBB);
9096     BB->addSuccessor(sinkMBB);
9097   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9098     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9099   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9100     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9101   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9102     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9103   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9104     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9105 
9106   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9107     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9108   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9109     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9110   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9111     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9112   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9113     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9114 
9115   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9116     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9117   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9118     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9119   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9120     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9121   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9122     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9123 
9124   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9125     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9126   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9127     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9128   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9129     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9130   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9131     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9132 
9133   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9134     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9135   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9136     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9137   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9138     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9139   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9140     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9141 
9142   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9143     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9144   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9145     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9146   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9147     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9148   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9149     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9150 
9151   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9152     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9153   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9154     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9155   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9156     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9157   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9158     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9159 
9160   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9161     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9162   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9163     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9164   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9165     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9166   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9167     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9168 
9169   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9170     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9171   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9172     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9173   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9174     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9175   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9176     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9177 
9178   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9179     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9180   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9181     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9182   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9183     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9184   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9185     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9186 
9187   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9188     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9189   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9190     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9191   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9192     BB = EmitAtomicBinary(MI, BB, 4, 0);
9193   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9194     BB = EmitAtomicBinary(MI, BB, 8, 0);
9195 
9196   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9197            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9198            (Subtarget.hasPartwordAtomics() &&
9199             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9200            (Subtarget.hasPartwordAtomics() &&
9201             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9202     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9203 
9204     auto LoadMnemonic = PPC::LDARX;
9205     auto StoreMnemonic = PPC::STDCX;
9206     switch (MI.getOpcode()) {
9207     default:
9208       llvm_unreachable("Compare and swap of unknown size");
9209     case PPC::ATOMIC_CMP_SWAP_I8:
9210       LoadMnemonic = PPC::LBARX;
9211       StoreMnemonic = PPC::STBCX;
9212       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9213       break;
9214     case PPC::ATOMIC_CMP_SWAP_I16:
9215       LoadMnemonic = PPC::LHARX;
9216       StoreMnemonic = PPC::STHCX;
9217       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9218       break;
9219     case PPC::ATOMIC_CMP_SWAP_I32:
9220       LoadMnemonic = PPC::LWARX;
9221       StoreMnemonic = PPC::STWCX;
9222       break;
9223     case PPC::ATOMIC_CMP_SWAP_I64:
9224       LoadMnemonic = PPC::LDARX;
9225       StoreMnemonic = PPC::STDCX;
9226       break;
9227     }
9228     unsigned dest = MI.getOperand(0).getReg();
9229     unsigned ptrA = MI.getOperand(1).getReg();
9230     unsigned ptrB = MI.getOperand(2).getReg();
9231     unsigned oldval = MI.getOperand(3).getReg();
9232     unsigned newval = MI.getOperand(4).getReg();
9233     DebugLoc dl = MI.getDebugLoc();
9234 
9235     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9236     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9237     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9238     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9239     F->insert(It, loop1MBB);
9240     F->insert(It, loop2MBB);
9241     F->insert(It, midMBB);
9242     F->insert(It, exitMBB);
9243     exitMBB->splice(exitMBB->begin(), BB,
9244                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9245     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9246 
9247     //  thisMBB:
9248     //   ...
9249     //   fallthrough --> loopMBB
9250     BB->addSuccessor(loop1MBB);
9251 
9252     // loop1MBB:
9253     //   l[bhwd]arx dest, ptr
9254     //   cmp[wd] dest, oldval
9255     //   bne- midMBB
9256     // loop2MBB:
9257     //   st[bhwd]cx. newval, ptr
9258     //   bne- loopMBB
9259     //   b exitBB
9260     // midMBB:
9261     //   st[bhwd]cx. dest, ptr
9262     // exitBB:
9263     BB = loop1MBB;
9264     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9265       .addReg(ptrA).addReg(ptrB);
9266     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9267       .addReg(oldval).addReg(dest);
9268     BuildMI(BB, dl, TII->get(PPC::BCC))
9269       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9270     BB->addSuccessor(loop2MBB);
9271     BB->addSuccessor(midMBB);
9272 
9273     BB = loop2MBB;
9274     BuildMI(BB, dl, TII->get(StoreMnemonic))
9275       .addReg(newval).addReg(ptrA).addReg(ptrB);
9276     BuildMI(BB, dl, TII->get(PPC::BCC))
9277       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9278     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9279     BB->addSuccessor(loop1MBB);
9280     BB->addSuccessor(exitMBB);
9281 
9282     BB = midMBB;
9283     BuildMI(BB, dl, TII->get(StoreMnemonic))
9284       .addReg(dest).addReg(ptrA).addReg(ptrB);
9285     BB->addSuccessor(exitMBB);
9286 
9287     //  exitMBB:
9288     //   ...
9289     BB = exitMBB;
9290   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9291              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9292     // We must use 64-bit registers for addresses when targeting 64-bit,
9293     // since we're actually doing arithmetic on them.  Other registers
9294     // can be 32-bit.
9295     bool is64bit = Subtarget.isPPC64();
9296     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9297 
9298     unsigned dest = MI.getOperand(0).getReg();
9299     unsigned ptrA = MI.getOperand(1).getReg();
9300     unsigned ptrB = MI.getOperand(2).getReg();
9301     unsigned oldval = MI.getOperand(3).getReg();
9302     unsigned newval = MI.getOperand(4).getReg();
9303     DebugLoc dl = MI.getDebugLoc();
9304 
9305     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9306     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9307     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9308     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9309     F->insert(It, loop1MBB);
9310     F->insert(It, loop2MBB);
9311     F->insert(It, midMBB);
9312     F->insert(It, exitMBB);
9313     exitMBB->splice(exitMBB->begin(), BB,
9314                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9315     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9316 
9317     MachineRegisterInfo &RegInfo = F->getRegInfo();
9318     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9319                                             : &PPC::GPRCRegClass;
9320     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9321     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9322     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
9323     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9324     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9325     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9326     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9327     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9328     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9329     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9330     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9331     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9332     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9333     unsigned Ptr1Reg;
9334     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9335     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9336     //  thisMBB:
9337     //   ...
9338     //   fallthrough --> loopMBB
9339     BB->addSuccessor(loop1MBB);
9340 
9341     // The 4-byte load must be aligned, while a char or short may be
9342     // anywhere in the word.  Hence all this nasty bookkeeping code.
9343     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9344     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9345     //   xori shift, shift1, 24 [16]
9346     //   rlwinm ptr, ptr1, 0, 0, 29
9347     //   slw newval2, newval, shift
9348     //   slw oldval2, oldval,shift
9349     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9350     //   slw mask, mask2, shift
9351     //   and newval3, newval2, mask
9352     //   and oldval3, oldval2, mask
9353     // loop1MBB:
9354     //   lwarx tmpDest, ptr
9355     //   and tmp, tmpDest, mask
9356     //   cmpw tmp, oldval3
9357     //   bne- midMBB
9358     // loop2MBB:
9359     //   andc tmp2, tmpDest, mask
9360     //   or tmp4, tmp2, newval3
9361     //   stwcx. tmp4, ptr
9362     //   bne- loop1MBB
9363     //   b exitBB
9364     // midMBB:
9365     //   stwcx. tmpDest, ptr
9366     // exitBB:
9367     //   srw dest, tmpDest, shift
9368     if (ptrA != ZeroReg) {
9369       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9370       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9371         .addReg(ptrA).addReg(ptrB);
9372     } else {
9373       Ptr1Reg = ptrB;
9374     }
9375     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9376         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9377     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9378         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9379     if (is64bit)
9380       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9381         .addReg(Ptr1Reg).addImm(0).addImm(61);
9382     else
9383       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9384         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9385     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9386         .addReg(newval).addReg(ShiftReg);
9387     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9388         .addReg(oldval).addReg(ShiftReg);
9389     if (is8bit)
9390       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9391     else {
9392       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9393       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9394         .addReg(Mask3Reg).addImm(65535);
9395     }
9396     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9397         .addReg(Mask2Reg).addReg(ShiftReg);
9398     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9399         .addReg(NewVal2Reg).addReg(MaskReg);
9400     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9401         .addReg(OldVal2Reg).addReg(MaskReg);
9402 
9403     BB = loop1MBB;
9404     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9405         .addReg(ZeroReg).addReg(PtrReg);
9406     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9407         .addReg(TmpDestReg).addReg(MaskReg);
9408     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9409         .addReg(TmpReg).addReg(OldVal3Reg);
9410     BuildMI(BB, dl, TII->get(PPC::BCC))
9411         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9412     BB->addSuccessor(loop2MBB);
9413     BB->addSuccessor(midMBB);
9414 
9415     BB = loop2MBB;
9416     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9417         .addReg(TmpDestReg).addReg(MaskReg);
9418     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9419         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9420     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9421         .addReg(ZeroReg).addReg(PtrReg);
9422     BuildMI(BB, dl, TII->get(PPC::BCC))
9423       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9424     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9425     BB->addSuccessor(loop1MBB);
9426     BB->addSuccessor(exitMBB);
9427 
9428     BB = midMBB;
9429     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9430       .addReg(ZeroReg).addReg(PtrReg);
9431     BB->addSuccessor(exitMBB);
9432 
9433     //  exitMBB:
9434     //   ...
9435     BB = exitMBB;
9436     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9437       .addReg(ShiftReg);
9438   } else if (MI.getOpcode() == PPC::FADDrtz) {
9439     // This pseudo performs an FADD with rounding mode temporarily forced
9440     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9441     // is not modeled at the SelectionDAG level.
9442     unsigned Dest = MI.getOperand(0).getReg();
9443     unsigned Src1 = MI.getOperand(1).getReg();
9444     unsigned Src2 = MI.getOperand(2).getReg();
9445     DebugLoc dl = MI.getDebugLoc();
9446 
9447     MachineRegisterInfo &RegInfo = F->getRegInfo();
9448     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9449 
9450     // Save FPSCR value.
9451     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9452 
9453     // Set rounding mode to round-to-zero.
9454     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9455     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9456 
9457     // Perform addition.
9458     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9459 
9460     // Restore FPSCR value.
9461     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9462   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9463              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9464              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9465              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9466     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9467                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9468                           ? PPC::ANDIo8
9469                           : PPC::ANDIo;
9470     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9471                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9472 
9473     MachineRegisterInfo &RegInfo = F->getRegInfo();
9474     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9475                                                   &PPC::GPRCRegClass :
9476                                                   &PPC::G8RCRegClass);
9477 
9478     DebugLoc dl = MI.getDebugLoc();
9479     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9480         .addReg(MI.getOperand(1).getReg())
9481         .addImm(1);
9482     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9483             MI.getOperand(0).getReg())
9484         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9485   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9486     DebugLoc Dl = MI.getDebugLoc();
9487     MachineRegisterInfo &RegInfo = F->getRegInfo();
9488     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9489     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9490     return BB;
9491   } else {
9492     llvm_unreachable("Unexpected instr type to insert");
9493   }
9494 
9495   MI.eraseFromParent(); // The pseudo instruction is gone now.
9496   return BB;
9497 }
9498 
9499 //===----------------------------------------------------------------------===//
9500 // Target Optimization Hooks
9501 //===----------------------------------------------------------------------===//
9502 
9503 static std::string getRecipOp(const char *Base, EVT VT) {
9504   std::string RecipOp(Base);
9505   if (VT.getScalarType() == MVT::f64)
9506     RecipOp += "d";
9507   else
9508     RecipOp += "f";
9509 
9510   if (VT.isVector())
9511     RecipOp = "vec-" + RecipOp;
9512 
9513   return RecipOp;
9514 }
9515 
9516 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9517                                             DAGCombinerInfo &DCI,
9518                                             unsigned &RefinementSteps,
9519                                             bool &UseOneConstNR) const {
9520   EVT VT = Operand.getValueType();
9521   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9522       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9523       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9524       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9525       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9526       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9527     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9528     std::string RecipOp = getRecipOp("sqrt", VT);
9529     if (!Recips.isEnabled(RecipOp))
9530       return SDValue();
9531 
9532     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9533     UseOneConstNR = true;
9534     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9535   }
9536   return SDValue();
9537 }
9538 
9539 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9540                                             DAGCombinerInfo &DCI,
9541                                             unsigned &RefinementSteps) const {
9542   EVT VT = Operand.getValueType();
9543   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9544       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9545       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9546       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9547       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9548       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9549     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9550     std::string RecipOp = getRecipOp("div", VT);
9551     if (!Recips.isEnabled(RecipOp))
9552       return SDValue();
9553 
9554     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9555     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9556   }
9557   return SDValue();
9558 }
9559 
9560 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9561   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9562   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9563   // enabled for division), this functionality is redundant with the default
9564   // combiner logic (once the division -> reciprocal/multiply transformation
9565   // has taken place). As a result, this matters more for older cores than for
9566   // newer ones.
9567 
9568   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9569   // reciprocal if there are two or more FDIVs (for embedded cores with only
9570   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9571   switch (Subtarget.getDarwinDirective()) {
9572   default:
9573     return 3;
9574   case PPC::DIR_440:
9575   case PPC::DIR_A2:
9576   case PPC::DIR_E500mc:
9577   case PPC::DIR_E5500:
9578     return 2;
9579   }
9580 }
9581 
9582 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9583 // collapsed, and so we need to look through chains of them.
9584 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9585                                      int64_t& Offset, SelectionDAG &DAG) {
9586   if (DAG.isBaseWithConstantOffset(Loc)) {
9587     Base = Loc.getOperand(0);
9588     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9589 
9590     // The base might itself be a base plus an offset, and if so, accumulate
9591     // that as well.
9592     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9593   }
9594 }
9595 
9596 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9597                             unsigned Bytes, int Dist,
9598                             SelectionDAG &DAG) {
9599   if (VT.getSizeInBits() / 8 != Bytes)
9600     return false;
9601 
9602   SDValue BaseLoc = Base->getBasePtr();
9603   if (Loc.getOpcode() == ISD::FrameIndex) {
9604     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9605       return false;
9606     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9607     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9608     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9609     int FS  = MFI.getObjectSize(FI);
9610     int BFS = MFI.getObjectSize(BFI);
9611     if (FS != BFS || FS != (int)Bytes) return false;
9612     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9613   }
9614 
9615   SDValue Base1 = Loc, Base2 = BaseLoc;
9616   int64_t Offset1 = 0, Offset2 = 0;
9617   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9618   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9619   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9620     return true;
9621 
9622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9623   const GlobalValue *GV1 = nullptr;
9624   const GlobalValue *GV2 = nullptr;
9625   Offset1 = 0;
9626   Offset2 = 0;
9627   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9628   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9629   if (isGA1 && isGA2 && GV1 == GV2)
9630     return Offset1 == (Offset2 + Dist*Bytes);
9631   return false;
9632 }
9633 
9634 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9635 // not enforce equality of the chain operands.
9636 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9637                             unsigned Bytes, int Dist,
9638                             SelectionDAG &DAG) {
9639   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9640     EVT VT = LS->getMemoryVT();
9641     SDValue Loc = LS->getBasePtr();
9642     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9643   }
9644 
9645   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9646     EVT VT;
9647     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9648     default: return false;
9649     case Intrinsic::ppc_qpx_qvlfd:
9650     case Intrinsic::ppc_qpx_qvlfda:
9651       VT = MVT::v4f64;
9652       break;
9653     case Intrinsic::ppc_qpx_qvlfs:
9654     case Intrinsic::ppc_qpx_qvlfsa:
9655       VT = MVT::v4f32;
9656       break;
9657     case Intrinsic::ppc_qpx_qvlfcd:
9658     case Intrinsic::ppc_qpx_qvlfcda:
9659       VT = MVT::v2f64;
9660       break;
9661     case Intrinsic::ppc_qpx_qvlfcs:
9662     case Intrinsic::ppc_qpx_qvlfcsa:
9663       VT = MVT::v2f32;
9664       break;
9665     case Intrinsic::ppc_qpx_qvlfiwa:
9666     case Intrinsic::ppc_qpx_qvlfiwz:
9667     case Intrinsic::ppc_altivec_lvx:
9668     case Intrinsic::ppc_altivec_lvxl:
9669     case Intrinsic::ppc_vsx_lxvw4x:
9670       VT = MVT::v4i32;
9671       break;
9672     case Intrinsic::ppc_vsx_lxvd2x:
9673       VT = MVT::v2f64;
9674       break;
9675     case Intrinsic::ppc_altivec_lvebx:
9676       VT = MVT::i8;
9677       break;
9678     case Intrinsic::ppc_altivec_lvehx:
9679       VT = MVT::i16;
9680       break;
9681     case Intrinsic::ppc_altivec_lvewx:
9682       VT = MVT::i32;
9683       break;
9684     }
9685 
9686     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9687   }
9688 
9689   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9690     EVT VT;
9691     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9692     default: return false;
9693     case Intrinsic::ppc_qpx_qvstfd:
9694     case Intrinsic::ppc_qpx_qvstfda:
9695       VT = MVT::v4f64;
9696       break;
9697     case Intrinsic::ppc_qpx_qvstfs:
9698     case Intrinsic::ppc_qpx_qvstfsa:
9699       VT = MVT::v4f32;
9700       break;
9701     case Intrinsic::ppc_qpx_qvstfcd:
9702     case Intrinsic::ppc_qpx_qvstfcda:
9703       VT = MVT::v2f64;
9704       break;
9705     case Intrinsic::ppc_qpx_qvstfcs:
9706     case Intrinsic::ppc_qpx_qvstfcsa:
9707       VT = MVT::v2f32;
9708       break;
9709     case Intrinsic::ppc_qpx_qvstfiw:
9710     case Intrinsic::ppc_qpx_qvstfiwa:
9711     case Intrinsic::ppc_altivec_stvx:
9712     case Intrinsic::ppc_altivec_stvxl:
9713     case Intrinsic::ppc_vsx_stxvw4x:
9714       VT = MVT::v4i32;
9715       break;
9716     case Intrinsic::ppc_vsx_stxvd2x:
9717       VT = MVT::v2f64;
9718       break;
9719     case Intrinsic::ppc_altivec_stvebx:
9720       VT = MVT::i8;
9721       break;
9722     case Intrinsic::ppc_altivec_stvehx:
9723       VT = MVT::i16;
9724       break;
9725     case Intrinsic::ppc_altivec_stvewx:
9726       VT = MVT::i32;
9727       break;
9728     }
9729 
9730     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9731   }
9732 
9733   return false;
9734 }
9735 
9736 // Return true is there is a nearyby consecutive load to the one provided
9737 // (regardless of alignment). We search up and down the chain, looking though
9738 // token factors and other loads (but nothing else). As a result, a true result
9739 // indicates that it is safe to create a new consecutive load adjacent to the
9740 // load provided.
9741 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9742   SDValue Chain = LD->getChain();
9743   EVT VT = LD->getMemoryVT();
9744 
9745   SmallSet<SDNode *, 16> LoadRoots;
9746   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9747   SmallSet<SDNode *, 16> Visited;
9748 
9749   // First, search up the chain, branching to follow all token-factor operands.
9750   // If we find a consecutive load, then we're done, otherwise, record all
9751   // nodes just above the top-level loads and token factors.
9752   while (!Queue.empty()) {
9753     SDNode *ChainNext = Queue.pop_back_val();
9754     if (!Visited.insert(ChainNext).second)
9755       continue;
9756 
9757     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9758       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9759         return true;
9760 
9761       if (!Visited.count(ChainLD->getChain().getNode()))
9762         Queue.push_back(ChainLD->getChain().getNode());
9763     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9764       for (const SDUse &O : ChainNext->ops())
9765         if (!Visited.count(O.getNode()))
9766           Queue.push_back(O.getNode());
9767     } else
9768       LoadRoots.insert(ChainNext);
9769   }
9770 
9771   // Second, search down the chain, starting from the top-level nodes recorded
9772   // in the first phase. These top-level nodes are the nodes just above all
9773   // loads and token factors. Starting with their uses, recursively look though
9774   // all loads (just the chain uses) and token factors to find a consecutive
9775   // load.
9776   Visited.clear();
9777   Queue.clear();
9778 
9779   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9780        IE = LoadRoots.end(); I != IE; ++I) {
9781     Queue.push_back(*I);
9782 
9783     while (!Queue.empty()) {
9784       SDNode *LoadRoot = Queue.pop_back_val();
9785       if (!Visited.insert(LoadRoot).second)
9786         continue;
9787 
9788       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9789         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9790           return true;
9791 
9792       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9793            UE = LoadRoot->use_end(); UI != UE; ++UI)
9794         if (((isa<MemSDNode>(*UI) &&
9795             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9796             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9797           Queue.push_back(*UI);
9798     }
9799   }
9800 
9801   return false;
9802 }
9803 
9804 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9805                                                   DAGCombinerInfo &DCI) const {
9806   SelectionDAG &DAG = DCI.DAG;
9807   SDLoc dl(N);
9808 
9809   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9810   // If we're tracking CR bits, we need to be careful that we don't have:
9811   //   trunc(binary-ops(zext(x), zext(y)))
9812   // or
9813   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9814   // such that we're unnecessarily moving things into GPRs when it would be
9815   // better to keep them in CR bits.
9816 
9817   // Note that trunc here can be an actual i1 trunc, or can be the effective
9818   // truncation that comes from a setcc or select_cc.
9819   if (N->getOpcode() == ISD::TRUNCATE &&
9820       N->getValueType(0) != MVT::i1)
9821     return SDValue();
9822 
9823   if (N->getOperand(0).getValueType() != MVT::i32 &&
9824       N->getOperand(0).getValueType() != MVT::i64)
9825     return SDValue();
9826 
9827   if (N->getOpcode() == ISD::SETCC ||
9828       N->getOpcode() == ISD::SELECT_CC) {
9829     // If we're looking at a comparison, then we need to make sure that the
9830     // high bits (all except for the first) don't matter the result.
9831     ISD::CondCode CC =
9832       cast<CondCodeSDNode>(N->getOperand(
9833         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9834     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9835 
9836     if (ISD::isSignedIntSetCC(CC)) {
9837       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9838           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9839         return SDValue();
9840     } else if (ISD::isUnsignedIntSetCC(CC)) {
9841       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9842                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9843           !DAG.MaskedValueIsZero(N->getOperand(1),
9844                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9845         return SDValue();
9846     } else {
9847       // This is neither a signed nor an unsigned comparison, just make sure
9848       // that the high bits are equal.
9849       APInt Op1Zero, Op1One;
9850       APInt Op2Zero, Op2One;
9851       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9852       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9853 
9854       // We don't really care about what is known about the first bit (if
9855       // anything), so clear it in all masks prior to comparing them.
9856       Op1Zero.clearBit(0); Op1One.clearBit(0);
9857       Op2Zero.clearBit(0); Op2One.clearBit(0);
9858 
9859       if (Op1Zero != Op2Zero || Op1One != Op2One)
9860         return SDValue();
9861     }
9862   }
9863 
9864   // We now know that the higher-order bits are irrelevant, we just need to
9865   // make sure that all of the intermediate operations are bit operations, and
9866   // all inputs are extensions.
9867   if (N->getOperand(0).getOpcode() != ISD::AND &&
9868       N->getOperand(0).getOpcode() != ISD::OR  &&
9869       N->getOperand(0).getOpcode() != ISD::XOR &&
9870       N->getOperand(0).getOpcode() != ISD::SELECT &&
9871       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9872       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9873       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9874       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9875       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9876     return SDValue();
9877 
9878   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9879       N->getOperand(1).getOpcode() != ISD::AND &&
9880       N->getOperand(1).getOpcode() != ISD::OR  &&
9881       N->getOperand(1).getOpcode() != ISD::XOR &&
9882       N->getOperand(1).getOpcode() != ISD::SELECT &&
9883       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9884       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9885       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9886       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9887       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9888     return SDValue();
9889 
9890   SmallVector<SDValue, 4> Inputs;
9891   SmallVector<SDValue, 8> BinOps, PromOps;
9892   SmallPtrSet<SDNode *, 16> Visited;
9893 
9894   for (unsigned i = 0; i < 2; ++i) {
9895     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9896           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9897           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9898           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9899         isa<ConstantSDNode>(N->getOperand(i)))
9900       Inputs.push_back(N->getOperand(i));
9901     else
9902       BinOps.push_back(N->getOperand(i));
9903 
9904     if (N->getOpcode() == ISD::TRUNCATE)
9905       break;
9906   }
9907 
9908   // Visit all inputs, collect all binary operations (and, or, xor and
9909   // select) that are all fed by extensions.
9910   while (!BinOps.empty()) {
9911     SDValue BinOp = BinOps.back();
9912     BinOps.pop_back();
9913 
9914     if (!Visited.insert(BinOp.getNode()).second)
9915       continue;
9916 
9917     PromOps.push_back(BinOp);
9918 
9919     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9920       // The condition of the select is not promoted.
9921       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9922         continue;
9923       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9924         continue;
9925 
9926       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9927             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9928             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9929            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9930           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9931         Inputs.push_back(BinOp.getOperand(i));
9932       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9933                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9934                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9935                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9936                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9937                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9938                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9939                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9940                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9941         BinOps.push_back(BinOp.getOperand(i));
9942       } else {
9943         // We have an input that is not an extension or another binary
9944         // operation; we'll abort this transformation.
9945         return SDValue();
9946       }
9947     }
9948   }
9949 
9950   // Make sure that this is a self-contained cluster of operations (which
9951   // is not quite the same thing as saying that everything has only one
9952   // use).
9953   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9954     if (isa<ConstantSDNode>(Inputs[i]))
9955       continue;
9956 
9957     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9958                               UE = Inputs[i].getNode()->use_end();
9959          UI != UE; ++UI) {
9960       SDNode *User = *UI;
9961       if (User != N && !Visited.count(User))
9962         return SDValue();
9963 
9964       // Make sure that we're not going to promote the non-output-value
9965       // operand(s) or SELECT or SELECT_CC.
9966       // FIXME: Although we could sometimes handle this, and it does occur in
9967       // practice that one of the condition inputs to the select is also one of
9968       // the outputs, we currently can't deal with this.
9969       if (User->getOpcode() == ISD::SELECT) {
9970         if (User->getOperand(0) == Inputs[i])
9971           return SDValue();
9972       } else if (User->getOpcode() == ISD::SELECT_CC) {
9973         if (User->getOperand(0) == Inputs[i] ||
9974             User->getOperand(1) == Inputs[i])
9975           return SDValue();
9976       }
9977     }
9978   }
9979 
9980   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9981     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9982                               UE = PromOps[i].getNode()->use_end();
9983          UI != UE; ++UI) {
9984       SDNode *User = *UI;
9985       if (User != N && !Visited.count(User))
9986         return SDValue();
9987 
9988       // Make sure that we're not going to promote the non-output-value
9989       // operand(s) or SELECT or SELECT_CC.
9990       // FIXME: Although we could sometimes handle this, and it does occur in
9991       // practice that one of the condition inputs to the select is also one of
9992       // the outputs, we currently can't deal with this.
9993       if (User->getOpcode() == ISD::SELECT) {
9994         if (User->getOperand(0) == PromOps[i])
9995           return SDValue();
9996       } else if (User->getOpcode() == ISD::SELECT_CC) {
9997         if (User->getOperand(0) == PromOps[i] ||
9998             User->getOperand(1) == PromOps[i])
9999           return SDValue();
10000       }
10001     }
10002   }
10003 
10004   // Replace all inputs with the extension operand.
10005   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10006     // Constants may have users outside the cluster of to-be-promoted nodes,
10007     // and so we need to replace those as we do the promotions.
10008     if (isa<ConstantSDNode>(Inputs[i]))
10009       continue;
10010     else
10011       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10012   }
10013 
10014   std::list<HandleSDNode> PromOpHandles;
10015   for (auto &PromOp : PromOps)
10016     PromOpHandles.emplace_back(PromOp);
10017 
10018   // Replace all operations (these are all the same, but have a different
10019   // (i1) return type). DAG.getNode will validate that the types of
10020   // a binary operator match, so go through the list in reverse so that
10021   // we've likely promoted both operands first. Any intermediate truncations or
10022   // extensions disappear.
10023   while (!PromOpHandles.empty()) {
10024     SDValue PromOp = PromOpHandles.back().getValue();
10025     PromOpHandles.pop_back();
10026 
10027     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10028         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10029         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10030         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10031       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10032           PromOp.getOperand(0).getValueType() != MVT::i1) {
10033         // The operand is not yet ready (see comment below).
10034         PromOpHandles.emplace_front(PromOp);
10035         continue;
10036       }
10037 
10038       SDValue RepValue = PromOp.getOperand(0);
10039       if (isa<ConstantSDNode>(RepValue))
10040         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10041 
10042       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10043       continue;
10044     }
10045 
10046     unsigned C;
10047     switch (PromOp.getOpcode()) {
10048     default:             C = 0; break;
10049     case ISD::SELECT:    C = 1; break;
10050     case ISD::SELECT_CC: C = 2; break;
10051     }
10052 
10053     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10054          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10055         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10056          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10057       // The to-be-promoted operands of this node have not yet been
10058       // promoted (this should be rare because we're going through the
10059       // list backward, but if one of the operands has several users in
10060       // this cluster of to-be-promoted nodes, it is possible).
10061       PromOpHandles.emplace_front(PromOp);
10062       continue;
10063     }
10064 
10065     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10066                                 PromOp.getNode()->op_end());
10067 
10068     // If there are any constant inputs, make sure they're replaced now.
10069     for (unsigned i = 0; i < 2; ++i)
10070       if (isa<ConstantSDNode>(Ops[C+i]))
10071         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10072 
10073     DAG.ReplaceAllUsesOfValueWith(PromOp,
10074       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10075   }
10076 
10077   // Now we're left with the initial truncation itself.
10078   if (N->getOpcode() == ISD::TRUNCATE)
10079     return N->getOperand(0);
10080 
10081   // Otherwise, this is a comparison. The operands to be compared have just
10082   // changed type (to i1), but everything else is the same.
10083   return SDValue(N, 0);
10084 }
10085 
10086 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10087                                                   DAGCombinerInfo &DCI) const {
10088   SelectionDAG &DAG = DCI.DAG;
10089   SDLoc dl(N);
10090 
10091   // If we're tracking CR bits, we need to be careful that we don't have:
10092   //   zext(binary-ops(trunc(x), trunc(y)))
10093   // or
10094   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10095   // such that we're unnecessarily moving things into CR bits that can more
10096   // efficiently stay in GPRs. Note that if we're not certain that the high
10097   // bits are set as required by the final extension, we still may need to do
10098   // some masking to get the proper behavior.
10099 
10100   // This same functionality is important on PPC64 when dealing with
10101   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10102   // the return values of functions. Because it is so similar, it is handled
10103   // here as well.
10104 
10105   if (N->getValueType(0) != MVT::i32 &&
10106       N->getValueType(0) != MVT::i64)
10107     return SDValue();
10108 
10109   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10110         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10111     return SDValue();
10112 
10113   if (N->getOperand(0).getOpcode() != ISD::AND &&
10114       N->getOperand(0).getOpcode() != ISD::OR  &&
10115       N->getOperand(0).getOpcode() != ISD::XOR &&
10116       N->getOperand(0).getOpcode() != ISD::SELECT &&
10117       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10118     return SDValue();
10119 
10120   SmallVector<SDValue, 4> Inputs;
10121   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10122   SmallPtrSet<SDNode *, 16> Visited;
10123 
10124   // Visit all inputs, collect all binary operations (and, or, xor and
10125   // select) that are all fed by truncations.
10126   while (!BinOps.empty()) {
10127     SDValue BinOp = BinOps.back();
10128     BinOps.pop_back();
10129 
10130     if (!Visited.insert(BinOp.getNode()).second)
10131       continue;
10132 
10133     PromOps.push_back(BinOp);
10134 
10135     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10136       // The condition of the select is not promoted.
10137       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10138         continue;
10139       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10140         continue;
10141 
10142       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10143           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10144         Inputs.push_back(BinOp.getOperand(i));
10145       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10146                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10147                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10148                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10149                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10150         BinOps.push_back(BinOp.getOperand(i));
10151       } else {
10152         // We have an input that is not a truncation or another binary
10153         // operation; we'll abort this transformation.
10154         return SDValue();
10155       }
10156     }
10157   }
10158 
10159   // The operands of a select that must be truncated when the select is
10160   // promoted because the operand is actually part of the to-be-promoted set.
10161   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10162 
10163   // Make sure that this is a self-contained cluster of operations (which
10164   // is not quite the same thing as saying that everything has only one
10165   // use).
10166   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10167     if (isa<ConstantSDNode>(Inputs[i]))
10168       continue;
10169 
10170     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10171                               UE = Inputs[i].getNode()->use_end();
10172          UI != UE; ++UI) {
10173       SDNode *User = *UI;
10174       if (User != N && !Visited.count(User))
10175         return SDValue();
10176 
10177       // If we're going to promote the non-output-value operand(s) or SELECT or
10178       // SELECT_CC, record them for truncation.
10179       if (User->getOpcode() == ISD::SELECT) {
10180         if (User->getOperand(0) == Inputs[i])
10181           SelectTruncOp[0].insert(std::make_pair(User,
10182                                     User->getOperand(0).getValueType()));
10183       } else if (User->getOpcode() == ISD::SELECT_CC) {
10184         if (User->getOperand(0) == Inputs[i])
10185           SelectTruncOp[0].insert(std::make_pair(User,
10186                                     User->getOperand(0).getValueType()));
10187         if (User->getOperand(1) == Inputs[i])
10188           SelectTruncOp[1].insert(std::make_pair(User,
10189                                     User->getOperand(1).getValueType()));
10190       }
10191     }
10192   }
10193 
10194   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10195     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10196                               UE = PromOps[i].getNode()->use_end();
10197          UI != UE; ++UI) {
10198       SDNode *User = *UI;
10199       if (User != N && !Visited.count(User))
10200         return SDValue();
10201 
10202       // If we're going to promote the non-output-value operand(s) or SELECT or
10203       // SELECT_CC, record them for truncation.
10204       if (User->getOpcode() == ISD::SELECT) {
10205         if (User->getOperand(0) == PromOps[i])
10206           SelectTruncOp[0].insert(std::make_pair(User,
10207                                     User->getOperand(0).getValueType()));
10208       } else if (User->getOpcode() == ISD::SELECT_CC) {
10209         if (User->getOperand(0) == PromOps[i])
10210           SelectTruncOp[0].insert(std::make_pair(User,
10211                                     User->getOperand(0).getValueType()));
10212         if (User->getOperand(1) == PromOps[i])
10213           SelectTruncOp[1].insert(std::make_pair(User,
10214                                     User->getOperand(1).getValueType()));
10215       }
10216     }
10217   }
10218 
10219   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10220   bool ReallyNeedsExt = false;
10221   if (N->getOpcode() != ISD::ANY_EXTEND) {
10222     // If all of the inputs are not already sign/zero extended, then
10223     // we'll still need to do that at the end.
10224     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10225       if (isa<ConstantSDNode>(Inputs[i]))
10226         continue;
10227 
10228       unsigned OpBits =
10229         Inputs[i].getOperand(0).getValueSizeInBits();
10230       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10231 
10232       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10233            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10234                                   APInt::getHighBitsSet(OpBits,
10235                                                         OpBits-PromBits))) ||
10236           (N->getOpcode() == ISD::SIGN_EXTEND &&
10237            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10238              (OpBits-(PromBits-1)))) {
10239         ReallyNeedsExt = true;
10240         break;
10241       }
10242     }
10243   }
10244 
10245   // Replace all inputs, either with the truncation operand, or a
10246   // truncation or extension to the final output type.
10247   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10248     // Constant inputs need to be replaced with the to-be-promoted nodes that
10249     // use them because they might have users outside of the cluster of
10250     // promoted nodes.
10251     if (isa<ConstantSDNode>(Inputs[i]))
10252       continue;
10253 
10254     SDValue InSrc = Inputs[i].getOperand(0);
10255     if (Inputs[i].getValueType() == N->getValueType(0))
10256       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10257     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10258       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10259         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10260     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10261       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10262         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10263     else
10264       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10265         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10266   }
10267 
10268   std::list<HandleSDNode> PromOpHandles;
10269   for (auto &PromOp : PromOps)
10270     PromOpHandles.emplace_back(PromOp);
10271 
10272   // Replace all operations (these are all the same, but have a different
10273   // (promoted) return type). DAG.getNode will validate that the types of
10274   // a binary operator match, so go through the list in reverse so that
10275   // we've likely promoted both operands first.
10276   while (!PromOpHandles.empty()) {
10277     SDValue PromOp = PromOpHandles.back().getValue();
10278     PromOpHandles.pop_back();
10279 
10280     unsigned C;
10281     switch (PromOp.getOpcode()) {
10282     default:             C = 0; break;
10283     case ISD::SELECT:    C = 1; break;
10284     case ISD::SELECT_CC: C = 2; break;
10285     }
10286 
10287     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10288          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10289         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10290          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10291       // The to-be-promoted operands of this node have not yet been
10292       // promoted (this should be rare because we're going through the
10293       // list backward, but if one of the operands has several users in
10294       // this cluster of to-be-promoted nodes, it is possible).
10295       PromOpHandles.emplace_front(PromOp);
10296       continue;
10297     }
10298 
10299     // For SELECT and SELECT_CC nodes, we do a similar check for any
10300     // to-be-promoted comparison inputs.
10301     if (PromOp.getOpcode() == ISD::SELECT ||
10302         PromOp.getOpcode() == ISD::SELECT_CC) {
10303       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10304            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10305           (SelectTruncOp[1].count(PromOp.getNode()) &&
10306            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10307         PromOpHandles.emplace_front(PromOp);
10308         continue;
10309       }
10310     }
10311 
10312     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10313                                 PromOp.getNode()->op_end());
10314 
10315     // If this node has constant inputs, then they'll need to be promoted here.
10316     for (unsigned i = 0; i < 2; ++i) {
10317       if (!isa<ConstantSDNode>(Ops[C+i]))
10318         continue;
10319       if (Ops[C+i].getValueType() == N->getValueType(0))
10320         continue;
10321 
10322       if (N->getOpcode() == ISD::SIGN_EXTEND)
10323         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10324       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10325         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10326       else
10327         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10328     }
10329 
10330     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10331     // truncate them again to the original value type.
10332     if (PromOp.getOpcode() == ISD::SELECT ||
10333         PromOp.getOpcode() == ISD::SELECT_CC) {
10334       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10335       if (SI0 != SelectTruncOp[0].end())
10336         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10337       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10338       if (SI1 != SelectTruncOp[1].end())
10339         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10340     }
10341 
10342     DAG.ReplaceAllUsesOfValueWith(PromOp,
10343       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10344   }
10345 
10346   // Now we're left with the initial extension itself.
10347   if (!ReallyNeedsExt)
10348     return N->getOperand(0);
10349 
10350   // To zero extend, just mask off everything except for the first bit (in the
10351   // i1 case).
10352   if (N->getOpcode() == ISD::ZERO_EXTEND)
10353     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10354                        DAG.getConstant(APInt::getLowBitsSet(
10355                                          N->getValueSizeInBits(0), PromBits),
10356                                        dl, N->getValueType(0)));
10357 
10358   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10359          "Invalid extension type");
10360   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10361   SDValue ShiftCst =
10362       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10363   return DAG.getNode(
10364       ISD::SRA, dl, N->getValueType(0),
10365       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10366       ShiftCst);
10367 }
10368 
10369 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10370                                                  DAGCombinerInfo &DCI) const {
10371   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10372          "Should be called with a BUILD_VECTOR node");
10373 
10374   SelectionDAG &DAG = DCI.DAG;
10375   SDLoc dl(N);
10376   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10377     return SDValue();
10378 
10379   // Looking for:
10380   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10381   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10382       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10383     return SDValue();
10384   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10385       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10386     return SDValue();
10387   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10388     return SDValue();
10389 
10390   SDValue Ext1 = N->getOperand(0).getOperand(0);
10391   SDValue Ext2 = N->getOperand(1).getOperand(0);
10392   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10393      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10394     return SDValue();
10395 
10396   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10397   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10398   if (!Ext1Op || !Ext2Op)
10399     return SDValue();
10400   if (Ext1.getValueType() != MVT::i32 ||
10401       Ext2.getValueType() != MVT::i32)
10402   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10403     return SDValue();
10404 
10405   int FirstElem = Ext1Op->getZExtValue();
10406   int SecondElem = Ext2Op->getZExtValue();
10407   int SubvecIdx;
10408   if (FirstElem == 0 && SecondElem == 1)
10409     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10410   else if (FirstElem == 2 && SecondElem == 3)
10411     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10412   else
10413     return SDValue();
10414 
10415   SDValue SrcVec = Ext1.getOperand(0);
10416   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10417     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10418   return DAG.getNode(NodeType, dl, MVT::v2f64,
10419                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10420 }
10421 
10422 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10423                                               DAGCombinerInfo &DCI) const {
10424   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10425           N->getOpcode() == ISD::UINT_TO_FP) &&
10426          "Need an int -> FP conversion node here");
10427 
10428   if (!Subtarget.has64BitSupport())
10429     return SDValue();
10430 
10431   SelectionDAG &DAG = DCI.DAG;
10432   SDLoc dl(N);
10433   SDValue Op(N, 0);
10434 
10435   // Don't handle ppc_fp128 here or i1 conversions.
10436   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10437     return SDValue();
10438   if (Op.getOperand(0).getValueType() == MVT::i1)
10439     return SDValue();
10440 
10441   // For i32 intermediate values, unfortunately, the conversion functions
10442   // leave the upper 32 bits of the value are undefined. Within the set of
10443   // scalar instructions, we have no method for zero- or sign-extending the
10444   // value. Thus, we cannot handle i32 intermediate values here.
10445   if (Op.getOperand(0).getValueType() == MVT::i32)
10446     return SDValue();
10447 
10448   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10449          "UINT_TO_FP is supported only with FPCVT");
10450 
10451   // If we have FCFIDS, then use it when converting to single-precision.
10452   // Otherwise, convert to double-precision and then round.
10453   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10454                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10455                                                             : PPCISD::FCFIDS)
10456                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10457                                                             : PPCISD::FCFID);
10458   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10459                   ? MVT::f32
10460                   : MVT::f64;
10461 
10462   // If we're converting from a float, to an int, and back to a float again,
10463   // then we don't need the store/load pair at all.
10464   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10465        Subtarget.hasFPCVT()) ||
10466       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10467     SDValue Src = Op.getOperand(0).getOperand(0);
10468     if (Src.getValueType() == MVT::f32) {
10469       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10470       DCI.AddToWorklist(Src.getNode());
10471     } else if (Src.getValueType() != MVT::f64) {
10472       // Make sure that we don't pick up a ppc_fp128 source value.
10473       return SDValue();
10474     }
10475 
10476     unsigned FCTOp =
10477       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10478                                                         PPCISD::FCTIDUZ;
10479 
10480     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10481     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10482 
10483     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10484       FP = DAG.getNode(ISD::FP_ROUND, dl,
10485                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10486       DCI.AddToWorklist(FP.getNode());
10487     }
10488 
10489     return FP;
10490   }
10491 
10492   return SDValue();
10493 }
10494 
10495 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10496 // builtins) into loads with swaps.
10497 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10498                                               DAGCombinerInfo &DCI) const {
10499   SelectionDAG &DAG = DCI.DAG;
10500   SDLoc dl(N);
10501   SDValue Chain;
10502   SDValue Base;
10503   MachineMemOperand *MMO;
10504 
10505   switch (N->getOpcode()) {
10506   default:
10507     llvm_unreachable("Unexpected opcode for little endian VSX load");
10508   case ISD::LOAD: {
10509     LoadSDNode *LD = cast<LoadSDNode>(N);
10510     Chain = LD->getChain();
10511     Base = LD->getBasePtr();
10512     MMO = LD->getMemOperand();
10513     // If the MMO suggests this isn't a load of a full vector, leave
10514     // things alone.  For a built-in, we have to make the change for
10515     // correctness, so if there is a size problem that will be a bug.
10516     if (MMO->getSize() < 16)
10517       return SDValue();
10518     break;
10519   }
10520   case ISD::INTRINSIC_W_CHAIN: {
10521     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10522     Chain = Intrin->getChain();
10523     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10524     // us what we want. Get operand 2 instead.
10525     Base = Intrin->getOperand(2);
10526     MMO = Intrin->getMemOperand();
10527     break;
10528   }
10529   }
10530 
10531   MVT VecTy = N->getValueType(0).getSimpleVT();
10532   SDValue LoadOps[] = { Chain, Base };
10533   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10534                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10535                                          LoadOps, MVT::v2f64, MMO);
10536 
10537   DCI.AddToWorklist(Load.getNode());
10538   Chain = Load.getValue(1);
10539   SDValue Swap = DAG.getNode(
10540       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10541   DCI.AddToWorklist(Swap.getNode());
10542 
10543   // Add a bitcast if the resulting load type doesn't match v2f64.
10544   if (VecTy != MVT::v2f64) {
10545     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10546     DCI.AddToWorklist(N.getNode());
10547     // Package {bitcast value, swap's chain} to match Load's shape.
10548     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10549                        N, Swap.getValue(1));
10550   }
10551 
10552   return Swap;
10553 }
10554 
10555 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10556 // builtins) into stores with swaps.
10557 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10558                                                DAGCombinerInfo &DCI) const {
10559   SelectionDAG &DAG = DCI.DAG;
10560   SDLoc dl(N);
10561   SDValue Chain;
10562   SDValue Base;
10563   unsigned SrcOpnd;
10564   MachineMemOperand *MMO;
10565 
10566   switch (N->getOpcode()) {
10567   default:
10568     llvm_unreachable("Unexpected opcode for little endian VSX store");
10569   case ISD::STORE: {
10570     StoreSDNode *ST = cast<StoreSDNode>(N);
10571     Chain = ST->getChain();
10572     Base = ST->getBasePtr();
10573     MMO = ST->getMemOperand();
10574     SrcOpnd = 1;
10575     // If the MMO suggests this isn't a store of a full vector, leave
10576     // things alone.  For a built-in, we have to make the change for
10577     // correctness, so if there is a size problem that will be a bug.
10578     if (MMO->getSize() < 16)
10579       return SDValue();
10580     break;
10581   }
10582   case ISD::INTRINSIC_VOID: {
10583     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10584     Chain = Intrin->getChain();
10585     // Intrin->getBasePtr() oddly does not get what we want.
10586     Base = Intrin->getOperand(3);
10587     MMO = Intrin->getMemOperand();
10588     SrcOpnd = 2;
10589     break;
10590   }
10591   }
10592 
10593   SDValue Src = N->getOperand(SrcOpnd);
10594   MVT VecTy = Src.getValueType().getSimpleVT();
10595 
10596   // All stores are done as v2f64 and possible bit cast.
10597   if (VecTy != MVT::v2f64) {
10598     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10599     DCI.AddToWorklist(Src.getNode());
10600   }
10601 
10602   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10603                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10604   DCI.AddToWorklist(Swap.getNode());
10605   Chain = Swap.getValue(1);
10606   SDValue StoreOps[] = { Chain, Swap, Base };
10607   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10608                                           DAG.getVTList(MVT::Other),
10609                                           StoreOps, VecTy, MMO);
10610   DCI.AddToWorklist(Store.getNode());
10611   return Store;
10612 }
10613 
10614 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10615                                              DAGCombinerInfo &DCI) const {
10616   SelectionDAG &DAG = DCI.DAG;
10617   SDLoc dl(N);
10618   switch (N->getOpcode()) {
10619   default: break;
10620   case PPCISD::SHL:
10621     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10622         return N->getOperand(0);
10623     break;
10624   case PPCISD::SRL:
10625     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10626         return N->getOperand(0);
10627     break;
10628   case PPCISD::SRA:
10629     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10630       if (C->isNullValue() ||   //  0 >>s V -> 0.
10631           C->isAllOnesValue())    // -1 >>s V -> -1.
10632         return N->getOperand(0);
10633     }
10634     break;
10635   case ISD::SIGN_EXTEND:
10636   case ISD::ZERO_EXTEND:
10637   case ISD::ANY_EXTEND:
10638     return DAGCombineExtBoolTrunc(N, DCI);
10639   case ISD::TRUNCATE:
10640   case ISD::SETCC:
10641   case ISD::SELECT_CC:
10642     return DAGCombineTruncBoolExt(N, DCI);
10643   case ISD::SINT_TO_FP:
10644   case ISD::UINT_TO_FP:
10645     return combineFPToIntToFP(N, DCI);
10646   case ISD::STORE: {
10647     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10648     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10649         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10650         N->getOperand(1).getValueType() == MVT::i32 &&
10651         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10652       SDValue Val = N->getOperand(1).getOperand(0);
10653       if (Val.getValueType() == MVT::f32) {
10654         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10655         DCI.AddToWorklist(Val.getNode());
10656       }
10657       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10658       DCI.AddToWorklist(Val.getNode());
10659 
10660       SDValue Ops[] = {
10661         N->getOperand(0), Val, N->getOperand(2),
10662         DAG.getValueType(N->getOperand(1).getValueType())
10663       };
10664 
10665       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10666               DAG.getVTList(MVT::Other), Ops,
10667               cast<StoreSDNode>(N)->getMemoryVT(),
10668               cast<StoreSDNode>(N)->getMemOperand());
10669       DCI.AddToWorklist(Val.getNode());
10670       return Val;
10671     }
10672 
10673     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10674     if (cast<StoreSDNode>(N)->isUnindexed() &&
10675         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10676         N->getOperand(1).getNode()->hasOneUse() &&
10677         (N->getOperand(1).getValueType() == MVT::i32 ||
10678          N->getOperand(1).getValueType() == MVT::i16 ||
10679          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10680           N->getOperand(1).getValueType() == MVT::i64))) {
10681       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10682       // Do an any-extend to 32-bits if this is a half-word input.
10683       if (BSwapOp.getValueType() == MVT::i16)
10684         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10685 
10686       SDValue Ops[] = {
10687         N->getOperand(0), BSwapOp, N->getOperand(2),
10688         DAG.getValueType(N->getOperand(1).getValueType())
10689       };
10690       return
10691         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10692                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10693                                 cast<StoreSDNode>(N)->getMemOperand());
10694     }
10695 
10696     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10697     EVT VT = N->getOperand(1).getValueType();
10698     if (VT.isSimple()) {
10699       MVT StoreVT = VT.getSimpleVT();
10700       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10701           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10702            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10703         return expandVSXStoreForLE(N, DCI);
10704     }
10705     break;
10706   }
10707   case ISD::LOAD: {
10708     LoadSDNode *LD = cast<LoadSDNode>(N);
10709     EVT VT = LD->getValueType(0);
10710 
10711     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10712     if (VT.isSimple()) {
10713       MVT LoadVT = VT.getSimpleVT();
10714       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10715           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10716            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10717         return expandVSXLoadForLE(N, DCI);
10718     }
10719 
10720     // We sometimes end up with a 64-bit integer load, from which we extract
10721     // two single-precision floating-point numbers. This happens with
10722     // std::complex<float>, and other similar structures, because of the way we
10723     // canonicalize structure copies. However, if we lack direct moves,
10724     // then the final bitcasts from the extracted integer values to the
10725     // floating-point numbers turn into store/load pairs. Even with direct moves,
10726     // just loading the two floating-point numbers is likely better.
10727     auto ReplaceTwoFloatLoad = [&]() {
10728       if (VT != MVT::i64)
10729         return false;
10730 
10731       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10732           LD->isVolatile())
10733         return false;
10734 
10735       //  We're looking for a sequence like this:
10736       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10737       //      t16: i64 = srl t13, Constant:i32<32>
10738       //    t17: i32 = truncate t16
10739       //  t18: f32 = bitcast t17
10740       //    t19: i32 = truncate t13
10741       //  t20: f32 = bitcast t19
10742 
10743       if (!LD->hasNUsesOfValue(2, 0))
10744         return false;
10745 
10746       auto UI = LD->use_begin();
10747       while (UI.getUse().getResNo() != 0) ++UI;
10748       SDNode *Trunc = *UI++;
10749       while (UI.getUse().getResNo() != 0) ++UI;
10750       SDNode *RightShift = *UI;
10751       if (Trunc->getOpcode() != ISD::TRUNCATE)
10752         std::swap(Trunc, RightShift);
10753 
10754       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10755           Trunc->getValueType(0) != MVT::i32 ||
10756           !Trunc->hasOneUse())
10757         return false;
10758       if (RightShift->getOpcode() != ISD::SRL ||
10759           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10760           RightShift->getConstantOperandVal(1) != 32 ||
10761           !RightShift->hasOneUse())
10762         return false;
10763 
10764       SDNode *Trunc2 = *RightShift->use_begin();
10765       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10766           Trunc2->getValueType(0) != MVT::i32 ||
10767           !Trunc2->hasOneUse())
10768         return false;
10769 
10770       SDNode *Bitcast = *Trunc->use_begin();
10771       SDNode *Bitcast2 = *Trunc2->use_begin();
10772 
10773       if (Bitcast->getOpcode() != ISD::BITCAST ||
10774           Bitcast->getValueType(0) != MVT::f32)
10775         return false;
10776       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10777           Bitcast2->getValueType(0) != MVT::f32)
10778         return false;
10779 
10780       if (Subtarget.isLittleEndian())
10781         std::swap(Bitcast, Bitcast2);
10782 
10783       // Bitcast has the second float (in memory-layout order) and Bitcast2
10784       // has the first one.
10785 
10786       SDValue BasePtr = LD->getBasePtr();
10787       if (LD->isIndexed()) {
10788         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10789                "Non-pre-inc AM on PPC?");
10790         BasePtr =
10791           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10792                       LD->getOffset());
10793       }
10794 
10795       auto MMOFlags =
10796           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
10797       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10798                                       LD->getPointerInfo(), LD->getAlignment(),
10799                                       MMOFlags, LD->getAAInfo());
10800       SDValue AddPtr =
10801         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10802                     BasePtr, DAG.getIntPtrConstant(4, dl));
10803       SDValue FloatLoad2 = DAG.getLoad(
10804           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10805           LD->getPointerInfo().getWithOffset(4),
10806           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
10807 
10808       if (LD->isIndexed()) {
10809         // Note that DAGCombine should re-form any pre-increment load(s) from
10810         // what is produced here if that makes sense.
10811         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10812       }
10813 
10814       DCI.CombineTo(Bitcast2, FloatLoad);
10815       DCI.CombineTo(Bitcast, FloatLoad2);
10816 
10817       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10818                                     SDValue(FloatLoad2.getNode(), 1));
10819       return true;
10820     };
10821 
10822     if (ReplaceTwoFloatLoad())
10823       return SDValue(N, 0);
10824 
10825     EVT MemVT = LD->getMemoryVT();
10826     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10827     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10828     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10829     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10830     if (LD->isUnindexed() && VT.isVector() &&
10831         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10832           // P8 and later hardware should just use LOAD.
10833           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10834                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10835          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10836           LD->getAlignment() >= ScalarABIAlignment)) &&
10837         LD->getAlignment() < ABIAlignment) {
10838       // This is a type-legal unaligned Altivec or QPX load.
10839       SDValue Chain = LD->getChain();
10840       SDValue Ptr = LD->getBasePtr();
10841       bool isLittleEndian = Subtarget.isLittleEndian();
10842 
10843       // This implements the loading of unaligned vectors as described in
10844       // the venerable Apple Velocity Engine overview. Specifically:
10845       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10846       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10847       //
10848       // The general idea is to expand a sequence of one or more unaligned
10849       // loads into an alignment-based permutation-control instruction (lvsl
10850       // or lvsr), a series of regular vector loads (which always truncate
10851       // their input address to an aligned address), and a series of
10852       // permutations.  The results of these permutations are the requested
10853       // loaded values.  The trick is that the last "extra" load is not taken
10854       // from the address you might suspect (sizeof(vector) bytes after the
10855       // last requested load), but rather sizeof(vector) - 1 bytes after the
10856       // last requested vector. The point of this is to avoid a page fault if
10857       // the base address happened to be aligned. This works because if the
10858       // base address is aligned, then adding less than a full vector length
10859       // will cause the last vector in the sequence to be (re)loaded.
10860       // Otherwise, the next vector will be fetched as you might suspect was
10861       // necessary.
10862 
10863       // We might be able to reuse the permutation generation from
10864       // a different base address offset from this one by an aligned amount.
10865       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10866       // optimization later.
10867       Intrinsic::ID Intr, IntrLD, IntrPerm;
10868       MVT PermCntlTy, PermTy, LDTy;
10869       if (Subtarget.hasAltivec()) {
10870         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10871                                  Intrinsic::ppc_altivec_lvsl;
10872         IntrLD = Intrinsic::ppc_altivec_lvx;
10873         IntrPerm = Intrinsic::ppc_altivec_vperm;
10874         PermCntlTy = MVT::v16i8;
10875         PermTy = MVT::v4i32;
10876         LDTy = MVT::v4i32;
10877       } else {
10878         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10879                                        Intrinsic::ppc_qpx_qvlpcls;
10880         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10881                                        Intrinsic::ppc_qpx_qvlfs;
10882         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10883         PermCntlTy = MVT::v4f64;
10884         PermTy = MVT::v4f64;
10885         LDTy = MemVT.getSimpleVT();
10886       }
10887 
10888       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10889 
10890       // Create the new MMO for the new base load. It is like the original MMO,
10891       // but represents an area in memory almost twice the vector size centered
10892       // on the original address. If the address is unaligned, we might start
10893       // reading up to (sizeof(vector)-1) bytes below the address of the
10894       // original unaligned load.
10895       MachineFunction &MF = DAG.getMachineFunction();
10896       MachineMemOperand *BaseMMO =
10897         MF.getMachineMemOperand(LD->getMemOperand(),
10898                                 -(long)MemVT.getStoreSize()+1,
10899                                 2*MemVT.getStoreSize()-1);
10900 
10901       // Create the new base load.
10902       SDValue LDXIntID =
10903           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10904       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10905       SDValue BaseLoad =
10906         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10907                                 DAG.getVTList(PermTy, MVT::Other),
10908                                 BaseLoadOps, LDTy, BaseMMO);
10909 
10910       // Note that the value of IncOffset (which is provided to the next
10911       // load's pointer info offset value, and thus used to calculate the
10912       // alignment), and the value of IncValue (which is actually used to
10913       // increment the pointer value) are different! This is because we
10914       // require the next load to appear to be aligned, even though it
10915       // is actually offset from the base pointer by a lesser amount.
10916       int IncOffset = VT.getSizeInBits() / 8;
10917       int IncValue = IncOffset;
10918 
10919       // Walk (both up and down) the chain looking for another load at the real
10920       // (aligned) offset (the alignment of the other load does not matter in
10921       // this case). If found, then do not use the offset reduction trick, as
10922       // that will prevent the loads from being later combined (as they would
10923       // otherwise be duplicates).
10924       if (!findConsecutiveLoad(LD, DAG))
10925         --IncValue;
10926 
10927       SDValue Increment =
10928           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10929       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10930 
10931       MachineMemOperand *ExtraMMO =
10932         MF.getMachineMemOperand(LD->getMemOperand(),
10933                                 1, 2*MemVT.getStoreSize()-1);
10934       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10935       SDValue ExtraLoad =
10936         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10937                                 DAG.getVTList(PermTy, MVT::Other),
10938                                 ExtraLoadOps, LDTy, ExtraMMO);
10939 
10940       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10941         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10942 
10943       // Because vperm has a big-endian bias, we must reverse the order
10944       // of the input vectors and complement the permute control vector
10945       // when generating little endian code.  We have already handled the
10946       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10947       // and ExtraLoad here.
10948       SDValue Perm;
10949       if (isLittleEndian)
10950         Perm = BuildIntrinsicOp(IntrPerm,
10951                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10952       else
10953         Perm = BuildIntrinsicOp(IntrPerm,
10954                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10955 
10956       if (VT != PermTy)
10957         Perm = Subtarget.hasAltivec() ?
10958                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10959                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10960                                DAG.getTargetConstant(1, dl, MVT::i64));
10961                                // second argument is 1 because this rounding
10962                                // is always exact.
10963 
10964       // The output of the permutation is our loaded result, the TokenFactor is
10965       // our new chain.
10966       DCI.CombineTo(N, Perm, TF);
10967       return SDValue(N, 0);
10968     }
10969     }
10970     break;
10971     case ISD::INTRINSIC_WO_CHAIN: {
10972       bool isLittleEndian = Subtarget.isLittleEndian();
10973       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10974       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10975                                            : Intrinsic::ppc_altivec_lvsl);
10976       if ((IID == Intr ||
10977            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10978            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10979         N->getOperand(1)->getOpcode() == ISD::ADD) {
10980         SDValue Add = N->getOperand(1);
10981 
10982         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10983                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10984 
10985         if (DAG.MaskedValueIsZero(
10986                 Add->getOperand(1),
10987                 APInt::getAllOnesValue(Bits /* alignment */)
10988                     .zext(
10989                         Add.getValueType().getScalarType().getSizeInBits()))) {
10990           SDNode *BasePtr = Add->getOperand(0).getNode();
10991           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10992                                     UE = BasePtr->use_end();
10993                UI != UE; ++UI) {
10994             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10995                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10996               // We've found another LVSL/LVSR, and this address is an aligned
10997               // multiple of that one. The results will be the same, so use the
10998               // one we've just found instead.
10999 
11000               return SDValue(*UI, 0);
11001             }
11002           }
11003         }
11004 
11005         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11006           SDNode *BasePtr = Add->getOperand(0).getNode();
11007           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11008                UE = BasePtr->use_end(); UI != UE; ++UI) {
11009             if (UI->getOpcode() == ISD::ADD &&
11010                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11011                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11012                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11013                 (1ULL << Bits) == 0) {
11014               SDNode *OtherAdd = *UI;
11015               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11016                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11017                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11018                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11019                   return SDValue(*VI, 0);
11020                 }
11021               }
11022             }
11023           }
11024         }
11025       }
11026     }
11027 
11028     break;
11029   case ISD::INTRINSIC_W_CHAIN: {
11030     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11031     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
11032       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11033       default:
11034         break;
11035       case Intrinsic::ppc_vsx_lxvw4x:
11036       case Intrinsic::ppc_vsx_lxvd2x:
11037         return expandVSXLoadForLE(N, DCI);
11038       }
11039     }
11040     break;
11041   }
11042   case ISD::INTRINSIC_VOID: {
11043     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11044     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
11045       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11046       default:
11047         break;
11048       case Intrinsic::ppc_vsx_stxvw4x:
11049       case Intrinsic::ppc_vsx_stxvd2x:
11050         return expandVSXStoreForLE(N, DCI);
11051       }
11052     }
11053     break;
11054   }
11055   case ISD::BSWAP:
11056     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11057     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11058         N->getOperand(0).hasOneUse() &&
11059         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11060          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11061           N->getValueType(0) == MVT::i64))) {
11062       SDValue Load = N->getOperand(0);
11063       LoadSDNode *LD = cast<LoadSDNode>(Load);
11064       // Create the byte-swapping load.
11065       SDValue Ops[] = {
11066         LD->getChain(),    // Chain
11067         LD->getBasePtr(),  // Ptr
11068         DAG.getValueType(N->getValueType(0)) // VT
11069       };
11070       SDValue BSLoad =
11071         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11072                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11073                                               MVT::i64 : MVT::i32, MVT::Other),
11074                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11075 
11076       // If this is an i16 load, insert the truncate.
11077       SDValue ResVal = BSLoad;
11078       if (N->getValueType(0) == MVT::i16)
11079         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11080 
11081       // First, combine the bswap away.  This makes the value produced by the
11082       // load dead.
11083       DCI.CombineTo(N, ResVal);
11084 
11085       // Next, combine the load away, we give it a bogus result value but a real
11086       // chain result.  The result value is dead because the bswap is dead.
11087       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11088 
11089       // Return N so it doesn't get rechecked!
11090       return SDValue(N, 0);
11091     }
11092 
11093     break;
11094   case PPCISD::VCMP: {
11095     // If a VCMPo node already exists with exactly the same operands as this
11096     // node, use its result instead of this node (VCMPo computes both a CR6 and
11097     // a normal output).
11098     //
11099     if (!N->getOperand(0).hasOneUse() &&
11100         !N->getOperand(1).hasOneUse() &&
11101         !N->getOperand(2).hasOneUse()) {
11102 
11103       // Scan all of the users of the LHS, looking for VCMPo's that match.
11104       SDNode *VCMPoNode = nullptr;
11105 
11106       SDNode *LHSN = N->getOperand(0).getNode();
11107       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11108            UI != E; ++UI)
11109         if (UI->getOpcode() == PPCISD::VCMPo &&
11110             UI->getOperand(1) == N->getOperand(1) &&
11111             UI->getOperand(2) == N->getOperand(2) &&
11112             UI->getOperand(0) == N->getOperand(0)) {
11113           VCMPoNode = *UI;
11114           break;
11115         }
11116 
11117       // If there is no VCMPo node, or if the flag value has a single use, don't
11118       // transform this.
11119       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11120         break;
11121 
11122       // Look at the (necessarily single) use of the flag value.  If it has a
11123       // chain, this transformation is more complex.  Note that multiple things
11124       // could use the value result, which we should ignore.
11125       SDNode *FlagUser = nullptr;
11126       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11127            FlagUser == nullptr; ++UI) {
11128         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11129         SDNode *User = *UI;
11130         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11131           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11132             FlagUser = User;
11133             break;
11134           }
11135         }
11136       }
11137 
11138       // If the user is a MFOCRF instruction, we know this is safe.
11139       // Otherwise we give up for right now.
11140       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11141         return SDValue(VCMPoNode, 0);
11142     }
11143     break;
11144   }
11145   case ISD::BRCOND: {
11146     SDValue Cond = N->getOperand(1);
11147     SDValue Target = N->getOperand(2);
11148 
11149     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11150         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11151           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11152 
11153       // We now need to make the intrinsic dead (it cannot be instruction
11154       // selected).
11155       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11156       assert(Cond.getNode()->hasOneUse() &&
11157              "Counter decrement has more than one use");
11158 
11159       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11160                          N->getOperand(0), Target);
11161     }
11162   }
11163   break;
11164   case ISD::BR_CC: {
11165     // If this is a branch on an altivec predicate comparison, lower this so
11166     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11167     // lowering is done pre-legalize, because the legalizer lowers the predicate
11168     // compare down to code that is difficult to reassemble.
11169     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11170     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11171 
11172     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11173     // value. If so, pass-through the AND to get to the intrinsic.
11174     if (LHS.getOpcode() == ISD::AND &&
11175         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11176         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11177           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11178         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11179         !isNullConstant(LHS.getOperand(1)))
11180       LHS = LHS.getOperand(0);
11181 
11182     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11183         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11184           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11185         isa<ConstantSDNode>(RHS)) {
11186       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11187              "Counter decrement comparison is not EQ or NE");
11188 
11189       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11190       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11191                     (CC == ISD::SETNE && !Val);
11192 
11193       // We now need to make the intrinsic dead (it cannot be instruction
11194       // selected).
11195       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11196       assert(LHS.getNode()->hasOneUse() &&
11197              "Counter decrement has more than one use");
11198 
11199       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11200                          N->getOperand(0), N->getOperand(4));
11201     }
11202 
11203     int CompareOpc;
11204     bool isDot;
11205 
11206     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11207         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11208         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11209       assert(isDot && "Can't compare against a vector result!");
11210 
11211       // If this is a comparison against something other than 0/1, then we know
11212       // that the condition is never/always true.
11213       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11214       if (Val != 0 && Val != 1) {
11215         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11216           return N->getOperand(0);
11217         // Always !=, turn it into an unconditional branch.
11218         return DAG.getNode(ISD::BR, dl, MVT::Other,
11219                            N->getOperand(0), N->getOperand(4));
11220       }
11221 
11222       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11223 
11224       // Create the PPCISD altivec 'dot' comparison node.
11225       SDValue Ops[] = {
11226         LHS.getOperand(2),  // LHS of compare
11227         LHS.getOperand(3),  // RHS of compare
11228         DAG.getConstant(CompareOpc, dl, MVT::i32)
11229       };
11230       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11231       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11232 
11233       // Unpack the result based on how the target uses it.
11234       PPC::Predicate CompOpc;
11235       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11236       default:  // Can't happen, don't crash on invalid number though.
11237       case 0:   // Branch on the value of the EQ bit of CR6.
11238         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11239         break;
11240       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11241         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11242         break;
11243       case 2:   // Branch on the value of the LT bit of CR6.
11244         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11245         break;
11246       case 3:   // Branch on the inverted value of the LT bit of CR6.
11247         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11248         break;
11249       }
11250 
11251       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11252                          DAG.getConstant(CompOpc, dl, MVT::i32),
11253                          DAG.getRegister(PPC::CR6, MVT::i32),
11254                          N->getOperand(4), CompNode.getValue(1));
11255     }
11256     break;
11257   }
11258   case ISD::BUILD_VECTOR:
11259     return DAGCombineBuildVector(N, DCI);
11260   }
11261 
11262   return SDValue();
11263 }
11264 
11265 SDValue
11266 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11267                                   SelectionDAG &DAG,
11268                                   std::vector<SDNode *> *Created) const {
11269   // fold (sdiv X, pow2)
11270   EVT VT = N->getValueType(0);
11271   if (VT == MVT::i64 && !Subtarget.isPPC64())
11272     return SDValue();
11273   if ((VT != MVT::i32 && VT != MVT::i64) ||
11274       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11275     return SDValue();
11276 
11277   SDLoc DL(N);
11278   SDValue N0 = N->getOperand(0);
11279 
11280   bool IsNegPow2 = (-Divisor).isPowerOf2();
11281   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11282   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11283 
11284   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11285   if (Created)
11286     Created->push_back(Op.getNode());
11287 
11288   if (IsNegPow2) {
11289     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11290     if (Created)
11291       Created->push_back(Op.getNode());
11292   }
11293 
11294   return Op;
11295 }
11296 
11297 //===----------------------------------------------------------------------===//
11298 // Inline Assembly Support
11299 //===----------------------------------------------------------------------===//
11300 
11301 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11302                                                       APInt &KnownZero,
11303                                                       APInt &KnownOne,
11304                                                       const SelectionDAG &DAG,
11305                                                       unsigned Depth) const {
11306   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11307   switch (Op.getOpcode()) {
11308   default: break;
11309   case PPCISD::LBRX: {
11310     // lhbrx is known to have the top bits cleared out.
11311     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11312       KnownZero = 0xFFFF0000;
11313     break;
11314   }
11315   case ISD::INTRINSIC_WO_CHAIN: {
11316     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11317     default: break;
11318     case Intrinsic::ppc_altivec_vcmpbfp_p:
11319     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11320     case Intrinsic::ppc_altivec_vcmpequb_p:
11321     case Intrinsic::ppc_altivec_vcmpequh_p:
11322     case Intrinsic::ppc_altivec_vcmpequw_p:
11323     case Intrinsic::ppc_altivec_vcmpequd_p:
11324     case Intrinsic::ppc_altivec_vcmpgefp_p:
11325     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11326     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11327     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11328     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11329     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11330     case Intrinsic::ppc_altivec_vcmpgtub_p:
11331     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11332     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11333     case Intrinsic::ppc_altivec_vcmpgtud_p:
11334       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11335       break;
11336     }
11337   }
11338   }
11339 }
11340 
11341 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11342   switch (Subtarget.getDarwinDirective()) {
11343   default: break;
11344   case PPC::DIR_970:
11345   case PPC::DIR_PWR4:
11346   case PPC::DIR_PWR5:
11347   case PPC::DIR_PWR5X:
11348   case PPC::DIR_PWR6:
11349   case PPC::DIR_PWR6X:
11350   case PPC::DIR_PWR7:
11351   case PPC::DIR_PWR8:
11352   case PPC::DIR_PWR9: {
11353     if (!ML)
11354       break;
11355 
11356     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11357 
11358     // For small loops (between 5 and 8 instructions), align to a 32-byte
11359     // boundary so that the entire loop fits in one instruction-cache line.
11360     uint64_t LoopSize = 0;
11361     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11362       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11363         LoopSize += TII->getInstSizeInBytes(*J);
11364         if (LoopSize > 32)
11365           break;
11366       }
11367 
11368     if (LoopSize > 16 && LoopSize <= 32)
11369       return 5;
11370 
11371     break;
11372   }
11373   }
11374 
11375   return TargetLowering::getPrefLoopAlignment(ML);
11376 }
11377 
11378 /// getConstraintType - Given a constraint, return the type of
11379 /// constraint it is for this target.
11380 PPCTargetLowering::ConstraintType
11381 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11382   if (Constraint.size() == 1) {
11383     switch (Constraint[0]) {
11384     default: break;
11385     case 'b':
11386     case 'r':
11387     case 'f':
11388     case 'd':
11389     case 'v':
11390     case 'y':
11391       return C_RegisterClass;
11392     case 'Z':
11393       // FIXME: While Z does indicate a memory constraint, it specifically
11394       // indicates an r+r address (used in conjunction with the 'y' modifier
11395       // in the replacement string). Currently, we're forcing the base
11396       // register to be r0 in the asm printer (which is interpreted as zero)
11397       // and forming the complete address in the second register. This is
11398       // suboptimal.
11399       return C_Memory;
11400     }
11401   } else if (Constraint == "wc") { // individual CR bits.
11402     return C_RegisterClass;
11403   } else if (Constraint == "wa" || Constraint == "wd" ||
11404              Constraint == "wf" || Constraint == "ws") {
11405     return C_RegisterClass; // VSX registers.
11406   }
11407   return TargetLowering::getConstraintType(Constraint);
11408 }
11409 
11410 /// Examine constraint type and operand type and determine a weight value.
11411 /// This object must already have been set up with the operand type
11412 /// and the current alternative constraint selected.
11413 TargetLowering::ConstraintWeight
11414 PPCTargetLowering::getSingleConstraintMatchWeight(
11415     AsmOperandInfo &info, const char *constraint) const {
11416   ConstraintWeight weight = CW_Invalid;
11417   Value *CallOperandVal = info.CallOperandVal;
11418     // If we don't have a value, we can't do a match,
11419     // but allow it at the lowest weight.
11420   if (!CallOperandVal)
11421     return CW_Default;
11422   Type *type = CallOperandVal->getType();
11423 
11424   // Look at the constraint type.
11425   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11426     return CW_Register; // an individual CR bit.
11427   else if ((StringRef(constraint) == "wa" ||
11428             StringRef(constraint) == "wd" ||
11429             StringRef(constraint) == "wf") &&
11430            type->isVectorTy())
11431     return CW_Register;
11432   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11433     return CW_Register;
11434 
11435   switch (*constraint) {
11436   default:
11437     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11438     break;
11439   case 'b':
11440     if (type->isIntegerTy())
11441       weight = CW_Register;
11442     break;
11443   case 'f':
11444     if (type->isFloatTy())
11445       weight = CW_Register;
11446     break;
11447   case 'd':
11448     if (type->isDoubleTy())
11449       weight = CW_Register;
11450     break;
11451   case 'v':
11452     if (type->isVectorTy())
11453       weight = CW_Register;
11454     break;
11455   case 'y':
11456     weight = CW_Register;
11457     break;
11458   case 'Z':
11459     weight = CW_Memory;
11460     break;
11461   }
11462   return weight;
11463 }
11464 
11465 std::pair<unsigned, const TargetRegisterClass *>
11466 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11467                                                 StringRef Constraint,
11468                                                 MVT VT) const {
11469   if (Constraint.size() == 1) {
11470     // GCC RS6000 Constraint Letters
11471     switch (Constraint[0]) {
11472     case 'b':   // R1-R31
11473       if (VT == MVT::i64 && Subtarget.isPPC64())
11474         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11475       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11476     case 'r':   // R0-R31
11477       if (VT == MVT::i64 && Subtarget.isPPC64())
11478         return std::make_pair(0U, &PPC::G8RCRegClass);
11479       return std::make_pair(0U, &PPC::GPRCRegClass);
11480     // 'd' and 'f' constraints are both defined to be "the floating point
11481     // registers", where one is for 32-bit and the other for 64-bit. We don't
11482     // really care overly much here so just give them all the same reg classes.
11483     case 'd':
11484     case 'f':
11485       if (VT == MVT::f32 || VT == MVT::i32)
11486         return std::make_pair(0U, &PPC::F4RCRegClass);
11487       if (VT == MVT::f64 || VT == MVT::i64)
11488         return std::make_pair(0U, &PPC::F8RCRegClass);
11489       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11490         return std::make_pair(0U, &PPC::QFRCRegClass);
11491       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11492         return std::make_pair(0U, &PPC::QSRCRegClass);
11493       break;
11494     case 'v':
11495       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11496         return std::make_pair(0U, &PPC::QFRCRegClass);
11497       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11498         return std::make_pair(0U, &PPC::QSRCRegClass);
11499       if (Subtarget.hasAltivec())
11500         return std::make_pair(0U, &PPC::VRRCRegClass);
11501     case 'y':   // crrc
11502       return std::make_pair(0U, &PPC::CRRCRegClass);
11503     }
11504   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11505     // An individual CR bit.
11506     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11507   } else if ((Constraint == "wa" || Constraint == "wd" ||
11508              Constraint == "wf") && Subtarget.hasVSX()) {
11509     return std::make_pair(0U, &PPC::VSRCRegClass);
11510   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11511     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11512       return std::make_pair(0U, &PPC::VSSRCRegClass);
11513     else
11514       return std::make_pair(0U, &PPC::VSFRCRegClass);
11515   }
11516 
11517   std::pair<unsigned, const TargetRegisterClass *> R =
11518       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11519 
11520   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11521   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11522   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11523   // register.
11524   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11525   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11526   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11527       PPC::GPRCRegClass.contains(R.first))
11528     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11529                             PPC::sub_32, &PPC::G8RCRegClass),
11530                           &PPC::G8RCRegClass);
11531 
11532   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11533   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11534     R.first = PPC::CR0;
11535     R.second = &PPC::CRRCRegClass;
11536   }
11537 
11538   return R;
11539 }
11540 
11541 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11542 /// vector.  If it is invalid, don't add anything to Ops.
11543 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11544                                                      std::string &Constraint,
11545                                                      std::vector<SDValue>&Ops,
11546                                                      SelectionDAG &DAG) const {
11547   SDValue Result;
11548 
11549   // Only support length 1 constraints.
11550   if (Constraint.length() > 1) return;
11551 
11552   char Letter = Constraint[0];
11553   switch (Letter) {
11554   default: break;
11555   case 'I':
11556   case 'J':
11557   case 'K':
11558   case 'L':
11559   case 'M':
11560   case 'N':
11561   case 'O':
11562   case 'P': {
11563     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11564     if (!CST) return; // Must be an immediate to match.
11565     SDLoc dl(Op);
11566     int64_t Value = CST->getSExtValue();
11567     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11568                          // numbers are printed as such.
11569     switch (Letter) {
11570     default: llvm_unreachable("Unknown constraint letter!");
11571     case 'I':  // "I" is a signed 16-bit constant.
11572       if (isInt<16>(Value))
11573         Result = DAG.getTargetConstant(Value, dl, TCVT);
11574       break;
11575     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11576       if (isShiftedUInt<16, 16>(Value))
11577         Result = DAG.getTargetConstant(Value, dl, TCVT);
11578       break;
11579     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11580       if (isShiftedInt<16, 16>(Value))
11581         Result = DAG.getTargetConstant(Value, dl, TCVT);
11582       break;
11583     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11584       if (isUInt<16>(Value))
11585         Result = DAG.getTargetConstant(Value, dl, TCVT);
11586       break;
11587     case 'M':  // "M" is a constant that is greater than 31.
11588       if (Value > 31)
11589         Result = DAG.getTargetConstant(Value, dl, TCVT);
11590       break;
11591     case 'N':  // "N" is a positive constant that is an exact power of two.
11592       if (Value > 0 && isPowerOf2_64(Value))
11593         Result = DAG.getTargetConstant(Value, dl, TCVT);
11594       break;
11595     case 'O':  // "O" is the constant zero.
11596       if (Value == 0)
11597         Result = DAG.getTargetConstant(Value, dl, TCVT);
11598       break;
11599     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11600       if (isInt<16>(-Value))
11601         Result = DAG.getTargetConstant(Value, dl, TCVT);
11602       break;
11603     }
11604     break;
11605   }
11606   }
11607 
11608   if (Result.getNode()) {
11609     Ops.push_back(Result);
11610     return;
11611   }
11612 
11613   // Handle standard constraint letters.
11614   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11615 }
11616 
11617 // isLegalAddressingMode - Return true if the addressing mode represented
11618 // by AM is legal for this target, for a load/store of the specified type.
11619 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11620                                               const AddrMode &AM, Type *Ty,
11621                                               unsigned AS) const {
11622   // PPC does not allow r+i addressing modes for vectors!
11623   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11624     return false;
11625 
11626   // PPC allows a sign-extended 16-bit immediate field.
11627   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11628     return false;
11629 
11630   // No global is ever allowed as a base.
11631   if (AM.BaseGV)
11632     return false;
11633 
11634   // PPC only support r+r,
11635   switch (AM.Scale) {
11636   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11637     break;
11638   case 1:
11639     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11640       return false;
11641     // Otherwise we have r+r or r+i.
11642     break;
11643   case 2:
11644     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11645       return false;
11646     // Allow 2*r as r+r.
11647     break;
11648   default:
11649     // No other scales are supported.
11650     return false;
11651   }
11652 
11653   return true;
11654 }
11655 
11656 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11657                                            SelectionDAG &DAG) const {
11658   MachineFunction &MF = DAG.getMachineFunction();
11659   MachineFrameInfo &MFI = MF.getFrameInfo();
11660   MFI.setReturnAddressIsTaken(true);
11661 
11662   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11663     return SDValue();
11664 
11665   SDLoc dl(Op);
11666   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11667 
11668   // Make sure the function does not optimize away the store of the RA to
11669   // the stack.
11670   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11671   FuncInfo->setLRStoreRequired();
11672   bool isPPC64 = Subtarget.isPPC64();
11673   auto PtrVT = getPointerTy(MF.getDataLayout());
11674 
11675   if (Depth > 0) {
11676     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11677     SDValue Offset =
11678         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11679                         isPPC64 ? MVT::i64 : MVT::i32);
11680     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11681                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11682                        MachinePointerInfo());
11683   }
11684 
11685   // Just load the return address off the stack.
11686   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11687   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11688                      MachinePointerInfo());
11689 }
11690 
11691 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11692                                           SelectionDAG &DAG) const {
11693   SDLoc dl(Op);
11694   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11695 
11696   MachineFunction &MF = DAG.getMachineFunction();
11697   MachineFrameInfo &MFI = MF.getFrameInfo();
11698   MFI.setFrameAddressIsTaken(true);
11699 
11700   EVT PtrVT = getPointerTy(MF.getDataLayout());
11701   bool isPPC64 = PtrVT == MVT::i64;
11702 
11703   // Naked functions never have a frame pointer, and so we use r1. For all
11704   // other functions, this decision must be delayed until during PEI.
11705   unsigned FrameReg;
11706   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11707     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11708   else
11709     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11710 
11711   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11712                                          PtrVT);
11713   while (Depth--)
11714     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11715                             FrameAddr, MachinePointerInfo());
11716   return FrameAddr;
11717 }
11718 
11719 // FIXME? Maybe this could be a TableGen attribute on some registers and
11720 // this table could be generated automatically from RegInfo.
11721 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11722                                               SelectionDAG &DAG) const {
11723   bool isPPC64 = Subtarget.isPPC64();
11724   bool isDarwinABI = Subtarget.isDarwinABI();
11725 
11726   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11727       (!isPPC64 && VT != MVT::i32))
11728     report_fatal_error("Invalid register global variable type");
11729 
11730   bool is64Bit = isPPC64 && VT == MVT::i64;
11731   unsigned Reg = StringSwitch<unsigned>(RegName)
11732                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11733                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11734                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11735                                   (is64Bit ? PPC::X13 : PPC::R13))
11736                    .Default(0);
11737 
11738   if (Reg)
11739     return Reg;
11740   report_fatal_error("Invalid register name global variable");
11741 }
11742 
11743 bool
11744 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11745   // The PowerPC target isn't yet aware of offsets.
11746   return false;
11747 }
11748 
11749 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11750                                            const CallInst &I,
11751                                            unsigned Intrinsic) const {
11752 
11753   switch (Intrinsic) {
11754   case Intrinsic::ppc_qpx_qvlfd:
11755   case Intrinsic::ppc_qpx_qvlfs:
11756   case Intrinsic::ppc_qpx_qvlfcd:
11757   case Intrinsic::ppc_qpx_qvlfcs:
11758   case Intrinsic::ppc_qpx_qvlfiwa:
11759   case Intrinsic::ppc_qpx_qvlfiwz:
11760   case Intrinsic::ppc_altivec_lvx:
11761   case Intrinsic::ppc_altivec_lvxl:
11762   case Intrinsic::ppc_altivec_lvebx:
11763   case Intrinsic::ppc_altivec_lvehx:
11764   case Intrinsic::ppc_altivec_lvewx:
11765   case Intrinsic::ppc_vsx_lxvd2x:
11766   case Intrinsic::ppc_vsx_lxvw4x: {
11767     EVT VT;
11768     switch (Intrinsic) {
11769     case Intrinsic::ppc_altivec_lvebx:
11770       VT = MVT::i8;
11771       break;
11772     case Intrinsic::ppc_altivec_lvehx:
11773       VT = MVT::i16;
11774       break;
11775     case Intrinsic::ppc_altivec_lvewx:
11776       VT = MVT::i32;
11777       break;
11778     case Intrinsic::ppc_vsx_lxvd2x:
11779       VT = MVT::v2f64;
11780       break;
11781     case Intrinsic::ppc_qpx_qvlfd:
11782       VT = MVT::v4f64;
11783       break;
11784     case Intrinsic::ppc_qpx_qvlfs:
11785       VT = MVT::v4f32;
11786       break;
11787     case Intrinsic::ppc_qpx_qvlfcd:
11788       VT = MVT::v2f64;
11789       break;
11790     case Intrinsic::ppc_qpx_qvlfcs:
11791       VT = MVT::v2f32;
11792       break;
11793     default:
11794       VT = MVT::v4i32;
11795       break;
11796     }
11797 
11798     Info.opc = ISD::INTRINSIC_W_CHAIN;
11799     Info.memVT = VT;
11800     Info.ptrVal = I.getArgOperand(0);
11801     Info.offset = -VT.getStoreSize()+1;
11802     Info.size = 2*VT.getStoreSize()-1;
11803     Info.align = 1;
11804     Info.vol = false;
11805     Info.readMem = true;
11806     Info.writeMem = false;
11807     return true;
11808   }
11809   case Intrinsic::ppc_qpx_qvlfda:
11810   case Intrinsic::ppc_qpx_qvlfsa:
11811   case Intrinsic::ppc_qpx_qvlfcda:
11812   case Intrinsic::ppc_qpx_qvlfcsa:
11813   case Intrinsic::ppc_qpx_qvlfiwaa:
11814   case Intrinsic::ppc_qpx_qvlfiwza: {
11815     EVT VT;
11816     switch (Intrinsic) {
11817     case Intrinsic::ppc_qpx_qvlfda:
11818       VT = MVT::v4f64;
11819       break;
11820     case Intrinsic::ppc_qpx_qvlfsa:
11821       VT = MVT::v4f32;
11822       break;
11823     case Intrinsic::ppc_qpx_qvlfcda:
11824       VT = MVT::v2f64;
11825       break;
11826     case Intrinsic::ppc_qpx_qvlfcsa:
11827       VT = MVT::v2f32;
11828       break;
11829     default:
11830       VT = MVT::v4i32;
11831       break;
11832     }
11833 
11834     Info.opc = ISD::INTRINSIC_W_CHAIN;
11835     Info.memVT = VT;
11836     Info.ptrVal = I.getArgOperand(0);
11837     Info.offset = 0;
11838     Info.size = VT.getStoreSize();
11839     Info.align = 1;
11840     Info.vol = false;
11841     Info.readMem = true;
11842     Info.writeMem = false;
11843     return true;
11844   }
11845   case Intrinsic::ppc_qpx_qvstfd:
11846   case Intrinsic::ppc_qpx_qvstfs:
11847   case Intrinsic::ppc_qpx_qvstfcd:
11848   case Intrinsic::ppc_qpx_qvstfcs:
11849   case Intrinsic::ppc_qpx_qvstfiw:
11850   case Intrinsic::ppc_altivec_stvx:
11851   case Intrinsic::ppc_altivec_stvxl:
11852   case Intrinsic::ppc_altivec_stvebx:
11853   case Intrinsic::ppc_altivec_stvehx:
11854   case Intrinsic::ppc_altivec_stvewx:
11855   case Intrinsic::ppc_vsx_stxvd2x:
11856   case Intrinsic::ppc_vsx_stxvw4x: {
11857     EVT VT;
11858     switch (Intrinsic) {
11859     case Intrinsic::ppc_altivec_stvebx:
11860       VT = MVT::i8;
11861       break;
11862     case Intrinsic::ppc_altivec_stvehx:
11863       VT = MVT::i16;
11864       break;
11865     case Intrinsic::ppc_altivec_stvewx:
11866       VT = MVT::i32;
11867       break;
11868     case Intrinsic::ppc_vsx_stxvd2x:
11869       VT = MVT::v2f64;
11870       break;
11871     case Intrinsic::ppc_qpx_qvstfd:
11872       VT = MVT::v4f64;
11873       break;
11874     case Intrinsic::ppc_qpx_qvstfs:
11875       VT = MVT::v4f32;
11876       break;
11877     case Intrinsic::ppc_qpx_qvstfcd:
11878       VT = MVT::v2f64;
11879       break;
11880     case Intrinsic::ppc_qpx_qvstfcs:
11881       VT = MVT::v2f32;
11882       break;
11883     default:
11884       VT = MVT::v4i32;
11885       break;
11886     }
11887 
11888     Info.opc = ISD::INTRINSIC_VOID;
11889     Info.memVT = VT;
11890     Info.ptrVal = I.getArgOperand(1);
11891     Info.offset = -VT.getStoreSize()+1;
11892     Info.size = 2*VT.getStoreSize()-1;
11893     Info.align = 1;
11894     Info.vol = false;
11895     Info.readMem = false;
11896     Info.writeMem = true;
11897     return true;
11898   }
11899   case Intrinsic::ppc_qpx_qvstfda:
11900   case Intrinsic::ppc_qpx_qvstfsa:
11901   case Intrinsic::ppc_qpx_qvstfcda:
11902   case Intrinsic::ppc_qpx_qvstfcsa:
11903   case Intrinsic::ppc_qpx_qvstfiwa: {
11904     EVT VT;
11905     switch (Intrinsic) {
11906     case Intrinsic::ppc_qpx_qvstfda:
11907       VT = MVT::v4f64;
11908       break;
11909     case Intrinsic::ppc_qpx_qvstfsa:
11910       VT = MVT::v4f32;
11911       break;
11912     case Intrinsic::ppc_qpx_qvstfcda:
11913       VT = MVT::v2f64;
11914       break;
11915     case Intrinsic::ppc_qpx_qvstfcsa:
11916       VT = MVT::v2f32;
11917       break;
11918     default:
11919       VT = MVT::v4i32;
11920       break;
11921     }
11922 
11923     Info.opc = ISD::INTRINSIC_VOID;
11924     Info.memVT = VT;
11925     Info.ptrVal = I.getArgOperand(1);
11926     Info.offset = 0;
11927     Info.size = VT.getStoreSize();
11928     Info.align = 1;
11929     Info.vol = false;
11930     Info.readMem = false;
11931     Info.writeMem = true;
11932     return true;
11933   }
11934   default:
11935     break;
11936   }
11937 
11938   return false;
11939 }
11940 
11941 /// getOptimalMemOpType - Returns the target specific optimal type for load
11942 /// and store operations as a result of memset, memcpy, and memmove
11943 /// lowering. If DstAlign is zero that means it's safe to destination
11944 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11945 /// means there isn't a need to check it against alignment requirement,
11946 /// probably because the source does not need to be loaded. If 'IsMemset' is
11947 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11948 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11949 /// source is constant so it does not need to be loaded.
11950 /// It returns EVT::Other if the type should be determined using generic
11951 /// target-independent logic.
11952 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11953                                            unsigned DstAlign, unsigned SrcAlign,
11954                                            bool IsMemset, bool ZeroMemset,
11955                                            bool MemcpyStrSrc,
11956                                            MachineFunction &MF) const {
11957   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11958     const Function *F = MF.getFunction();
11959     // When expanding a memset, require at least two QPX instructions to cover
11960     // the cost of loading the value to be stored from the constant pool.
11961     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11962        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11963         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11964       return MVT::v4f64;
11965     }
11966 
11967     // We should use Altivec/VSX loads and stores when available. For unaligned
11968     // addresses, unaligned VSX loads are only fast starting with the P8.
11969     if (Subtarget.hasAltivec() && Size >= 16 &&
11970         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11971          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11972       return MVT::v4i32;
11973   }
11974 
11975   if (Subtarget.isPPC64()) {
11976     return MVT::i64;
11977   }
11978 
11979   return MVT::i32;
11980 }
11981 
11982 /// \brief Returns true if it is beneficial to convert a load of a constant
11983 /// to just the constant itself.
11984 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11985                                                           Type *Ty) const {
11986   assert(Ty->isIntegerTy());
11987 
11988   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11989   return !(BitSize == 0 || BitSize > 64);
11990 }
11991 
11992 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11993   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11994     return false;
11995   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11996   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11997   return NumBits1 == 64 && NumBits2 == 32;
11998 }
11999 
12000 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12001   if (!VT1.isInteger() || !VT2.isInteger())
12002     return false;
12003   unsigned NumBits1 = VT1.getSizeInBits();
12004   unsigned NumBits2 = VT2.getSizeInBits();
12005   return NumBits1 == 64 && NumBits2 == 32;
12006 }
12007 
12008 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12009   // Generally speaking, zexts are not free, but they are free when they can be
12010   // folded with other operations.
12011   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12012     EVT MemVT = LD->getMemoryVT();
12013     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12014          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12015         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12016          LD->getExtensionType() == ISD::ZEXTLOAD))
12017       return true;
12018   }
12019 
12020   // FIXME: Add other cases...
12021   //  - 32-bit shifts with a zext to i64
12022   //  - zext after ctlz, bswap, etc.
12023   //  - zext after and by a constant mask
12024 
12025   return TargetLowering::isZExtFree(Val, VT2);
12026 }
12027 
12028 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12029   assert(VT.isFloatingPoint());
12030   return true;
12031 }
12032 
12033 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12034   return isInt<16>(Imm) || isUInt<16>(Imm);
12035 }
12036 
12037 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12038   return isInt<16>(Imm) || isUInt<16>(Imm);
12039 }
12040 
12041 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12042                                                        unsigned,
12043                                                        unsigned,
12044                                                        bool *Fast) const {
12045   if (DisablePPCUnaligned)
12046     return false;
12047 
12048   // PowerPC supports unaligned memory access for simple non-vector types.
12049   // Although accessing unaligned addresses is not as efficient as accessing
12050   // aligned addresses, it is generally more efficient than manual expansion,
12051   // and generally only traps for software emulation when crossing page
12052   // boundaries.
12053 
12054   if (!VT.isSimple())
12055     return false;
12056 
12057   if (VT.getSimpleVT().isVector()) {
12058     if (Subtarget.hasVSX()) {
12059       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12060           VT != MVT::v4f32 && VT != MVT::v4i32)
12061         return false;
12062     } else {
12063       return false;
12064     }
12065   }
12066 
12067   if (VT == MVT::ppcf128)
12068     return false;
12069 
12070   if (Fast)
12071     *Fast = true;
12072 
12073   return true;
12074 }
12075 
12076 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12077   VT = VT.getScalarType();
12078 
12079   if (!VT.isSimple())
12080     return false;
12081 
12082   switch (VT.getSimpleVT().SimpleTy) {
12083   case MVT::f32:
12084   case MVT::f64:
12085     return true;
12086   default:
12087     break;
12088   }
12089 
12090   return false;
12091 }
12092 
12093 const MCPhysReg *
12094 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12095   // LR is a callee-save register, but we must treat it as clobbered by any call
12096   // site. Hence we include LR in the scratch registers, which are in turn added
12097   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12098   // to CTR, which is used by any indirect call.
12099   static const MCPhysReg ScratchRegs[] = {
12100     PPC::X12, PPC::LR8, PPC::CTR8, 0
12101   };
12102 
12103   return ScratchRegs;
12104 }
12105 
12106 unsigned PPCTargetLowering::getExceptionPointerRegister(
12107     const Constant *PersonalityFn) const {
12108   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12109 }
12110 
12111 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12112     const Constant *PersonalityFn) const {
12113   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12114 }
12115 
12116 bool
12117 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12118                      EVT VT , unsigned DefinedValues) const {
12119   if (VT == MVT::v2i64)
12120     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12121 
12122   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12123     return true;
12124 
12125   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12126 }
12127 
12128 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12129   if (DisableILPPref || Subtarget.enableMachineScheduler())
12130     return TargetLowering::getSchedulingPreference(N);
12131 
12132   return Sched::ILP;
12133 }
12134 
12135 // Create a fast isel object.
12136 FastISel *
12137 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12138                                   const TargetLibraryInfo *LibInfo) const {
12139   return PPC::createFastISel(FuncInfo, LibInfo);
12140 }
12141 
12142 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12143   if (Subtarget.isDarwinABI()) return;
12144   if (!Subtarget.isPPC64()) return;
12145 
12146   // Update IsSplitCSR in PPCFunctionInfo
12147   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12148   PFI->setIsSplitCSR(true);
12149 }
12150 
12151 void PPCTargetLowering::insertCopiesSplitCSR(
12152   MachineBasicBlock *Entry,
12153   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12154   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12155   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12156   if (!IStart)
12157     return;
12158 
12159   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12160   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12161   MachineBasicBlock::iterator MBBI = Entry->begin();
12162   for (const MCPhysReg *I = IStart; *I; ++I) {
12163     const TargetRegisterClass *RC = nullptr;
12164     if (PPC::G8RCRegClass.contains(*I))
12165       RC = &PPC::G8RCRegClass;
12166     else if (PPC::F8RCRegClass.contains(*I))
12167       RC = &PPC::F8RCRegClass;
12168     else if (PPC::CRRCRegClass.contains(*I))
12169       RC = &PPC::CRRCRegClass;
12170     else if (PPC::VRRCRegClass.contains(*I))
12171       RC = &PPC::VRRCRegClass;
12172     else
12173       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12174 
12175     unsigned NewVR = MRI->createVirtualRegister(RC);
12176     // Create copy from CSR to a virtual register.
12177     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12178     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12179     // nounwind. If we want to generalize this later, we may need to emit
12180     // CFI pseudo-instructions.
12181     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12182              Attribute::NoUnwind) &&
12183            "Function should be nounwind in insertCopiesSplitCSR!");
12184     Entry->addLiveIn(*I);
12185     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12186       .addReg(*I);
12187 
12188     // Insert the copy-back instructions right before the terminator
12189     for (auto *Exit : Exits)
12190       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12191               TII->get(TargetOpcode::COPY), *I)
12192         .addReg(NewVR);
12193   }
12194 }
12195 
12196 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12197 bool PPCTargetLowering::useLoadStackGuardNode() const {
12198   if (!Subtarget.isTargetLinux())
12199     return TargetLowering::useLoadStackGuardNode();
12200   return true;
12201 }
12202 
12203 // Override to disable global variable loading on Linux.
12204 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12205   if (!Subtarget.isTargetLinux())
12206     return TargetLowering::insertSSPDeclarations(M);
12207 }
12208