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/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include <list>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "ppc-lowering"
51 
52 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
53 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
54 
55 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
56 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
57 
58 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
59 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
60 
61 static cl::opt<bool> DisableSCO("disable-ppc-sco",
62 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
63 
64 STATISTIC(NumTailCalls, "Number of tail calls");
65 STATISTIC(NumSiblingCalls, "Number of sibling calls");
66 
67 // FIXME: Remove this once the bug has been fixed!
68 extern cl::opt<bool> ANDIGlueBug;
69 
70 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
71                                      const PPCSubtarget &STI)
72     : TargetLowering(TM), Subtarget(STI) {
73   // Use _setjmp/_longjmp instead of setjmp/longjmp.
74   setUseUnderscoreSetJmp(true);
75   setUseUnderscoreLongJmp(true);
76 
77   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
78   // arguments are at least 4/8 bytes aligned.
79   bool isPPC64 = Subtarget.isPPC64();
80   setMinStackArgumentAlignment(isPPC64 ? 8:4);
81 
82   // Set up the register classes.
83   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
84   if (!useSoftFloat()) {
85     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
86     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
87   }
88 
89   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
90   for (MVT VT : MVT::integer_valuetypes()) {
91     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
92     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
93   }
94 
95   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
96 
97   // PowerPC has pre-inc load and store's.
98   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
99   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
100   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
101   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
102   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
103   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
104   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
105   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
106   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
107   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
108   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
109   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
110   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
111   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
112 
113   if (Subtarget.useCRBits()) {
114     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
115 
116     if (isPPC64 || Subtarget.hasFPCVT()) {
117       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
118       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
119                          isPPC64 ? MVT::i64 : MVT::i32);
120       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
121       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
122                         isPPC64 ? MVT::i64 : MVT::i32);
123     } else {
124       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
125       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
126     }
127 
128     // PowerPC does not support direct load / store of condition registers
129     setOperationAction(ISD::LOAD, MVT::i1, Custom);
130     setOperationAction(ISD::STORE, MVT::i1, Custom);
131 
132     // FIXME: Remove this once the ANDI glue bug is fixed:
133     if (ANDIGlueBug)
134       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
135 
136     for (MVT VT : MVT::integer_valuetypes()) {
137       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
138       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
139       setTruncStoreAction(VT, MVT::i1, Expand);
140     }
141 
142     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
143   }
144 
145   // This is used in the ppcf128->int sequence.  Note it has different semantics
146   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
147   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
148 
149   // We do not currently implement these libm ops for PowerPC.
150   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
151   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
152   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
153   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
154   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
155   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
156 
157   // PowerPC has no SREM/UREM instructions
158   setOperationAction(ISD::SREM, MVT::i32, Expand);
159   setOperationAction(ISD::UREM, MVT::i32, Expand);
160   setOperationAction(ISD::SREM, MVT::i64, Expand);
161   setOperationAction(ISD::UREM, MVT::i64, Expand);
162 
163   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
164   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
165   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
166   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
167   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
168   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
169   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
170   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
171   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
172 
173   // We don't support sin/cos/sqrt/fmod/pow
174   setOperationAction(ISD::FSIN , MVT::f64, Expand);
175   setOperationAction(ISD::FCOS , MVT::f64, Expand);
176   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
177   setOperationAction(ISD::FREM , MVT::f64, Expand);
178   setOperationAction(ISD::FPOW , MVT::f64, Expand);
179   setOperationAction(ISD::FMA  , MVT::f64, Legal);
180   setOperationAction(ISD::FSIN , MVT::f32, Expand);
181   setOperationAction(ISD::FCOS , MVT::f32, Expand);
182   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
183   setOperationAction(ISD::FREM , MVT::f32, Expand);
184   setOperationAction(ISD::FPOW , MVT::f32, Expand);
185   setOperationAction(ISD::FMA  , MVT::f32, Legal);
186 
187   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
188 
189   // If we're enabling GP optimizations, use hardware square root
190   if (!Subtarget.hasFSQRT() &&
191       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
192         Subtarget.hasFRE()))
193     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
194 
195   if (!Subtarget.hasFSQRT() &&
196       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
197         Subtarget.hasFRES()))
198     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
199 
200   if (Subtarget.hasFCPSGN()) {
201     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
202     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
203   } else {
204     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
205     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
206   }
207 
208   if (Subtarget.hasFPRND()) {
209     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
210     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
211     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
212     setOperationAction(ISD::FROUND, MVT::f64, Legal);
213 
214     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
215     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
216     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
217     setOperationAction(ISD::FROUND, MVT::f32, Legal);
218   }
219 
220   // PowerPC does not have BSWAP
221   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
222   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
223   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
224   if (Subtarget.isISA3_0()) {
225     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
226     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
227   } else {
228     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
229     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
230   }
231 
232   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
233     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
234     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
235   } else {
236     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
237     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
238   }
239 
240   // PowerPC does not have ROTR
241   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
242   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
243 
244   if (!Subtarget.useCRBits()) {
245     // PowerPC does not have Select
246     setOperationAction(ISD::SELECT, MVT::i32, Expand);
247     setOperationAction(ISD::SELECT, MVT::i64, Expand);
248     setOperationAction(ISD::SELECT, MVT::f32, Expand);
249     setOperationAction(ISD::SELECT, MVT::f64, Expand);
250   }
251 
252   // PowerPC wants to turn select_cc of FP into fsel when possible.
253   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
254   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
255 
256   // PowerPC wants to optimize integer setcc a bit
257   if (!Subtarget.useCRBits())
258     setOperationAction(ISD::SETCC, MVT::i32, Custom);
259 
260   // PowerPC does not have BRCOND which requires SetCC
261   if (!Subtarget.useCRBits())
262     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
263 
264   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
265 
266   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
267   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
268 
269   // PowerPC does not have [U|S]INT_TO_FP
270   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
271   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
272 
273   if (Subtarget.hasDirectMove() && isPPC64) {
274     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
275     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
276     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
277     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
278   } else {
279     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
280     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
281     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
282     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
283   }
284 
285   // We cannot sextinreg(i1).  Expand to shifts.
286   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
287 
288   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
289   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
290   // support continuation, user-level threading, and etc.. As a result, no
291   // other SjLj exception interfaces are implemented and please don't build
292   // your own exception handling based on them.
293   // LLVM/Clang supports zero-cost DWARF exception handling.
294   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
295   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
296 
297   // We want to legalize GlobalAddress and ConstantPool nodes into the
298   // appropriate instructions to materialize the address.
299   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
300   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
301   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
302   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
303   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
304   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
305   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
306   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
307   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
308   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
309 
310   // TRAP is legal.
311   setOperationAction(ISD::TRAP, MVT::Other, Legal);
312 
313   // TRAMPOLINE is custom lowered.
314   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
315   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
316 
317   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
318   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
319 
320   if (Subtarget.isSVR4ABI()) {
321     if (isPPC64) {
322       // VAARG always uses double-word chunks, so promote anything smaller.
323       setOperationAction(ISD::VAARG, MVT::i1, Promote);
324       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
325       setOperationAction(ISD::VAARG, MVT::i8, Promote);
326       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
327       setOperationAction(ISD::VAARG, MVT::i16, Promote);
328       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
329       setOperationAction(ISD::VAARG, MVT::i32, Promote);
330       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
331       setOperationAction(ISD::VAARG, MVT::Other, Expand);
332     } else {
333       // VAARG is custom lowered with the 32-bit SVR4 ABI.
334       setOperationAction(ISD::VAARG, MVT::Other, Custom);
335       setOperationAction(ISD::VAARG, MVT::i64, Custom);
336     }
337   } else
338     setOperationAction(ISD::VAARG, MVT::Other, Expand);
339 
340   if (Subtarget.isSVR4ABI() && !isPPC64)
341     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
342     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
343   else
344     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
345 
346   // Use the default implementation.
347   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
348   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
349   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
350   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
351   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
352   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
353   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
354   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
355   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
356 
357   // We want to custom lower some of our intrinsics.
358   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
359 
360   // To handle counter-based loop conditions.
361   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
362 
363   // Comparisons that require checking two conditions.
364   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
365   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
366   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
367   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
368   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
369   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
370   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
371   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
372   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
373   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
374   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
375   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
376 
377   if (Subtarget.has64BitSupport()) {
378     // They also have instructions for converting between i64 and fp.
379     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
380     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
383     // This is just the low 32 bits of a (signed) fp->i64 conversion.
384     // We cannot do this with Promote because i64 is not a legal type.
385     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
386 
387     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
388       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
389   } else {
390     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
391     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
392   }
393 
394   // With the instructions enabled under FPCVT, we can do everything.
395   if (Subtarget.hasFPCVT()) {
396     if (Subtarget.has64BitSupport()) {
397       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
398       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
399       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
400       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
401     }
402 
403     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
404     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
405     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
406     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
407   }
408 
409   if (Subtarget.use64BitRegs()) {
410     // 64-bit PowerPC implementations can support i64 types directly
411     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
412     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
413     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
414     // 64-bit PowerPC wants to expand i128 shifts itself.
415     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
416     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
417     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
418   } else {
419     // 32-bit PowerPC wants to expand i64 shifts itself.
420     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
421     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
422     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
423   }
424 
425   if (Subtarget.hasAltivec()) {
426     // First set operation action for all vector types to expand. Then we
427     // will selectively turn on ones that can be effectively codegen'd.
428     for (MVT VT : MVT::vector_valuetypes()) {
429       // add/sub are legal for all supported vector VT's.
430       setOperationAction(ISD::ADD, VT, Legal);
431       setOperationAction(ISD::SUB, VT, Legal);
432 
433       // Vector instructions introduced in P8
434       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
435         setOperationAction(ISD::CTPOP, VT, Legal);
436         setOperationAction(ISD::CTLZ, VT, Legal);
437       }
438       else {
439         setOperationAction(ISD::CTPOP, VT, Expand);
440         setOperationAction(ISD::CTLZ, VT, Expand);
441       }
442 
443       // Vector instructions introduced in P9
444       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
445         setOperationAction(ISD::CTTZ, VT, Legal);
446       else
447         setOperationAction(ISD::CTTZ, VT, Expand);
448 
449       // We promote all shuffles to v16i8.
450       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
451       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
452 
453       // We promote all non-typed operations to v4i32.
454       setOperationAction(ISD::AND   , VT, Promote);
455       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
456       setOperationAction(ISD::OR    , VT, Promote);
457       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
458       setOperationAction(ISD::XOR   , VT, Promote);
459       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
460       setOperationAction(ISD::LOAD  , VT, Promote);
461       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
462       setOperationAction(ISD::SELECT, VT, Promote);
463       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
464       setOperationAction(ISD::SELECT_CC, VT, Promote);
465       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
466       setOperationAction(ISD::STORE, VT, Promote);
467       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
468 
469       // No other operations are legal.
470       setOperationAction(ISD::MUL , VT, Expand);
471       setOperationAction(ISD::SDIV, VT, Expand);
472       setOperationAction(ISD::SREM, VT, Expand);
473       setOperationAction(ISD::UDIV, VT, Expand);
474       setOperationAction(ISD::UREM, VT, Expand);
475       setOperationAction(ISD::FDIV, VT, Expand);
476       setOperationAction(ISD::FREM, VT, Expand);
477       setOperationAction(ISD::FNEG, VT, Expand);
478       setOperationAction(ISD::FSQRT, VT, Expand);
479       setOperationAction(ISD::FLOG, VT, Expand);
480       setOperationAction(ISD::FLOG10, VT, Expand);
481       setOperationAction(ISD::FLOG2, VT, Expand);
482       setOperationAction(ISD::FEXP, VT, Expand);
483       setOperationAction(ISD::FEXP2, VT, Expand);
484       setOperationAction(ISD::FSIN, VT, Expand);
485       setOperationAction(ISD::FCOS, VT, Expand);
486       setOperationAction(ISD::FABS, VT, Expand);
487       setOperationAction(ISD::FPOWI, VT, Expand);
488       setOperationAction(ISD::FFLOOR, VT, Expand);
489       setOperationAction(ISD::FCEIL,  VT, Expand);
490       setOperationAction(ISD::FTRUNC, VT, Expand);
491       setOperationAction(ISD::FRINT,  VT, Expand);
492       setOperationAction(ISD::FNEARBYINT, VT, Expand);
493       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
494       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
495       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
496       setOperationAction(ISD::MULHU, VT, Expand);
497       setOperationAction(ISD::MULHS, VT, Expand);
498       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
499       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
500       setOperationAction(ISD::UDIVREM, VT, Expand);
501       setOperationAction(ISD::SDIVREM, VT, Expand);
502       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
503       setOperationAction(ISD::FPOW, VT, Expand);
504       setOperationAction(ISD::BSWAP, VT, Expand);
505       setOperationAction(ISD::VSELECT, VT, Expand);
506       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
507       setOperationAction(ISD::ROTL, VT, Expand);
508       setOperationAction(ISD::ROTR, VT, Expand);
509 
510       for (MVT InnerVT : MVT::vector_valuetypes()) {
511         setTruncStoreAction(VT, InnerVT, Expand);
512         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
513         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
514         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
515       }
516     }
517 
518     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
519     // with merges, splats, etc.
520     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
521 
522     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
523     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
524     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
525     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
526     setOperationAction(ISD::SELECT, MVT::v4i32,
527                        Subtarget.useCRBits() ? Legal : Expand);
528     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
529     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
530     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
531     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
532     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
533     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
534     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
535     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
536     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
537 
538     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
539     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
540     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
541     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
542 
543     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
544     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
545 
546     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
547       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
548       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
549     }
550 
551     if (Subtarget.hasP8Altivec())
552       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
553     else
554       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
555 
556     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
557     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
558 
559     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
560     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
561 
562     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
563     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
564     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
565     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
566     if (Subtarget.hasP8Altivec())
567       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
568     if (Subtarget.hasVSX())
569       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
570 
571     // Altivec does not contain unordered floating-point compare instructions
572     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
573     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
574     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
575     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
576 
577     if (Subtarget.hasVSX()) {
578       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
579       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
580       if (Subtarget.hasP8Vector()) {
581         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
582         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
583       }
584       if (Subtarget.hasDirectMove() && isPPC64) {
585         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
586         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
587         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
588         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
589         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
590         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
591         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
592         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
593       }
594       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
595 
596       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
597       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
598       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
599       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
600       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
601 
602       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
603 
604       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
605       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
606 
607       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
608       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
609 
610       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
611       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
612       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
613       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
614       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
615 
616       // Share the Altivec comparison restrictions.
617       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
618       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
619       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
620       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
621 
622       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
623       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
624 
625       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
626 
627       if (Subtarget.hasP8Vector())
628         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
629 
630       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
631 
632       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
633       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
634       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
635 
636       if (Subtarget.hasP8Altivec()) {
637         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
638         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
639         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
640 
641         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
642       }
643       else {
644         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
645         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
646         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
647 
648         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
649 
650         // VSX v2i64 only supports non-arithmetic operations.
651         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
652         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
653       }
654 
655       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
656       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
657       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
658       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
659 
660       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
661 
662       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
663       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
664       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
665       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
666 
667       // Vector operation legalization checks the result type of
668       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
669       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
670       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
671       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
672       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
673 
674       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
675       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
676       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
677       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
678 
679       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
680     }
681 
682     if (Subtarget.hasP8Altivec()) {
683       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
684       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
685     }
686 
687     if (Subtarget.hasP9Vector()) {
688       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
689       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
690     }
691 
692     if (Subtarget.isISA3_0() && Subtarget.hasDirectMove())
693       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
694   }
695 
696   if (Subtarget.hasQPX()) {
697     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
698     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
699     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
700     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
701 
702     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
703     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
704 
705     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
706     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
707 
708     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
709     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
710 
711     if (!Subtarget.useCRBits())
712       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
713     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
714 
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
716     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
717     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
718     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
719     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
720     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
721     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
722 
723     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
724     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
725 
726     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
727     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
728     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
729 
730     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
731     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
732     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
733     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
734     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
735     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
736     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
737     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
738     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
739     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
740     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
741 
742     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
743     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
744 
745     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
746     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
747 
748     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
749 
750     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
751     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
752     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
753     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
754 
755     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
756     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
757 
758     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
759     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
760 
761     if (!Subtarget.useCRBits())
762       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
763     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
764 
765     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
766     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
767     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
768     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
769     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
770     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
771     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
772 
773     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
774     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
775 
776     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
777     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
778     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
779     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
780     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
781     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
782     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
783     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
784     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
785     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
786     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
787 
788     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
789     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
790 
791     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
792     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
793 
794     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
795 
796     setOperationAction(ISD::AND , MVT::v4i1, Legal);
797     setOperationAction(ISD::OR , MVT::v4i1, Legal);
798     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
799 
800     if (!Subtarget.useCRBits())
801       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
802     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
803 
804     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
805     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
806 
807     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
808     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
809     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
811     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
812     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
813     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
814 
815     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
816     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
817 
818     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
819 
820     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
821     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
822     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
823     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
824 
825     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
826     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
827     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
828     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
829 
830     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
831     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
832 
833     // These need to set FE_INEXACT, and so cannot be vectorized here.
834     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
835     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
836 
837     if (TM.Options.UnsafeFPMath) {
838       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
839       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
840 
841       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
842       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
843     } else {
844       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
845       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
846 
847       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
848       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
849     }
850   }
851 
852   if (Subtarget.has64BitSupport())
853     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
854 
855   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
856 
857   if (!isPPC64) {
858     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
859     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
860   }
861 
862   setBooleanContents(ZeroOrOneBooleanContent);
863 
864   if (Subtarget.hasAltivec()) {
865     // Altivec instructions set fields to all zeros or all ones.
866     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
867   }
868 
869   if (!isPPC64) {
870     // These libcalls are not available in 32-bit.
871     setLibcallName(RTLIB::SHL_I128, nullptr);
872     setLibcallName(RTLIB::SRL_I128, nullptr);
873     setLibcallName(RTLIB::SRA_I128, nullptr);
874   }
875 
876   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
877 
878   // We have target-specific dag combine patterns for the following nodes:
879   setTargetDAGCombine(ISD::SINT_TO_FP);
880   setTargetDAGCombine(ISD::BUILD_VECTOR);
881   if (Subtarget.hasFPCVT())
882     setTargetDAGCombine(ISD::UINT_TO_FP);
883   setTargetDAGCombine(ISD::LOAD);
884   setTargetDAGCombine(ISD::STORE);
885   setTargetDAGCombine(ISD::BR_CC);
886   if (Subtarget.useCRBits())
887     setTargetDAGCombine(ISD::BRCOND);
888   setTargetDAGCombine(ISD::BSWAP);
889   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
890   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
891   setTargetDAGCombine(ISD::INTRINSIC_VOID);
892 
893   setTargetDAGCombine(ISD::SIGN_EXTEND);
894   setTargetDAGCombine(ISD::ZERO_EXTEND);
895   setTargetDAGCombine(ISD::ANY_EXTEND);
896 
897   if (Subtarget.useCRBits()) {
898     setTargetDAGCombine(ISD::TRUNCATE);
899     setTargetDAGCombine(ISD::SETCC);
900     setTargetDAGCombine(ISD::SELECT_CC);
901   }
902 
903   // Use reciprocal estimates.
904   if (TM.Options.UnsafeFPMath) {
905     setTargetDAGCombine(ISD::FDIV);
906     setTargetDAGCombine(ISD::FSQRT);
907   }
908 
909   // Darwin long double math library functions have $LDBL128 appended.
910   if (Subtarget.isDarwin()) {
911     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
912     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
913     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
914     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
915     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
916     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
917     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
918     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
919     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
920     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
921   }
922 
923   // With 32 condition bits, we don't need to sink (and duplicate) compares
924   // aggressively in CodeGenPrep.
925   if (Subtarget.useCRBits()) {
926     setHasMultipleConditionRegisters();
927     setJumpIsExpensive();
928   }
929 
930   setMinFunctionAlignment(2);
931   if (Subtarget.isDarwin())
932     setPrefFunctionAlignment(4);
933 
934   switch (Subtarget.getDarwinDirective()) {
935   default: break;
936   case PPC::DIR_970:
937   case PPC::DIR_A2:
938   case PPC::DIR_E500mc:
939   case PPC::DIR_E5500:
940   case PPC::DIR_PWR4:
941   case PPC::DIR_PWR5:
942   case PPC::DIR_PWR5X:
943   case PPC::DIR_PWR6:
944   case PPC::DIR_PWR6X:
945   case PPC::DIR_PWR7:
946   case PPC::DIR_PWR8:
947   case PPC::DIR_PWR9:
948     setPrefFunctionAlignment(4);
949     setPrefLoopAlignment(4);
950     break;
951   }
952 
953   if (Subtarget.enableMachineScheduler())
954     setSchedulingPreference(Sched::Source);
955   else
956     setSchedulingPreference(Sched::Hybrid);
957 
958   computeRegisterProperties(STI.getRegisterInfo());
959 
960   // The Freescale cores do better with aggressive inlining of memcpy and
961   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
962   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
963       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
964     MaxStoresPerMemset = 32;
965     MaxStoresPerMemsetOptSize = 16;
966     MaxStoresPerMemcpy = 32;
967     MaxStoresPerMemcpyOptSize = 8;
968     MaxStoresPerMemmove = 32;
969     MaxStoresPerMemmoveOptSize = 8;
970   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
971     // The A2 also benefits from (very) aggressive inlining of memcpy and
972     // friends. The overhead of a the function call, even when warm, can be
973     // over one hundred cycles.
974     MaxStoresPerMemset = 128;
975     MaxStoresPerMemcpy = 128;
976     MaxStoresPerMemmove = 128;
977   }
978 }
979 
980 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
981 /// the desired ByVal argument alignment.
982 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
983                              unsigned MaxMaxAlign) {
984   if (MaxAlign == MaxMaxAlign)
985     return;
986   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
987     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
988       MaxAlign = 32;
989     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
990       MaxAlign = 16;
991   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
992     unsigned EltAlign = 0;
993     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
994     if (EltAlign > MaxAlign)
995       MaxAlign = EltAlign;
996   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
997     for (auto *EltTy : STy->elements()) {
998       unsigned EltAlign = 0;
999       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1000       if (EltAlign > MaxAlign)
1001         MaxAlign = EltAlign;
1002       if (MaxAlign == MaxMaxAlign)
1003         break;
1004     }
1005   }
1006 }
1007 
1008 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1009 /// function arguments in the caller parameter area.
1010 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1011                                                   const DataLayout &DL) const {
1012   // Darwin passes everything on 4 byte boundary.
1013   if (Subtarget.isDarwin())
1014     return 4;
1015 
1016   // 16byte and wider vectors are passed on 16byte boundary.
1017   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1018   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1019   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1020     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1021   return Align;
1022 }
1023 
1024 bool PPCTargetLowering::useSoftFloat() const {
1025   return Subtarget.useSoftFloat();
1026 }
1027 
1028 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1029   switch ((PPCISD::NodeType)Opcode) {
1030   case PPCISD::FIRST_NUMBER:    break;
1031   case PPCISD::FSEL:            return "PPCISD::FSEL";
1032   case PPCISD::FCFID:           return "PPCISD::FCFID";
1033   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1034   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1035   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1036   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1037   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1038   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1039   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1040   case PPCISD::FRE:             return "PPCISD::FRE";
1041   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1042   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1043   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1044   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1045   case PPCISD::VPERM:           return "PPCISD::VPERM";
1046   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1047   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1048   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1049   case PPCISD::CMPB:            return "PPCISD::CMPB";
1050   case PPCISD::Hi:              return "PPCISD::Hi";
1051   case PPCISD::Lo:              return "PPCISD::Lo";
1052   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1053   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1054   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1055   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1056   case PPCISD::SRL:             return "PPCISD::SRL";
1057   case PPCISD::SRA:             return "PPCISD::SRA";
1058   case PPCISD::SHL:             return "PPCISD::SHL";
1059   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1060   case PPCISD::CALL:            return "PPCISD::CALL";
1061   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1062   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1063   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1064   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1065   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1066   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1067   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1068   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1069   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1070   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1071   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1072   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1073   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1074   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1075   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1076   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1077   case PPCISD::VCMP:            return "PPCISD::VCMP";
1078   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1079   case PPCISD::LBRX:            return "PPCISD::LBRX";
1080   case PPCISD::STBRX:           return "PPCISD::STBRX";
1081   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1082   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1083   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1084   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1085   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1086   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1087   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1088   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1089   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1090   case PPCISD::BDZ:             return "PPCISD::BDZ";
1091   case PPCISD::MFFS:            return "PPCISD::MFFS";
1092   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1093   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1094   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1095   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1096   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1097   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1098   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1099   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1100   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1101   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1102   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1103   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1104   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1105   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1106   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1107   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1108   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1109   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1110   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1111   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1112   case PPCISD::SC:              return "PPCISD::SC";
1113   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1114   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1115   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1116   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1117   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1118   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1119   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1120   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1121   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1122   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1123   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1124   }
1125   return nullptr;
1126 }
1127 
1128 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1129                                           EVT VT) const {
1130   if (!VT.isVector())
1131     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1132 
1133   if (Subtarget.hasQPX())
1134     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1135 
1136   return VT.changeVectorElementTypeToInteger();
1137 }
1138 
1139 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1140   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1141   return true;
1142 }
1143 
1144 //===----------------------------------------------------------------------===//
1145 // Node matching predicates, for use by the tblgen matching code.
1146 //===----------------------------------------------------------------------===//
1147 
1148 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1149 static bool isFloatingPointZero(SDValue Op) {
1150   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1151     return CFP->getValueAPF().isZero();
1152   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1153     // Maybe this has already been legalized into the constant pool?
1154     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1155       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1156         return CFP->getValueAPF().isZero();
1157   }
1158   return false;
1159 }
1160 
1161 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1162 /// true if Op is undef or if it matches the specified value.
1163 static bool isConstantOrUndef(int Op, int Val) {
1164   return Op < 0 || Op == Val;
1165 }
1166 
1167 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1168 /// VPKUHUM instruction.
1169 /// The ShuffleKind distinguishes between big-endian operations with
1170 /// two different inputs (0), either-endian operations with two identical
1171 /// inputs (1), and little-endian operations with two different inputs (2).
1172 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1173 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1174                                SelectionDAG &DAG) {
1175   bool IsLE = DAG.getDataLayout().isLittleEndian();
1176   if (ShuffleKind == 0) {
1177     if (IsLE)
1178       return false;
1179     for (unsigned i = 0; i != 16; ++i)
1180       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1181         return false;
1182   } else if (ShuffleKind == 2) {
1183     if (!IsLE)
1184       return false;
1185     for (unsigned i = 0; i != 16; ++i)
1186       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1187         return false;
1188   } else if (ShuffleKind == 1) {
1189     unsigned j = IsLE ? 0 : 1;
1190     for (unsigned i = 0; i != 8; ++i)
1191       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1192           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1193         return false;
1194   }
1195   return true;
1196 }
1197 
1198 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1199 /// VPKUWUM instruction.
1200 /// The ShuffleKind distinguishes between big-endian operations with
1201 /// two different inputs (0), either-endian operations with two identical
1202 /// inputs (1), and little-endian operations with two different inputs (2).
1203 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1204 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1205                                SelectionDAG &DAG) {
1206   bool IsLE = DAG.getDataLayout().isLittleEndian();
1207   if (ShuffleKind == 0) {
1208     if (IsLE)
1209       return false;
1210     for (unsigned i = 0; i != 16; i += 2)
1211       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1212           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1213         return false;
1214   } else if (ShuffleKind == 2) {
1215     if (!IsLE)
1216       return false;
1217     for (unsigned i = 0; i != 16; i += 2)
1218       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1219           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1220         return false;
1221   } else if (ShuffleKind == 1) {
1222     unsigned j = IsLE ? 0 : 2;
1223     for (unsigned i = 0; i != 8; i += 2)
1224       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1225           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1226           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1227           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1228         return false;
1229   }
1230   return true;
1231 }
1232 
1233 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1234 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1235 /// current subtarget.
1236 ///
1237 /// The ShuffleKind distinguishes between big-endian operations with
1238 /// two different inputs (0), either-endian operations with two identical
1239 /// inputs (1), and little-endian operations with two different inputs (2).
1240 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1241 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1242                                SelectionDAG &DAG) {
1243   const PPCSubtarget& Subtarget =
1244     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1245   if (!Subtarget.hasP8Vector())
1246     return false;
1247 
1248   bool IsLE = DAG.getDataLayout().isLittleEndian();
1249   if (ShuffleKind == 0) {
1250     if (IsLE)
1251       return false;
1252     for (unsigned i = 0; i != 16; i += 4)
1253       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1254           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1255           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1256           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1257         return false;
1258   } else if (ShuffleKind == 2) {
1259     if (!IsLE)
1260       return false;
1261     for (unsigned i = 0; i != 16; i += 4)
1262       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1263           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1264           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1265           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1266         return false;
1267   } else if (ShuffleKind == 1) {
1268     unsigned j = IsLE ? 0 : 4;
1269     for (unsigned i = 0; i != 8; i += 4)
1270       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1271           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1272           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1273           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1274           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1275           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1276           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1277           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1278         return false;
1279   }
1280   return true;
1281 }
1282 
1283 /// isVMerge - Common function, used to match vmrg* shuffles.
1284 ///
1285 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1286                      unsigned LHSStart, unsigned RHSStart) {
1287   if (N->getValueType(0) != MVT::v16i8)
1288     return false;
1289   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1290          "Unsupported merge size!");
1291 
1292   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1293     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1294       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1295                              LHSStart+j+i*UnitSize) ||
1296           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1297                              RHSStart+j+i*UnitSize))
1298         return false;
1299     }
1300   return true;
1301 }
1302 
1303 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1304 /// a VMRGL* 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::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1310                              unsigned ShuffleKind, SelectionDAG &DAG) {
1311   if (DAG.getDataLayout().isLittleEndian()) {
1312     if (ShuffleKind == 1) // unary
1313       return isVMerge(N, UnitSize, 0, 0);
1314     else if (ShuffleKind == 2) // swapped
1315       return isVMerge(N, UnitSize, 0, 16);
1316     else
1317       return false;
1318   } else {
1319     if (ShuffleKind == 1) // unary
1320       return isVMerge(N, UnitSize, 8, 8);
1321     else if (ShuffleKind == 0) // normal
1322       return isVMerge(N, UnitSize, 8, 24);
1323     else
1324       return false;
1325   }
1326 }
1327 
1328 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1329 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1330 /// The ShuffleKind distinguishes between big-endian merges with two
1331 /// different inputs (0), either-endian merges with two identical inputs (1),
1332 /// and little-endian merges with two different inputs (2).  For the latter,
1333 /// the input operands are swapped (see PPCInstrAltivec.td).
1334 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1335                              unsigned ShuffleKind, SelectionDAG &DAG) {
1336   if (DAG.getDataLayout().isLittleEndian()) {
1337     if (ShuffleKind == 1) // unary
1338       return isVMerge(N, UnitSize, 8, 8);
1339     else if (ShuffleKind == 2) // swapped
1340       return isVMerge(N, UnitSize, 8, 24);
1341     else
1342       return false;
1343   } else {
1344     if (ShuffleKind == 1) // unary
1345       return isVMerge(N, UnitSize, 0, 0);
1346     else if (ShuffleKind == 0) // normal
1347       return isVMerge(N, UnitSize, 0, 16);
1348     else
1349       return false;
1350   }
1351 }
1352 
1353 /**
1354  * \brief Common function used to match vmrgew and vmrgow shuffles
1355  *
1356  * The indexOffset determines whether to look for even or odd words in
1357  * the shuffle mask. This is based on the of the endianness of the target
1358  * machine.
1359  *   - Little Endian:
1360  *     - Use offset of 0 to check for odd elements
1361  *     - Use offset of 4 to check for even elements
1362  *   - Big Endian:
1363  *     - Use offset of 0 to check for even elements
1364  *     - Use offset of 4 to check for odd elements
1365  * A detailed description of the vector element ordering for little endian and
1366  * big endian can be found at
1367  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1368  * Targeting your applications - what little endian and big endian IBM XL C/C++
1369  * compiler differences mean to you
1370  *
1371  * The mask to the shuffle vector instruction specifies the indices of the
1372  * elements from the two input vectors to place in the result. The elements are
1373  * numbered in array-access order, starting with the first vector. These vectors
1374  * are always of type v16i8, thus each vector will contain 16 elements of size
1375  * 8. More info on the shuffle vector can be found in the
1376  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1377  * Language Reference.
1378  *
1379  * The RHSStartValue indicates whether the same input vectors are used (unary)
1380  * or two different input vectors are used, based on the following:
1381  *   - If the instruction uses the same vector for both inputs, the range of the
1382  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1383  *     be 0.
1384  *   - If the instruction has two different vectors then the range of the
1385  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1386  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1387  *     to 31 specify elements in the second vector).
1388  *
1389  * \param[in] N The shuffle vector SD Node to analyze
1390  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1391  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1392  * vector to the shuffle_vector instruction
1393  * \return true iff this shuffle vector represents an even or odd word merge
1394  */
1395 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1396                      unsigned RHSStartValue) {
1397   if (N->getValueType(0) != MVT::v16i8)
1398     return false;
1399 
1400   for (unsigned i = 0; i < 2; ++i)
1401     for (unsigned j = 0; j < 4; ++j)
1402       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1403                              i*RHSStartValue+j+IndexOffset) ||
1404           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1405                              i*RHSStartValue+j+IndexOffset+8))
1406         return false;
1407   return true;
1408 }
1409 
1410 /**
1411  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1412  * vmrgow instructions.
1413  *
1414  * \param[in] N The shuffle vector SD Node to analyze
1415  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1416  * \param[in] ShuffleKind Identify the type of merge:
1417  *   - 0 = big-endian merge with two different inputs;
1418  *   - 1 = either-endian merge with two identical inputs;
1419  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1420  *     little-endian merges).
1421  * \param[in] DAG The current SelectionDAG
1422  * \return true iff this shuffle mask
1423  */
1424 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1425                               unsigned ShuffleKind, SelectionDAG &DAG) {
1426   if (DAG.getDataLayout().isLittleEndian()) {
1427     unsigned indexOffset = CheckEven ? 4 : 0;
1428     if (ShuffleKind == 1) // Unary
1429       return isVMerge(N, indexOffset, 0);
1430     else if (ShuffleKind == 2) // swapped
1431       return isVMerge(N, indexOffset, 16);
1432     else
1433       return false;
1434   }
1435   else {
1436     unsigned indexOffset = CheckEven ? 0 : 4;
1437     if (ShuffleKind == 1) // Unary
1438       return isVMerge(N, indexOffset, 0);
1439     else if (ShuffleKind == 0) // Normal
1440       return isVMerge(N, indexOffset, 16);
1441     else
1442       return false;
1443   }
1444   return false;
1445 }
1446 
1447 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1448 /// amount, otherwise return -1.
1449 /// The ShuffleKind distinguishes between big-endian operations with two
1450 /// different inputs (0), either-endian operations with two identical inputs
1451 /// (1), and little-endian operations with two different inputs (2).  For the
1452 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1453 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1454                              SelectionDAG &DAG) {
1455   if (N->getValueType(0) != MVT::v16i8)
1456     return -1;
1457 
1458   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1459 
1460   // Find the first non-undef value in the shuffle mask.
1461   unsigned i;
1462   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1463     /*search*/;
1464 
1465   if (i == 16) return -1;  // all undef.
1466 
1467   // Otherwise, check to see if the rest of the elements are consecutively
1468   // numbered from this value.
1469   unsigned ShiftAmt = SVOp->getMaskElt(i);
1470   if (ShiftAmt < i) return -1;
1471 
1472   ShiftAmt -= i;
1473   bool isLE = DAG.getDataLayout().isLittleEndian();
1474 
1475   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1476     // Check the rest of the elements to see if they are consecutive.
1477     for (++i; i != 16; ++i)
1478       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1479         return -1;
1480   } else if (ShuffleKind == 1) {
1481     // Check the rest of the elements to see if they are consecutive.
1482     for (++i; i != 16; ++i)
1483       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1484         return -1;
1485   } else
1486     return -1;
1487 
1488   if (isLE)
1489     ShiftAmt = 16 - ShiftAmt;
1490 
1491   return ShiftAmt;
1492 }
1493 
1494 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1495 /// specifies a splat of a single element that is suitable for input to
1496 /// VSPLTB/VSPLTH/VSPLTW.
1497 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1498   assert(N->getValueType(0) == MVT::v16i8 &&
1499          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1500 
1501   // The consecutive indices need to specify an element, not part of two
1502   // different elements.  So abandon ship early if this isn't the case.
1503   if (N->getMaskElt(0) % EltSize != 0)
1504     return false;
1505 
1506   // This is a splat operation if each element of the permute is the same, and
1507   // if the value doesn't reference the second vector.
1508   unsigned ElementBase = N->getMaskElt(0);
1509 
1510   // FIXME: Handle UNDEF elements too!
1511   if (ElementBase >= 16)
1512     return false;
1513 
1514   // Check that the indices are consecutive, in the case of a multi-byte element
1515   // splatted with a v16i8 mask.
1516   for (unsigned i = 1; i != EltSize; ++i)
1517     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1518       return false;
1519 
1520   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1521     if (N->getMaskElt(i) < 0) continue;
1522     for (unsigned j = 0; j != EltSize; ++j)
1523       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1524         return false;
1525   }
1526   return true;
1527 }
1528 
1529 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1530                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1531 
1532   // Check that the mask is shuffling words
1533   for (unsigned i = 0; i < 4; ++i) {
1534     unsigned B0 = N->getMaskElt(i*4);
1535     unsigned B1 = N->getMaskElt(i*4+1);
1536     unsigned B2 = N->getMaskElt(i*4+2);
1537     unsigned B3 = N->getMaskElt(i*4+3);
1538     if (B0 % 4)
1539       return false;
1540     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1541       return false;
1542   }
1543 
1544   // Now we look at mask elements 0,4,8,12
1545   unsigned M0 = N->getMaskElt(0) / 4;
1546   unsigned M1 = N->getMaskElt(4) / 4;
1547   unsigned M2 = N->getMaskElt(8) / 4;
1548   unsigned M3 = N->getMaskElt(12) / 4;
1549   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1550   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1551 
1552   // Below, let H and L be arbitrary elements of the shuffle mask
1553   // where H is in the range [4,7] and L is in the range [0,3].
1554   // H, 1, 2, 3 or L, 5, 6, 7
1555   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1556       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1557     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1558     InsertAtByte = IsLE ? 12 : 0;
1559     Swap = M0 < 4;
1560     return true;
1561   }
1562   // 0, H, 2, 3 or 4, L, 6, 7
1563   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1564       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1565     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1566     InsertAtByte = IsLE ? 8 : 4;
1567     Swap = M1 < 4;
1568     return true;
1569   }
1570   // 0, 1, H, 3 or 4, 5, L, 7
1571   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1572       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1573     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1574     InsertAtByte = IsLE ? 4 : 8;
1575     Swap = M2 < 4;
1576     return true;
1577   }
1578   // 0, 1, 2, H or 4, 5, 6, L
1579   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1580       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1581     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1582     InsertAtByte = IsLE ? 0 : 12;
1583     Swap = M3 < 4;
1584     return true;
1585   }
1586 
1587   // If both vector operands for the shuffle are the same vector, the mask will
1588   // contain only elements from the first one and the second one will be undef.
1589   if (N->getOperand(1).isUndef()) {
1590     ShiftElts = 0;
1591     Swap = true;
1592     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1593     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1594       InsertAtByte = IsLE ? 12 : 0;
1595       return true;
1596     }
1597     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1598       InsertAtByte = IsLE ? 8 : 4;
1599       return true;
1600     }
1601     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1602       InsertAtByte = IsLE ? 4 : 8;
1603       return true;
1604     }
1605     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1606       InsertAtByte = IsLE ? 0 : 12;
1607       return true;
1608     }
1609   }
1610 
1611   return false;
1612 }
1613 
1614 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1615 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1616 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1617                                 SelectionDAG &DAG) {
1618   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1619   assert(isSplatShuffleMask(SVOp, EltSize));
1620   if (DAG.getDataLayout().isLittleEndian())
1621     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1622   else
1623     return SVOp->getMaskElt(0) / EltSize;
1624 }
1625 
1626 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1627 /// by using a vspltis[bhw] instruction of the specified element size, return
1628 /// the constant being splatted.  The ByteSize field indicates the number of
1629 /// bytes of each element [124] -> [bhw].
1630 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1631   SDValue OpVal(nullptr, 0);
1632 
1633   // If ByteSize of the splat is bigger than the element size of the
1634   // build_vector, then we have a case where we are checking for a splat where
1635   // multiple elements of the buildvector are folded together into a single
1636   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1637   unsigned EltSize = 16/N->getNumOperands();
1638   if (EltSize < ByteSize) {
1639     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1640     SDValue UniquedVals[4];
1641     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1642 
1643     // See if all of the elements in the buildvector agree across.
1644     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1645       if (N->getOperand(i).isUndef()) continue;
1646       // If the element isn't a constant, bail fully out.
1647       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1648 
1649 
1650       if (!UniquedVals[i&(Multiple-1)].getNode())
1651         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1652       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1653         return SDValue();  // no match.
1654     }
1655 
1656     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1657     // either constant or undef values that are identical for each chunk.  See
1658     // if these chunks can form into a larger vspltis*.
1659 
1660     // Check to see if all of the leading entries are either 0 or -1.  If
1661     // neither, then this won't fit into the immediate field.
1662     bool LeadingZero = true;
1663     bool LeadingOnes = true;
1664     for (unsigned i = 0; i != Multiple-1; ++i) {
1665       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1666 
1667       LeadingZero &= isNullConstant(UniquedVals[i]);
1668       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1669     }
1670     // Finally, check the least significant entry.
1671     if (LeadingZero) {
1672       if (!UniquedVals[Multiple-1].getNode())
1673         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1674       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1675       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1676         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1677     }
1678     if (LeadingOnes) {
1679       if (!UniquedVals[Multiple-1].getNode())
1680         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1681       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1682       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1683         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1684     }
1685 
1686     return SDValue();
1687   }
1688 
1689   // Check to see if this buildvec has a single non-undef value in its elements.
1690   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1691     if (N->getOperand(i).isUndef()) continue;
1692     if (!OpVal.getNode())
1693       OpVal = N->getOperand(i);
1694     else if (OpVal != N->getOperand(i))
1695       return SDValue();
1696   }
1697 
1698   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1699 
1700   unsigned ValSizeInBytes = EltSize;
1701   uint64_t Value = 0;
1702   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1703     Value = CN->getZExtValue();
1704   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1705     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1706     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1707   }
1708 
1709   // If the splat value is larger than the element value, then we can never do
1710   // this splat.  The only case that we could fit the replicated bits into our
1711   // immediate field for would be zero, and we prefer to use vxor for it.
1712   if (ValSizeInBytes < ByteSize) return SDValue();
1713 
1714   // If the element value is larger than the splat value, check if it consists
1715   // of a repeated bit pattern of size ByteSize.
1716   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1717     return SDValue();
1718 
1719   // Properly sign extend the value.
1720   int MaskVal = SignExtend32(Value, ByteSize * 8);
1721 
1722   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1723   if (MaskVal == 0) return SDValue();
1724 
1725   // Finally, if this value fits in a 5 bit sext field, return it
1726   if (SignExtend32<5>(MaskVal) == MaskVal)
1727     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1728   return SDValue();
1729 }
1730 
1731 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1732 /// amount, otherwise return -1.
1733 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1734   EVT VT = N->getValueType(0);
1735   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1736     return -1;
1737 
1738   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1739 
1740   // Find the first non-undef value in the shuffle mask.
1741   unsigned i;
1742   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1743     /*search*/;
1744 
1745   if (i == 4) return -1;  // all undef.
1746 
1747   // Otherwise, check to see if the rest of the elements are consecutively
1748   // numbered from this value.
1749   unsigned ShiftAmt = SVOp->getMaskElt(i);
1750   if (ShiftAmt < i) return -1;
1751   ShiftAmt -= i;
1752 
1753   // Check the rest of the elements to see if they are consecutive.
1754   for (++i; i != 4; ++i)
1755     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1756       return -1;
1757 
1758   return ShiftAmt;
1759 }
1760 
1761 //===----------------------------------------------------------------------===//
1762 //  Addressing Mode Selection
1763 //===----------------------------------------------------------------------===//
1764 
1765 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1766 /// or 64-bit immediate, and if the value can be accurately represented as a
1767 /// sign extension from a 16-bit value.  If so, this returns true and the
1768 /// immediate.
1769 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1770   if (!isa<ConstantSDNode>(N))
1771     return false;
1772 
1773   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1774   if (N->getValueType(0) == MVT::i32)
1775     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1776   else
1777     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1778 }
1779 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1780   return isIntS16Immediate(Op.getNode(), Imm);
1781 }
1782 
1783 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1784 /// can be represented as an indexed [r+r] operation.  Returns false if it
1785 /// can be more efficiently represented with [r+imm].
1786 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1787                                             SDValue &Index,
1788                                             SelectionDAG &DAG) const {
1789   short imm = 0;
1790   if (N.getOpcode() == ISD::ADD) {
1791     if (isIntS16Immediate(N.getOperand(1), imm))
1792       return false;    // r+i
1793     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1794       return false;    // r+i
1795 
1796     Base = N.getOperand(0);
1797     Index = N.getOperand(1);
1798     return true;
1799   } else if (N.getOpcode() == ISD::OR) {
1800     if (isIntS16Immediate(N.getOperand(1), imm))
1801       return false;    // r+i can fold it if we can.
1802 
1803     // If this is an or of disjoint bitfields, we can codegen this as an add
1804     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1805     // disjoint.
1806     APInt LHSKnownZero, LHSKnownOne;
1807     APInt RHSKnownZero, RHSKnownOne;
1808     DAG.computeKnownBits(N.getOperand(0),
1809                          LHSKnownZero, LHSKnownOne);
1810 
1811     if (LHSKnownZero.getBoolValue()) {
1812       DAG.computeKnownBits(N.getOperand(1),
1813                            RHSKnownZero, RHSKnownOne);
1814       // If all of the bits are known zero on the LHS or RHS, the add won't
1815       // carry.
1816       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1817         Base = N.getOperand(0);
1818         Index = N.getOperand(1);
1819         return true;
1820       }
1821     }
1822   }
1823 
1824   return false;
1825 }
1826 
1827 // If we happen to be doing an i64 load or store into a stack slot that has
1828 // less than a 4-byte alignment, then the frame-index elimination may need to
1829 // use an indexed load or store instruction (because the offset may not be a
1830 // multiple of 4). The extra register needed to hold the offset comes from the
1831 // register scavenger, and it is possible that the scavenger will need to use
1832 // an emergency spill slot. As a result, we need to make sure that a spill slot
1833 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1834 // stack slot.
1835 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1836   // FIXME: This does not handle the LWA case.
1837   if (VT != MVT::i64)
1838     return;
1839 
1840   // NOTE: We'll exclude negative FIs here, which come from argument
1841   // lowering, because there are no known test cases triggering this problem
1842   // using packed structures (or similar). We can remove this exclusion if
1843   // we find such a test case. The reason why this is so test-case driven is
1844   // because this entire 'fixup' is only to prevent crashes (from the
1845   // register scavenger) on not-really-valid inputs. For example, if we have:
1846   //   %a = alloca i1
1847   //   %b = bitcast i1* %a to i64*
1848   //   store i64* a, i64 b
1849   // then the store should really be marked as 'align 1', but is not. If it
1850   // were marked as 'align 1' then the indexed form would have been
1851   // instruction-selected initially, and the problem this 'fixup' is preventing
1852   // won't happen regardless.
1853   if (FrameIdx < 0)
1854     return;
1855 
1856   MachineFunction &MF = DAG.getMachineFunction();
1857   MachineFrameInfo &MFI = MF.getFrameInfo();
1858 
1859   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1860   if (Align >= 4)
1861     return;
1862 
1863   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1864   FuncInfo->setHasNonRISpills();
1865 }
1866 
1867 /// Returns true if the address N can be represented by a base register plus
1868 /// a signed 16-bit displacement [r+imm], and if it is not better
1869 /// represented as reg+reg.  If Aligned is true, only accept displacements
1870 /// suitable for STD and friends, i.e. multiples of 4.
1871 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1872                                             SDValue &Base,
1873                                             SelectionDAG &DAG,
1874                                             bool Aligned) const {
1875   // FIXME dl should come from parent load or store, not from address
1876   SDLoc dl(N);
1877   // If this can be more profitably realized as r+r, fail.
1878   if (SelectAddressRegReg(N, Disp, Base, DAG))
1879     return false;
1880 
1881   if (N.getOpcode() == ISD::ADD) {
1882     short imm = 0;
1883     if (isIntS16Immediate(N.getOperand(1), imm) &&
1884         (!Aligned || (imm & 3) == 0)) {
1885       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1886       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1887         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1888         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1889       } else {
1890         Base = N.getOperand(0);
1891       }
1892       return true; // [r+i]
1893     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1894       // Match LOAD (ADD (X, Lo(G))).
1895       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1896              && "Cannot handle constant offsets yet!");
1897       Disp = N.getOperand(1).getOperand(0);  // The global address.
1898       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1899              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1900              Disp.getOpcode() == ISD::TargetConstantPool ||
1901              Disp.getOpcode() == ISD::TargetJumpTable);
1902       Base = N.getOperand(0);
1903       return true;  // [&g+r]
1904     }
1905   } else if (N.getOpcode() == ISD::OR) {
1906     short imm = 0;
1907     if (isIntS16Immediate(N.getOperand(1), imm) &&
1908         (!Aligned || (imm & 3) == 0)) {
1909       // If this is an or of disjoint bitfields, we can codegen this as an add
1910       // (for better address arithmetic) if the LHS and RHS of the OR are
1911       // provably disjoint.
1912       APInt LHSKnownZero, LHSKnownOne;
1913       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1914 
1915       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1916         // If all of the bits are known zero on the LHS or RHS, the add won't
1917         // carry.
1918         if (FrameIndexSDNode *FI =
1919               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1920           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1921           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1922         } else {
1923           Base = N.getOperand(0);
1924         }
1925         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1926         return true;
1927       }
1928     }
1929   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1930     // Loading from a constant address.
1931 
1932     // If this address fits entirely in a 16-bit sext immediate field, codegen
1933     // this as "d, 0"
1934     short Imm;
1935     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1936       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1937       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1938                              CN->getValueType(0));
1939       return true;
1940     }
1941 
1942     // Handle 32-bit sext immediates with LIS + addr mode.
1943     if ((CN->getValueType(0) == MVT::i32 ||
1944          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1945         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1946       int Addr = (int)CN->getZExtValue();
1947 
1948       // Otherwise, break this down into an LIS + disp.
1949       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1950 
1951       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1952                                    MVT::i32);
1953       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1954       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1955       return true;
1956     }
1957   }
1958 
1959   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1960   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1961     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1962     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1963   } else
1964     Base = N;
1965   return true;      // [r+0]
1966 }
1967 
1968 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1969 /// represented as an indexed [r+r] operation.
1970 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1971                                                 SDValue &Index,
1972                                                 SelectionDAG &DAG) const {
1973   // Check to see if we can easily represent this as an [r+r] address.  This
1974   // will fail if it thinks that the address is more profitably represented as
1975   // reg+imm, e.g. where imm = 0.
1976   if (SelectAddressRegReg(N, Base, Index, DAG))
1977     return true;
1978 
1979   // If the operand is an addition, always emit this as [r+r], since this is
1980   // better (for code size, and execution, as the memop does the add for free)
1981   // than emitting an explicit add.
1982   if (N.getOpcode() == ISD::ADD) {
1983     Base = N.getOperand(0);
1984     Index = N.getOperand(1);
1985     return true;
1986   }
1987 
1988   // Otherwise, do it the hard way, using R0 as the base register.
1989   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1990                          N.getValueType());
1991   Index = N;
1992   return true;
1993 }
1994 
1995 /// getPreIndexedAddressParts - returns true by value, base pointer and
1996 /// offset pointer and addressing mode by reference if the node's address
1997 /// can be legally represented as pre-indexed load / store address.
1998 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1999                                                   SDValue &Offset,
2000                                                   ISD::MemIndexedMode &AM,
2001                                                   SelectionDAG &DAG) const {
2002   if (DisablePPCPreinc) return false;
2003 
2004   bool isLoad = true;
2005   SDValue Ptr;
2006   EVT VT;
2007   unsigned Alignment;
2008   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2009     Ptr = LD->getBasePtr();
2010     VT = LD->getMemoryVT();
2011     Alignment = LD->getAlignment();
2012   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2013     Ptr = ST->getBasePtr();
2014     VT  = ST->getMemoryVT();
2015     Alignment = ST->getAlignment();
2016     isLoad = false;
2017   } else
2018     return false;
2019 
2020   // PowerPC doesn't have preinc load/store instructions for vectors (except
2021   // for QPX, which does have preinc r+r forms).
2022   if (VT.isVector()) {
2023     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2024       return false;
2025     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2026       AM = ISD::PRE_INC;
2027       return true;
2028     }
2029   }
2030 
2031   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2032 
2033     // Common code will reject creating a pre-inc form if the base pointer
2034     // is a frame index, or if N is a store and the base pointer is either
2035     // the same as or a predecessor of the value being stored.  Check for
2036     // those situations here, and try with swapped Base/Offset instead.
2037     bool Swap = false;
2038 
2039     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2040       Swap = true;
2041     else if (!isLoad) {
2042       SDValue Val = cast<StoreSDNode>(N)->getValue();
2043       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2044         Swap = true;
2045     }
2046 
2047     if (Swap)
2048       std::swap(Base, Offset);
2049 
2050     AM = ISD::PRE_INC;
2051     return true;
2052   }
2053 
2054   // LDU/STU can only handle immediates that are a multiple of 4.
2055   if (VT != MVT::i64) {
2056     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2057       return false;
2058   } else {
2059     // LDU/STU need an address with at least 4-byte alignment.
2060     if (Alignment < 4)
2061       return false;
2062 
2063     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2064       return false;
2065   }
2066 
2067   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2068     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2069     // sext i32 to i64 when addr mode is r+i.
2070     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2071         LD->getExtensionType() == ISD::SEXTLOAD &&
2072         isa<ConstantSDNode>(Offset))
2073       return false;
2074   }
2075 
2076   AM = ISD::PRE_INC;
2077   return true;
2078 }
2079 
2080 //===----------------------------------------------------------------------===//
2081 //  LowerOperation implementation
2082 //===----------------------------------------------------------------------===//
2083 
2084 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2085 /// and LoOpFlags to the target MO flags.
2086 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2087                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2088                                const GlobalValue *GV = nullptr) {
2089   HiOpFlags = PPCII::MO_HA;
2090   LoOpFlags = PPCII::MO_LO;
2091 
2092   // Don't use the pic base if not in PIC relocation model.
2093   if (IsPIC) {
2094     HiOpFlags |= PPCII::MO_PIC_FLAG;
2095     LoOpFlags |= PPCII::MO_PIC_FLAG;
2096   }
2097 
2098   // If this is a reference to a global value that requires a non-lazy-ptr, make
2099   // sure that instruction lowering adds it.
2100   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2101     HiOpFlags |= PPCII::MO_NLP_FLAG;
2102     LoOpFlags |= PPCII::MO_NLP_FLAG;
2103 
2104     if (GV->hasHiddenVisibility()) {
2105       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2106       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2107     }
2108   }
2109 }
2110 
2111 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2112                              SelectionDAG &DAG) {
2113   SDLoc DL(HiPart);
2114   EVT PtrVT = HiPart.getValueType();
2115   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2116 
2117   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2118   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2119 
2120   // With PIC, the first instruction is actually "GR+hi(&G)".
2121   if (isPIC)
2122     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2123                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2124 
2125   // Generate non-pic code that has direct accesses to the constant pool.
2126   // The address of the global is just (hi(&g)+lo(&g)).
2127   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2128 }
2129 
2130 static void setUsesTOCBasePtr(MachineFunction &MF) {
2131   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2132   FuncInfo->setUsesTOCBasePtr();
2133 }
2134 
2135 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2136   setUsesTOCBasePtr(DAG.getMachineFunction());
2137 }
2138 
2139 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2140                            SDValue GA) {
2141   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2142   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2143                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2144 
2145   SDValue Ops[] = { GA, Reg };
2146   return DAG.getMemIntrinsicNode(
2147       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2148       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2149       false, 0);
2150 }
2151 
2152 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2153                                              SelectionDAG &DAG) const {
2154   EVT PtrVT = Op.getValueType();
2155   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2156   const Constant *C = CP->getConstVal();
2157 
2158   // 64-bit SVR4 ABI code is always position-independent.
2159   // The actual address of the GlobalValue is stored in the TOC.
2160   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2161     setUsesTOCBasePtr(DAG);
2162     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2163     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2164   }
2165 
2166   unsigned MOHiFlag, MOLoFlag;
2167   bool IsPIC = isPositionIndependent();
2168   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2169 
2170   if (IsPIC && Subtarget.isSVR4ABI()) {
2171     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2172                                            PPCII::MO_PIC_FLAG);
2173     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2174   }
2175 
2176   SDValue CPIHi =
2177     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2178   SDValue CPILo =
2179     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2180   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2181 }
2182 
2183 // For 64-bit PowerPC, prefer the more compact relative encodings.
2184 // This trades 32 bits per jump table entry for one or two instructions
2185 // on the jump site.
2186 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2187   if (isJumpTableRelative())
2188     return MachineJumpTableInfo::EK_LabelDifference32;
2189 
2190   return TargetLowering::getJumpTableEncoding();
2191 }
2192 
2193 bool PPCTargetLowering::isJumpTableRelative() const {
2194   if (Subtarget.isPPC64())
2195     return true;
2196   return TargetLowering::isJumpTableRelative();
2197 }
2198 
2199 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2200                                                     SelectionDAG &DAG) const {
2201   if (!Subtarget.isPPC64())
2202     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2203 
2204   switch (getTargetMachine().getCodeModel()) {
2205   case CodeModel::Default:
2206   case CodeModel::Small:
2207   case CodeModel::Medium:
2208     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2209   default:
2210     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2211                        getPointerTy(DAG.getDataLayout()));
2212   }
2213 }
2214 
2215 const MCExpr *
2216 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2217                                                 unsigned JTI,
2218                                                 MCContext &Ctx) const {
2219   if (!Subtarget.isPPC64())
2220     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2221 
2222   switch (getTargetMachine().getCodeModel()) {
2223   case CodeModel::Default:
2224   case CodeModel::Small:
2225   case CodeModel::Medium:
2226     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2227   default:
2228     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2229   }
2230 }
2231 
2232 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2233   EVT PtrVT = Op.getValueType();
2234   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2235 
2236   // 64-bit SVR4 ABI code is always position-independent.
2237   // The actual address of the GlobalValue is stored in the TOC.
2238   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2239     setUsesTOCBasePtr(DAG);
2240     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2241     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2242   }
2243 
2244   unsigned MOHiFlag, MOLoFlag;
2245   bool IsPIC = isPositionIndependent();
2246   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2247 
2248   if (IsPIC && Subtarget.isSVR4ABI()) {
2249     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2250                                         PPCII::MO_PIC_FLAG);
2251     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2252   }
2253 
2254   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2255   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2256   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2257 }
2258 
2259 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2260                                              SelectionDAG &DAG) const {
2261   EVT PtrVT = Op.getValueType();
2262   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2263   const BlockAddress *BA = BASDN->getBlockAddress();
2264 
2265   // 64-bit SVR4 ABI code is always position-independent.
2266   // The actual BlockAddress is stored in the TOC.
2267   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2268     setUsesTOCBasePtr(DAG);
2269     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2270     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2271   }
2272 
2273   unsigned MOHiFlag, MOLoFlag;
2274   bool IsPIC = isPositionIndependent();
2275   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2276   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2277   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2278   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2279 }
2280 
2281 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2282                                               SelectionDAG &DAG) const {
2283 
2284   // FIXME: TLS addresses currently use medium model code sequences,
2285   // which is the most useful form.  Eventually support for small and
2286   // large models could be added if users need it, at the cost of
2287   // additional complexity.
2288   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2289   if (DAG.getTarget().Options.EmulatedTLS)
2290     return LowerToTLSEmulatedModel(GA, DAG);
2291 
2292   SDLoc dl(GA);
2293   const GlobalValue *GV = GA->getGlobal();
2294   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2295   bool is64bit = Subtarget.isPPC64();
2296   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2297   PICLevel::Level picLevel = M->getPICLevel();
2298 
2299   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2300 
2301   if (Model == TLSModel::LocalExec) {
2302     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2303                                                PPCII::MO_TPREL_HA);
2304     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2305                                                PPCII::MO_TPREL_LO);
2306     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2307                                      is64bit ? MVT::i64 : MVT::i32);
2308     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2309     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2310   }
2311 
2312   if (Model == TLSModel::InitialExec) {
2313     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2314     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2315                                                 PPCII::MO_TLS);
2316     SDValue GOTPtr;
2317     if (is64bit) {
2318       setUsesTOCBasePtr(DAG);
2319       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2320       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2321                            PtrVT, GOTReg, TGA);
2322     } else
2323       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2324     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2325                                    PtrVT, TGA, GOTPtr);
2326     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2327   }
2328 
2329   if (Model == TLSModel::GeneralDynamic) {
2330     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2331     SDValue GOTPtr;
2332     if (is64bit) {
2333       setUsesTOCBasePtr(DAG);
2334       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2335       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2336                                    GOTReg, TGA);
2337     } else {
2338       if (picLevel == PICLevel::SmallPIC)
2339         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2340       else
2341         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2342     }
2343     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2344                        GOTPtr, TGA, TGA);
2345   }
2346 
2347   if (Model == TLSModel::LocalDynamic) {
2348     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2349     SDValue GOTPtr;
2350     if (is64bit) {
2351       setUsesTOCBasePtr(DAG);
2352       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2353       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2354                            GOTReg, TGA);
2355     } else {
2356       if (picLevel == PICLevel::SmallPIC)
2357         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2358       else
2359         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2360     }
2361     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2362                                   PtrVT, GOTPtr, TGA, TGA);
2363     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2364                                       PtrVT, TLSAddr, TGA);
2365     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2366   }
2367 
2368   llvm_unreachable("Unknown TLS model!");
2369 }
2370 
2371 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2372                                               SelectionDAG &DAG) const {
2373   EVT PtrVT = Op.getValueType();
2374   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2375   SDLoc DL(GSDN);
2376   const GlobalValue *GV = GSDN->getGlobal();
2377 
2378   // 64-bit SVR4 ABI code is always position-independent.
2379   // The actual address of the GlobalValue is stored in the TOC.
2380   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2381     setUsesTOCBasePtr(DAG);
2382     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2383     return getTOCEntry(DAG, DL, true, GA);
2384   }
2385 
2386   unsigned MOHiFlag, MOLoFlag;
2387   bool IsPIC = isPositionIndependent();
2388   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2389 
2390   if (IsPIC && Subtarget.isSVR4ABI()) {
2391     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2392                                             GSDN->getOffset(),
2393                                             PPCII::MO_PIC_FLAG);
2394     return getTOCEntry(DAG, DL, false, GA);
2395   }
2396 
2397   SDValue GAHi =
2398     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2399   SDValue GALo =
2400     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2401 
2402   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2403 
2404   // If the global reference is actually to a non-lazy-pointer, we have to do an
2405   // extra load to get the address of the global.
2406   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2407     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2408   return Ptr;
2409 }
2410 
2411 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2412   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2413   SDLoc dl(Op);
2414 
2415   if (Op.getValueType() == MVT::v2i64) {
2416     // When the operands themselves are v2i64 values, we need to do something
2417     // special because VSX has no underlying comparison operations for these.
2418     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2419       // Equality can be handled by casting to the legal type for Altivec
2420       // comparisons, everything else needs to be expanded.
2421       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2422         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2423                  DAG.getSetCC(dl, MVT::v4i32,
2424                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2425                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2426                    CC));
2427       }
2428 
2429       return SDValue();
2430     }
2431 
2432     // We handle most of these in the usual way.
2433     return Op;
2434   }
2435 
2436   // If we're comparing for equality to zero, expose the fact that this is
2437   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2438   // fold the new nodes.
2439   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2440     return V;
2441 
2442   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2443     // Leave comparisons against 0 and -1 alone for now, since they're usually
2444     // optimized.  FIXME: revisit this when we can custom lower all setcc
2445     // optimizations.
2446     if (C->isAllOnesValue() || C->isNullValue())
2447       return SDValue();
2448   }
2449 
2450   // If we have an integer seteq/setne, turn it into a compare against zero
2451   // by xor'ing the rhs with the lhs, which is faster than setting a
2452   // condition register, reading it back out, and masking the correct bit.  The
2453   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2454   // the result to other bit-twiddling opportunities.
2455   EVT LHSVT = Op.getOperand(0).getValueType();
2456   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2457     EVT VT = Op.getValueType();
2458     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2459                                 Op.getOperand(1));
2460     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2461   }
2462   return SDValue();
2463 }
2464 
2465 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2466   SDNode *Node = Op.getNode();
2467   EVT VT = Node->getValueType(0);
2468   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2469   SDValue InChain = Node->getOperand(0);
2470   SDValue VAListPtr = Node->getOperand(1);
2471   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2472   SDLoc dl(Node);
2473 
2474   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2475 
2476   // gpr_index
2477   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2478                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2479   InChain = GprIndex.getValue(1);
2480 
2481   if (VT == MVT::i64) {
2482     // Check if GprIndex is even
2483     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2484                                  DAG.getConstant(1, dl, MVT::i32));
2485     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2486                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2487     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2488                                           DAG.getConstant(1, dl, MVT::i32));
2489     // Align GprIndex to be even if it isn't
2490     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2491                            GprIndex);
2492   }
2493 
2494   // fpr index is 1 byte after gpr
2495   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2496                                DAG.getConstant(1, dl, MVT::i32));
2497 
2498   // fpr
2499   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2500                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2501   InChain = FprIndex.getValue(1);
2502 
2503   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2504                                        DAG.getConstant(8, dl, MVT::i32));
2505 
2506   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2507                                         DAG.getConstant(4, dl, MVT::i32));
2508 
2509   // areas
2510   SDValue OverflowArea =
2511       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2512   InChain = OverflowArea.getValue(1);
2513 
2514   SDValue RegSaveArea =
2515       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2516   InChain = RegSaveArea.getValue(1);
2517 
2518   // select overflow_area if index > 8
2519   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2520                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2521 
2522   // adjustment constant gpr_index * 4/8
2523   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2524                                     VT.isInteger() ? GprIndex : FprIndex,
2525                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2526                                                     MVT::i32));
2527 
2528   // OurReg = RegSaveArea + RegConstant
2529   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2530                                RegConstant);
2531 
2532   // Floating types are 32 bytes into RegSaveArea
2533   if (VT.isFloatingPoint())
2534     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2535                          DAG.getConstant(32, dl, MVT::i32));
2536 
2537   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2538   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2539                                    VT.isInteger() ? GprIndex : FprIndex,
2540                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2541                                                    MVT::i32));
2542 
2543   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2544                               VT.isInteger() ? VAListPtr : FprPtr,
2545                               MachinePointerInfo(SV), MVT::i8);
2546 
2547   // determine if we should load from reg_save_area or overflow_area
2548   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2549 
2550   // increase overflow_area by 4/8 if gpr/fpr > 8
2551   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2552                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2553                                           dl, MVT::i32));
2554 
2555   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2556                              OverflowAreaPlusN);
2557 
2558   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2559                               MachinePointerInfo(), MVT::i32);
2560 
2561   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2562 }
2563 
2564 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2565   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2566 
2567   // We have to copy the entire va_list struct:
2568   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2569   return DAG.getMemcpy(Op.getOperand(0), Op,
2570                        Op.getOperand(1), Op.getOperand(2),
2571                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2572                        false, MachinePointerInfo(), MachinePointerInfo());
2573 }
2574 
2575 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2576                                                   SelectionDAG &DAG) const {
2577   return Op.getOperand(0);
2578 }
2579 
2580 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2581                                                 SelectionDAG &DAG) const {
2582   SDValue Chain = Op.getOperand(0);
2583   SDValue Trmp = Op.getOperand(1); // trampoline
2584   SDValue FPtr = Op.getOperand(2); // nested function
2585   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2586   SDLoc dl(Op);
2587 
2588   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2589   bool isPPC64 = (PtrVT == MVT::i64);
2590   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2591 
2592   TargetLowering::ArgListTy Args;
2593   TargetLowering::ArgListEntry Entry;
2594 
2595   Entry.Ty = IntPtrTy;
2596   Entry.Node = Trmp; Args.push_back(Entry);
2597 
2598   // TrampSize == (isPPC64 ? 48 : 40);
2599   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2600                                isPPC64 ? MVT::i64 : MVT::i32);
2601   Args.push_back(Entry);
2602 
2603   Entry.Node = FPtr; Args.push_back(Entry);
2604   Entry.Node = Nest; Args.push_back(Entry);
2605 
2606   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2607   TargetLowering::CallLoweringInfo CLI(DAG);
2608   CLI.setDebugLoc(dl).setChain(Chain)
2609     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2610                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2611                std::move(Args));
2612 
2613   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2614   return CallResult.second;
2615 }
2616 
2617 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2618   MachineFunction &MF = DAG.getMachineFunction();
2619   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2620   EVT PtrVT = getPointerTy(MF.getDataLayout());
2621 
2622   SDLoc dl(Op);
2623 
2624   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2625     // vastart just stores the address of the VarArgsFrameIndex slot into the
2626     // memory location argument.
2627     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2628     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2629     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2630                         MachinePointerInfo(SV));
2631   }
2632 
2633   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2634   // We suppose the given va_list is already allocated.
2635   //
2636   // typedef struct {
2637   //  char gpr;     /* index into the array of 8 GPRs
2638   //                 * stored in the register save area
2639   //                 * gpr=0 corresponds to r3,
2640   //                 * gpr=1 to r4, etc.
2641   //                 */
2642   //  char fpr;     /* index into the array of 8 FPRs
2643   //                 * stored in the register save area
2644   //                 * fpr=0 corresponds to f1,
2645   //                 * fpr=1 to f2, etc.
2646   //                 */
2647   //  char *overflow_arg_area;
2648   //                /* location on stack that holds
2649   //                 * the next overflow argument
2650   //                 */
2651   //  char *reg_save_area;
2652   //               /* where r3:r10 and f1:f8 (if saved)
2653   //                * are stored
2654   //                */
2655   // } va_list[1];
2656 
2657   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2658   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2659   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2660                                             PtrVT);
2661   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2662                                  PtrVT);
2663 
2664   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2665   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2666 
2667   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2668   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2669 
2670   uint64_t FPROffset = 1;
2671   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2672 
2673   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2674 
2675   // Store first byte : number of int regs
2676   SDValue firstStore =
2677       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2678                         MachinePointerInfo(SV), MVT::i8);
2679   uint64_t nextOffset = FPROffset;
2680   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2681                                   ConstFPROffset);
2682 
2683   // Store second byte : number of float regs
2684   SDValue secondStore =
2685       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2686                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2687   nextOffset += StackOffset;
2688   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2689 
2690   // Store second word : arguments given on stack
2691   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2692                                     MachinePointerInfo(SV, nextOffset));
2693   nextOffset += FrameOffset;
2694   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2695 
2696   // Store third word : arguments given in registers
2697   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2698                       MachinePointerInfo(SV, nextOffset));
2699 }
2700 
2701 #include "PPCGenCallingConv.inc"
2702 
2703 // Function whose sole purpose is to kill compiler warnings
2704 // stemming from unused functions included from PPCGenCallingConv.inc.
2705 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2706   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2707 }
2708 
2709 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2710                                       CCValAssign::LocInfo &LocInfo,
2711                                       ISD::ArgFlagsTy &ArgFlags,
2712                                       CCState &State) {
2713   return true;
2714 }
2715 
2716 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2717                                              MVT &LocVT,
2718                                              CCValAssign::LocInfo &LocInfo,
2719                                              ISD::ArgFlagsTy &ArgFlags,
2720                                              CCState &State) {
2721   static const MCPhysReg ArgRegs[] = {
2722     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2723     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2724   };
2725   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2726 
2727   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2728 
2729   // Skip one register if the first unallocated register has an even register
2730   // number and there are still argument registers available which have not been
2731   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2732   // need to skip a register if RegNum is odd.
2733   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2734     State.AllocateReg(ArgRegs[RegNum]);
2735   }
2736 
2737   // Always return false here, as this function only makes sure that the first
2738   // unallocated register has an odd register number and does not actually
2739   // allocate a register for the current argument.
2740   return false;
2741 }
2742 
2743 bool
2744 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2745                                                   MVT &LocVT,
2746                                                   CCValAssign::LocInfo &LocInfo,
2747                                                   ISD::ArgFlagsTy &ArgFlags,
2748                                                   CCState &State) {
2749   static const MCPhysReg ArgRegs[] = {
2750     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2751     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2752   };
2753   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2754 
2755   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2756   int RegsLeft = NumArgRegs - RegNum;
2757 
2758   // Skip if there is not enough registers left for long double type (4 gpr regs
2759   // in soft float mode) and put long double argument on the stack.
2760   if (RegNum != NumArgRegs && RegsLeft < 4) {
2761     for (int i = 0; i < RegsLeft; i++) {
2762       State.AllocateReg(ArgRegs[RegNum + i]);
2763     }
2764   }
2765 
2766   return false;
2767 }
2768 
2769 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2770                                                MVT &LocVT,
2771                                                CCValAssign::LocInfo &LocInfo,
2772                                                ISD::ArgFlagsTy &ArgFlags,
2773                                                CCState &State) {
2774   static const MCPhysReg ArgRegs[] = {
2775     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2776     PPC::F8
2777   };
2778 
2779   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2780 
2781   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2782 
2783   // If there is only one Floating-point register left we need to put both f64
2784   // values of a split ppc_fp128 value on the stack.
2785   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2786     State.AllocateReg(ArgRegs[RegNum]);
2787   }
2788 
2789   // Always return false here, as this function only makes sure that the two f64
2790   // values a ppc_fp128 value is split into are both passed in registers or both
2791   // passed on the stack and does not actually allocate a register for the
2792   // current argument.
2793   return false;
2794 }
2795 
2796 /// FPR - The set of FP registers that should be allocated for arguments,
2797 /// on Darwin.
2798 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2799                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2800                                 PPC::F11, PPC::F12, PPC::F13};
2801 
2802 /// QFPR - The set of QPX registers that should be allocated for arguments.
2803 static const MCPhysReg QFPR[] = {
2804     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2805     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2806 
2807 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2808 /// the stack.
2809 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2810                                        unsigned PtrByteSize) {
2811   unsigned ArgSize = ArgVT.getStoreSize();
2812   if (Flags.isByVal())
2813     ArgSize = Flags.getByValSize();
2814 
2815   // Round up to multiples of the pointer size, except for array members,
2816   // which are always packed.
2817   if (!Flags.isInConsecutiveRegs())
2818     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2819 
2820   return ArgSize;
2821 }
2822 
2823 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2824 /// on the stack.
2825 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2826                                             ISD::ArgFlagsTy Flags,
2827                                             unsigned PtrByteSize) {
2828   unsigned Align = PtrByteSize;
2829 
2830   // Altivec parameters are padded to a 16 byte boundary.
2831   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2832       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2833       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2834       ArgVT == MVT::v1i128)
2835     Align = 16;
2836   // QPX vector types stored in double-precision are padded to a 32 byte
2837   // boundary.
2838   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2839     Align = 32;
2840 
2841   // ByVal parameters are aligned as requested.
2842   if (Flags.isByVal()) {
2843     unsigned BVAlign = Flags.getByValAlign();
2844     if (BVAlign > PtrByteSize) {
2845       if (BVAlign % PtrByteSize != 0)
2846           llvm_unreachable(
2847             "ByVal alignment is not a multiple of the pointer size");
2848 
2849       Align = BVAlign;
2850     }
2851   }
2852 
2853   // Array members are always packed to their original alignment.
2854   if (Flags.isInConsecutiveRegs()) {
2855     // If the array member was split into multiple registers, the first
2856     // needs to be aligned to the size of the full type.  (Except for
2857     // ppcf128, which is only aligned as its f64 components.)
2858     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2859       Align = OrigVT.getStoreSize();
2860     else
2861       Align = ArgVT.getStoreSize();
2862   }
2863 
2864   return Align;
2865 }
2866 
2867 /// CalculateStackSlotUsed - Return whether this argument will use its
2868 /// stack slot (instead of being passed in registers).  ArgOffset,
2869 /// AvailableFPRs, and AvailableVRs must hold the current argument
2870 /// position, and will be updated to account for this argument.
2871 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2872                                    ISD::ArgFlagsTy Flags,
2873                                    unsigned PtrByteSize,
2874                                    unsigned LinkageSize,
2875                                    unsigned ParamAreaSize,
2876                                    unsigned &ArgOffset,
2877                                    unsigned &AvailableFPRs,
2878                                    unsigned &AvailableVRs, bool HasQPX) {
2879   bool UseMemory = false;
2880 
2881   // Respect alignment of argument on the stack.
2882   unsigned Align =
2883     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2884   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2885   // If there's no space left in the argument save area, we must
2886   // use memory (this check also catches zero-sized arguments).
2887   if (ArgOffset >= LinkageSize + ParamAreaSize)
2888     UseMemory = true;
2889 
2890   // Allocate argument on the stack.
2891   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2892   if (Flags.isInConsecutiveRegsLast())
2893     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2894   // If we overran the argument save area, we must use memory
2895   // (this check catches arguments passed partially in memory)
2896   if (ArgOffset > LinkageSize + ParamAreaSize)
2897     UseMemory = true;
2898 
2899   // However, if the argument is actually passed in an FPR or a VR,
2900   // we don't use memory after all.
2901   if (!Flags.isByVal()) {
2902     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2903         // QPX registers overlap with the scalar FP registers.
2904         (HasQPX && (ArgVT == MVT::v4f32 ||
2905                     ArgVT == MVT::v4f64 ||
2906                     ArgVT == MVT::v4i1)))
2907       if (AvailableFPRs > 0) {
2908         --AvailableFPRs;
2909         return false;
2910       }
2911     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2912         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2913         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2914         ArgVT == MVT::v1i128)
2915       if (AvailableVRs > 0) {
2916         --AvailableVRs;
2917         return false;
2918       }
2919   }
2920 
2921   return UseMemory;
2922 }
2923 
2924 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2925 /// ensure minimum alignment required for target.
2926 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2927                                      unsigned NumBytes) {
2928   unsigned TargetAlign = Lowering->getStackAlignment();
2929   unsigned AlignMask = TargetAlign - 1;
2930   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2931   return NumBytes;
2932 }
2933 
2934 SDValue PPCTargetLowering::LowerFormalArguments(
2935     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2936     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2937     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2938   if (Subtarget.isSVR4ABI()) {
2939     if (Subtarget.isPPC64())
2940       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2941                                          dl, DAG, InVals);
2942     else
2943       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2944                                          dl, DAG, InVals);
2945   } else {
2946     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2947                                        dl, DAG, InVals);
2948   }
2949 }
2950 
2951 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2952     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2953     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2954     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2955 
2956   // 32-bit SVR4 ABI Stack Frame Layout:
2957   //              +-----------------------------------+
2958   //        +-->  |            Back chain             |
2959   //        |     +-----------------------------------+
2960   //        |     | Floating-point register save area |
2961   //        |     +-----------------------------------+
2962   //        |     |    General register save area     |
2963   //        |     +-----------------------------------+
2964   //        |     |          CR save word             |
2965   //        |     +-----------------------------------+
2966   //        |     |         VRSAVE save word          |
2967   //        |     +-----------------------------------+
2968   //        |     |         Alignment padding         |
2969   //        |     +-----------------------------------+
2970   //        |     |     Vector register save area     |
2971   //        |     +-----------------------------------+
2972   //        |     |       Local variable space        |
2973   //        |     +-----------------------------------+
2974   //        |     |        Parameter list area        |
2975   //        |     +-----------------------------------+
2976   //        |     |           LR save word            |
2977   //        |     +-----------------------------------+
2978   // SP-->  +---  |            Back chain             |
2979   //              +-----------------------------------+
2980   //
2981   // Specifications:
2982   //   System V Application Binary Interface PowerPC Processor Supplement
2983   //   AltiVec Technology Programming Interface Manual
2984 
2985   MachineFunction &MF = DAG.getMachineFunction();
2986   MachineFrameInfo &MFI = MF.getFrameInfo();
2987   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2988 
2989   EVT PtrVT = getPointerTy(MF.getDataLayout());
2990   // Potential tail calls could cause overwriting of argument stack slots.
2991   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2992                        (CallConv == CallingConv::Fast));
2993   unsigned PtrByteSize = 4;
2994 
2995   // Assign locations to all of the incoming arguments.
2996   SmallVector<CCValAssign, 16> ArgLocs;
2997   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2998                  *DAG.getContext());
2999 
3000   // Reserve space for the linkage area on the stack.
3001   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3002   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3003   if (useSoftFloat())
3004     CCInfo.PreAnalyzeFormalArguments(Ins);
3005 
3006   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3007   CCInfo.clearWasPPCF128();
3008 
3009   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3010     CCValAssign &VA = ArgLocs[i];
3011 
3012     // Arguments stored in registers.
3013     if (VA.isRegLoc()) {
3014       const TargetRegisterClass *RC;
3015       EVT ValVT = VA.getValVT();
3016 
3017       switch (ValVT.getSimpleVT().SimpleTy) {
3018         default:
3019           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3020         case MVT::i1:
3021         case MVT::i32:
3022           RC = &PPC::GPRCRegClass;
3023           break;
3024         case MVT::f32:
3025           if (Subtarget.hasP8Vector())
3026             RC = &PPC::VSSRCRegClass;
3027           else
3028             RC = &PPC::F4RCRegClass;
3029           break;
3030         case MVT::f64:
3031           if (Subtarget.hasVSX())
3032             RC = &PPC::VSFRCRegClass;
3033           else
3034             RC = &PPC::F8RCRegClass;
3035           break;
3036         case MVT::v16i8:
3037         case MVT::v8i16:
3038         case MVT::v4i32:
3039           RC = &PPC::VRRCRegClass;
3040           break;
3041         case MVT::v4f32:
3042           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3043           break;
3044         case MVT::v2f64:
3045         case MVT::v2i64:
3046           RC = &PPC::VRRCRegClass;
3047           break;
3048         case MVT::v4f64:
3049           RC = &PPC::QFRCRegClass;
3050           break;
3051         case MVT::v4i1:
3052           RC = &PPC::QBRCRegClass;
3053           break;
3054       }
3055 
3056       // Transform the arguments stored in physical registers into virtual ones.
3057       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3058       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3059                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3060 
3061       if (ValVT == MVT::i1)
3062         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3063 
3064       InVals.push_back(ArgValue);
3065     } else {
3066       // Argument stored in memory.
3067       assert(VA.isMemLoc());
3068 
3069       unsigned ArgSize = VA.getLocVT().getStoreSize();
3070       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3071                                      isImmutable);
3072 
3073       // Create load nodes to retrieve arguments from the stack.
3074       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3075       InVals.push_back(
3076           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3077     }
3078   }
3079 
3080   // Assign locations to all of the incoming aggregate by value arguments.
3081   // Aggregates passed by value are stored in the local variable space of the
3082   // caller's stack frame, right above the parameter list area.
3083   SmallVector<CCValAssign, 16> ByValArgLocs;
3084   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3085                       ByValArgLocs, *DAG.getContext());
3086 
3087   // Reserve stack space for the allocations in CCInfo.
3088   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3089 
3090   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3091 
3092   // Area that is at least reserved in the caller of this function.
3093   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3094   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3095 
3096   // Set the size that is at least reserved in caller of this function.  Tail
3097   // call optimized function's reserved stack space needs to be aligned so that
3098   // taking the difference between two stack areas will result in an aligned
3099   // stack.
3100   MinReservedArea =
3101       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3102   FuncInfo->setMinReservedArea(MinReservedArea);
3103 
3104   SmallVector<SDValue, 8> MemOps;
3105 
3106   // If the function takes variable number of arguments, make a frame index for
3107   // the start of the first vararg value... for expansion of llvm.va_start.
3108   if (isVarArg) {
3109     static const MCPhysReg GPArgRegs[] = {
3110       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3111       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3112     };
3113     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3114 
3115     static const MCPhysReg FPArgRegs[] = {
3116       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3117       PPC::F8
3118     };
3119     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3120 
3121     if (useSoftFloat())
3122        NumFPArgRegs = 0;
3123 
3124     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3125     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3126 
3127     // Make room for NumGPArgRegs and NumFPArgRegs.
3128     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3129                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3130 
3131     FuncInfo->setVarArgsStackOffset(
3132       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3133                             CCInfo.getNextStackOffset(), true));
3134 
3135     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3136     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3137 
3138     // The fixed integer arguments of a variadic function are stored to the
3139     // VarArgsFrameIndex on the stack so that they may be loaded by
3140     // dereferencing the result of va_next.
3141     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3142       // Get an existing live-in vreg, or add a new one.
3143       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3144       if (!VReg)
3145         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3146 
3147       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3148       SDValue Store =
3149           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3150       MemOps.push_back(Store);
3151       // Increment the address by four for the next argument to store
3152       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3153       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3154     }
3155 
3156     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3157     // is set.
3158     // The double arguments are stored to the VarArgsFrameIndex
3159     // on the stack.
3160     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3161       // Get an existing live-in vreg, or add a new one.
3162       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3163       if (!VReg)
3164         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3165 
3166       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3167       SDValue Store =
3168           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3169       MemOps.push_back(Store);
3170       // Increment the address by eight for the next argument to store
3171       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3172                                          PtrVT);
3173       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3174     }
3175   }
3176 
3177   if (!MemOps.empty())
3178     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3179 
3180   return Chain;
3181 }
3182 
3183 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3184 // value to MVT::i64 and then truncate to the correct register size.
3185 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3186                                              EVT ObjectVT, SelectionDAG &DAG,
3187                                              SDValue ArgVal,
3188                                              const SDLoc &dl) const {
3189   if (Flags.isSExt())
3190     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3191                          DAG.getValueType(ObjectVT));
3192   else if (Flags.isZExt())
3193     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3194                          DAG.getValueType(ObjectVT));
3195 
3196   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3197 }
3198 
3199 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3200     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3201     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3202     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3203   // TODO: add description of PPC stack frame format, or at least some docs.
3204   //
3205   bool isELFv2ABI = Subtarget.isELFv2ABI();
3206   bool isLittleEndian = Subtarget.isLittleEndian();
3207   MachineFunction &MF = DAG.getMachineFunction();
3208   MachineFrameInfo &MFI = MF.getFrameInfo();
3209   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3210 
3211   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3212          "fastcc not supported on varargs functions");
3213 
3214   EVT PtrVT = getPointerTy(MF.getDataLayout());
3215   // Potential tail calls could cause overwriting of argument stack slots.
3216   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3217                        (CallConv == CallingConv::Fast));
3218   unsigned PtrByteSize = 8;
3219   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3220 
3221   static const MCPhysReg GPR[] = {
3222     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3223     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3224   };
3225   static const MCPhysReg VR[] = {
3226     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3227     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3228   };
3229 
3230   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3231   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3232   const unsigned Num_VR_Regs  = array_lengthof(VR);
3233   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3234 
3235   // Do a first pass over the arguments to determine whether the ABI
3236   // guarantees that our caller has allocated the parameter save area
3237   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3238   // in the ELFv2 ABI, it is true if this is a vararg function or if
3239   // any parameter is located in a stack slot.
3240 
3241   bool HasParameterArea = !isELFv2ABI || isVarArg;
3242   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3243   unsigned NumBytes = LinkageSize;
3244   unsigned AvailableFPRs = Num_FPR_Regs;
3245   unsigned AvailableVRs = Num_VR_Regs;
3246   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3247     if (Ins[i].Flags.isNest())
3248       continue;
3249 
3250     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3251                                PtrByteSize, LinkageSize, ParamAreaSize,
3252                                NumBytes, AvailableFPRs, AvailableVRs,
3253                                Subtarget.hasQPX()))
3254       HasParameterArea = true;
3255   }
3256 
3257   // Add DAG nodes to load the arguments or copy them out of registers.  On
3258   // entry to a function on PPC, the arguments start after the linkage area,
3259   // although the first ones are often in registers.
3260 
3261   unsigned ArgOffset = LinkageSize;
3262   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3263   unsigned &QFPR_idx = FPR_idx;
3264   SmallVector<SDValue, 8> MemOps;
3265   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3266   unsigned CurArgIdx = 0;
3267   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3268     SDValue ArgVal;
3269     bool needsLoad = false;
3270     EVT ObjectVT = Ins[ArgNo].VT;
3271     EVT OrigVT = Ins[ArgNo].ArgVT;
3272     unsigned ObjSize = ObjectVT.getStoreSize();
3273     unsigned ArgSize = ObjSize;
3274     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3275     if (Ins[ArgNo].isOrigArg()) {
3276       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3277       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3278     }
3279     // We re-align the argument offset for each argument, except when using the
3280     // fast calling convention, when we need to make sure we do that only when
3281     // we'll actually use a stack slot.
3282     unsigned CurArgOffset, Align;
3283     auto ComputeArgOffset = [&]() {
3284       /* Respect alignment of argument on the stack.  */
3285       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3286       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3287       CurArgOffset = ArgOffset;
3288     };
3289 
3290     if (CallConv != CallingConv::Fast) {
3291       ComputeArgOffset();
3292 
3293       /* Compute GPR index associated with argument offset.  */
3294       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3295       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3296     }
3297 
3298     // FIXME the codegen can be much improved in some cases.
3299     // We do not have to keep everything in memory.
3300     if (Flags.isByVal()) {
3301       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3302 
3303       if (CallConv == CallingConv::Fast)
3304         ComputeArgOffset();
3305 
3306       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3307       ObjSize = Flags.getByValSize();
3308       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3309       // Empty aggregate parameters do not take up registers.  Examples:
3310       //   struct { } a;
3311       //   union  { } b;
3312       //   int c[0];
3313       // etc.  However, we have to provide a place-holder in InVals, so
3314       // pretend we have an 8-byte item at the current address for that
3315       // purpose.
3316       if (!ObjSize) {
3317         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3318         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3319         InVals.push_back(FIN);
3320         continue;
3321       }
3322 
3323       // Create a stack object covering all stack doublewords occupied
3324       // by the argument.  If the argument is (fully or partially) on
3325       // the stack, or if the argument is fully in registers but the
3326       // caller has allocated the parameter save anyway, we can refer
3327       // directly to the caller's stack frame.  Otherwise, create a
3328       // local copy in our own frame.
3329       int FI;
3330       if (HasParameterArea ||
3331           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3332         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3333       else
3334         FI = MFI.CreateStackObject(ArgSize, Align, false);
3335       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3336 
3337       // Handle aggregates smaller than 8 bytes.
3338       if (ObjSize < PtrByteSize) {
3339         // The value of the object is its address, which differs from the
3340         // address of the enclosing doubleword on big-endian systems.
3341         SDValue Arg = FIN;
3342         if (!isLittleEndian) {
3343           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3344           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3345         }
3346         InVals.push_back(Arg);
3347 
3348         if (GPR_idx != Num_GPR_Regs) {
3349           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3350           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3351           SDValue Store;
3352 
3353           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3354             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3355                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3356             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3357                                       MachinePointerInfo(&*FuncArg), ObjType);
3358           } else {
3359             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3360             // store the whole register as-is to the parameter save area
3361             // slot.
3362             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3363                                  MachinePointerInfo(&*FuncArg));
3364           }
3365 
3366           MemOps.push_back(Store);
3367         }
3368         // Whether we copied from a register or not, advance the offset
3369         // into the parameter save area by a full doubleword.
3370         ArgOffset += PtrByteSize;
3371         continue;
3372       }
3373 
3374       // The value of the object is its address, which is the address of
3375       // its first stack doubleword.
3376       InVals.push_back(FIN);
3377 
3378       // Store whatever pieces of the object are in registers to memory.
3379       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3380         if (GPR_idx == Num_GPR_Regs)
3381           break;
3382 
3383         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3384         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3385         SDValue Addr = FIN;
3386         if (j) {
3387           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3388           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3389         }
3390         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3391                                      MachinePointerInfo(&*FuncArg, j));
3392         MemOps.push_back(Store);
3393         ++GPR_idx;
3394       }
3395       ArgOffset += ArgSize;
3396       continue;
3397     }
3398 
3399     switch (ObjectVT.getSimpleVT().SimpleTy) {
3400     default: llvm_unreachable("Unhandled argument type!");
3401     case MVT::i1:
3402     case MVT::i32:
3403     case MVT::i64:
3404       if (Flags.isNest()) {
3405         // The 'nest' parameter, if any, is passed in R11.
3406         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3407         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3408 
3409         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3410           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3411 
3412         break;
3413       }
3414 
3415       // These can be scalar arguments or elements of an integer array type
3416       // passed directly.  Clang may use those instead of "byval" aggregate
3417       // types to avoid forcing arguments to memory unnecessarily.
3418       if (GPR_idx != Num_GPR_Regs) {
3419         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3420         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3421 
3422         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3423           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3424           // value to MVT::i64 and then truncate to the correct register size.
3425           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3426       } else {
3427         if (CallConv == CallingConv::Fast)
3428           ComputeArgOffset();
3429 
3430         needsLoad = true;
3431         ArgSize = PtrByteSize;
3432       }
3433       if (CallConv != CallingConv::Fast || needsLoad)
3434         ArgOffset += 8;
3435       break;
3436 
3437     case MVT::f32:
3438     case MVT::f64:
3439       // These can be scalar arguments or elements of a float array type
3440       // passed directly.  The latter are used to implement ELFv2 homogenous
3441       // float aggregates.
3442       if (FPR_idx != Num_FPR_Regs) {
3443         unsigned VReg;
3444 
3445         if (ObjectVT == MVT::f32)
3446           VReg = MF.addLiveIn(FPR[FPR_idx],
3447                               Subtarget.hasP8Vector()
3448                                   ? &PPC::VSSRCRegClass
3449                                   : &PPC::F4RCRegClass);
3450         else
3451           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3452                                                 ? &PPC::VSFRCRegClass
3453                                                 : &PPC::F8RCRegClass);
3454 
3455         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3456         ++FPR_idx;
3457       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3458         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3459         // once we support fp <-> gpr moves.
3460 
3461         // This can only ever happen in the presence of f32 array types,
3462         // since otherwise we never run out of FPRs before running out
3463         // of GPRs.
3464         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3465         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3466 
3467         if (ObjectVT == MVT::f32) {
3468           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3469             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3470                                  DAG.getConstant(32, dl, MVT::i32));
3471           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3472         }
3473 
3474         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3475       } else {
3476         if (CallConv == CallingConv::Fast)
3477           ComputeArgOffset();
3478 
3479         needsLoad = true;
3480       }
3481 
3482       // When passing an array of floats, the array occupies consecutive
3483       // space in the argument area; only round up to the next doubleword
3484       // at the end of the array.  Otherwise, each float takes 8 bytes.
3485       if (CallConv != CallingConv::Fast || needsLoad) {
3486         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3487         ArgOffset += ArgSize;
3488         if (Flags.isInConsecutiveRegsLast())
3489           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3490       }
3491       break;
3492     case MVT::v4f32:
3493     case MVT::v4i32:
3494     case MVT::v8i16:
3495     case MVT::v16i8:
3496     case MVT::v2f64:
3497     case MVT::v2i64:
3498     case MVT::v1i128:
3499       if (!Subtarget.hasQPX()) {
3500       // These can be scalar arguments or elements of a vector array type
3501       // passed directly.  The latter are used to implement ELFv2 homogenous
3502       // vector aggregates.
3503       if (VR_idx != Num_VR_Regs) {
3504         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3505         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3506         ++VR_idx;
3507       } else {
3508         if (CallConv == CallingConv::Fast)
3509           ComputeArgOffset();
3510 
3511         needsLoad = true;
3512       }
3513       if (CallConv != CallingConv::Fast || needsLoad)
3514         ArgOffset += 16;
3515       break;
3516       } // not QPX
3517 
3518       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3519              "Invalid QPX parameter type");
3520       /* fall through */
3521 
3522     case MVT::v4f64:
3523     case MVT::v4i1:
3524       // QPX vectors are treated like their scalar floating-point subregisters
3525       // (except that they're larger).
3526       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3527       if (QFPR_idx != Num_QFPR_Regs) {
3528         const TargetRegisterClass *RC;
3529         switch (ObjectVT.getSimpleVT().SimpleTy) {
3530         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3531         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3532         default:         RC = &PPC::QBRCRegClass; break;
3533         }
3534 
3535         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3536         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3537         ++QFPR_idx;
3538       } else {
3539         if (CallConv == CallingConv::Fast)
3540           ComputeArgOffset();
3541         needsLoad = true;
3542       }
3543       if (CallConv != CallingConv::Fast || needsLoad)
3544         ArgOffset += Sz;
3545       break;
3546     }
3547 
3548     // We need to load the argument to a virtual register if we determined
3549     // above that we ran out of physical registers of the appropriate type.
3550     if (needsLoad) {
3551       if (ObjSize < ArgSize && !isLittleEndian)
3552         CurArgOffset += ArgSize - ObjSize;
3553       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3554       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3555       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3556     }
3557 
3558     InVals.push_back(ArgVal);
3559   }
3560 
3561   // Area that is at least reserved in the caller of this function.
3562   unsigned MinReservedArea;
3563   if (HasParameterArea)
3564     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3565   else
3566     MinReservedArea = LinkageSize;
3567 
3568   // Set the size that is at least reserved in caller of this function.  Tail
3569   // call optimized functions' reserved stack space needs to be aligned so that
3570   // taking the difference between two stack areas will result in an aligned
3571   // stack.
3572   MinReservedArea =
3573       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3574   FuncInfo->setMinReservedArea(MinReservedArea);
3575 
3576   // If the function takes variable number of arguments, make a frame index for
3577   // the start of the first vararg value... for expansion of llvm.va_start.
3578   if (isVarArg) {
3579     int Depth = ArgOffset;
3580 
3581     FuncInfo->setVarArgsFrameIndex(
3582       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3583     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3584 
3585     // If this function is vararg, store any remaining integer argument regs
3586     // to their spots on the stack so that they may be loaded by dereferencing
3587     // the result of va_next.
3588     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3589          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3590       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3591       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3592       SDValue Store =
3593           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3594       MemOps.push_back(Store);
3595       // Increment the address by four for the next argument to store
3596       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3597       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3598     }
3599   }
3600 
3601   if (!MemOps.empty())
3602     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3603 
3604   return Chain;
3605 }
3606 
3607 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3608     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3609     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3610     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3611   // TODO: add description of PPC stack frame format, or at least some docs.
3612   //
3613   MachineFunction &MF = DAG.getMachineFunction();
3614   MachineFrameInfo &MFI = MF.getFrameInfo();
3615   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3616 
3617   EVT PtrVT = getPointerTy(MF.getDataLayout());
3618   bool isPPC64 = PtrVT == MVT::i64;
3619   // Potential tail calls could cause overwriting of argument stack slots.
3620   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3621                        (CallConv == CallingConv::Fast));
3622   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3623   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3624   unsigned ArgOffset = LinkageSize;
3625   // Area that is at least reserved in caller of this function.
3626   unsigned MinReservedArea = ArgOffset;
3627 
3628   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3629     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3630     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3631   };
3632   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3633     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3634     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3635   };
3636   static const MCPhysReg VR[] = {
3637     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3638     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3639   };
3640 
3641   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3642   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3643   const unsigned Num_VR_Regs  = array_lengthof( VR);
3644 
3645   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3646 
3647   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3648 
3649   // In 32-bit non-varargs functions, the stack space for vectors is after the
3650   // stack space for non-vectors.  We do not use this space unless we have
3651   // too many vectors to fit in registers, something that only occurs in
3652   // constructed examples:), but we have to walk the arglist to figure
3653   // that out...for the pathological case, compute VecArgOffset as the
3654   // start of the vector parameter area.  Computing VecArgOffset is the
3655   // entire point of the following loop.
3656   unsigned VecArgOffset = ArgOffset;
3657   if (!isVarArg && !isPPC64) {
3658     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3659          ++ArgNo) {
3660       EVT ObjectVT = Ins[ArgNo].VT;
3661       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3662 
3663       if (Flags.isByVal()) {
3664         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3665         unsigned ObjSize = Flags.getByValSize();
3666         unsigned ArgSize =
3667                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3668         VecArgOffset += ArgSize;
3669         continue;
3670       }
3671 
3672       switch(ObjectVT.getSimpleVT().SimpleTy) {
3673       default: llvm_unreachable("Unhandled argument type!");
3674       case MVT::i1:
3675       case MVT::i32:
3676       case MVT::f32:
3677         VecArgOffset += 4;
3678         break;
3679       case MVT::i64:  // PPC64
3680       case MVT::f64:
3681         // FIXME: We are guaranteed to be !isPPC64 at this point.
3682         // Does MVT::i64 apply?
3683         VecArgOffset += 8;
3684         break;
3685       case MVT::v4f32:
3686       case MVT::v4i32:
3687       case MVT::v8i16:
3688       case MVT::v16i8:
3689         // Nothing to do, we're only looking at Nonvector args here.
3690         break;
3691       }
3692     }
3693   }
3694   // We've found where the vector parameter area in memory is.  Skip the
3695   // first 12 parameters; these don't use that memory.
3696   VecArgOffset = ((VecArgOffset+15)/16)*16;
3697   VecArgOffset += 12*16;
3698 
3699   // Add DAG nodes to load the arguments or copy them out of registers.  On
3700   // entry to a function on PPC, the arguments start after the linkage area,
3701   // although the first ones are often in registers.
3702 
3703   SmallVector<SDValue, 8> MemOps;
3704   unsigned nAltivecParamsAtEnd = 0;
3705   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3706   unsigned CurArgIdx = 0;
3707   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3708     SDValue ArgVal;
3709     bool needsLoad = false;
3710     EVT ObjectVT = Ins[ArgNo].VT;
3711     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3712     unsigned ArgSize = ObjSize;
3713     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3714     if (Ins[ArgNo].isOrigArg()) {
3715       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3716       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3717     }
3718     unsigned CurArgOffset = ArgOffset;
3719 
3720     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3721     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3722         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3723       if (isVarArg || isPPC64) {
3724         MinReservedArea = ((MinReservedArea+15)/16)*16;
3725         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3726                                                   Flags,
3727                                                   PtrByteSize);
3728       } else  nAltivecParamsAtEnd++;
3729     } else
3730       // Calculate min reserved area.
3731       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3732                                                 Flags,
3733                                                 PtrByteSize);
3734 
3735     // FIXME the codegen can be much improved in some cases.
3736     // We do not have to keep everything in memory.
3737     if (Flags.isByVal()) {
3738       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3739 
3740       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3741       ObjSize = Flags.getByValSize();
3742       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3743       // Objects of size 1 and 2 are right justified, everything else is
3744       // left justified.  This means the memory address is adjusted forwards.
3745       if (ObjSize==1 || ObjSize==2) {
3746         CurArgOffset = CurArgOffset + (4 - ObjSize);
3747       }
3748       // The value of the object is its address.
3749       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3750       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3751       InVals.push_back(FIN);
3752       if (ObjSize==1 || ObjSize==2) {
3753         if (GPR_idx != Num_GPR_Regs) {
3754           unsigned VReg;
3755           if (isPPC64)
3756             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3757           else
3758             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3759           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3760           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3761           SDValue Store =
3762               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3763                                 MachinePointerInfo(&*FuncArg), ObjType);
3764           MemOps.push_back(Store);
3765           ++GPR_idx;
3766         }
3767 
3768         ArgOffset += PtrByteSize;
3769 
3770         continue;
3771       }
3772       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3773         // Store whatever pieces of the object are in registers
3774         // to memory.  ArgOffset will be the address of the beginning
3775         // of the object.
3776         if (GPR_idx != Num_GPR_Regs) {
3777           unsigned VReg;
3778           if (isPPC64)
3779             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3780           else
3781             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3782           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3783           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3784           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3785           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3786                                        MachinePointerInfo(&*FuncArg, j));
3787           MemOps.push_back(Store);
3788           ++GPR_idx;
3789           ArgOffset += PtrByteSize;
3790         } else {
3791           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3792           break;
3793         }
3794       }
3795       continue;
3796     }
3797 
3798     switch (ObjectVT.getSimpleVT().SimpleTy) {
3799     default: llvm_unreachable("Unhandled argument type!");
3800     case MVT::i1:
3801     case MVT::i32:
3802       if (!isPPC64) {
3803         if (GPR_idx != Num_GPR_Regs) {
3804           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3805           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3806 
3807           if (ObjectVT == MVT::i1)
3808             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3809 
3810           ++GPR_idx;
3811         } else {
3812           needsLoad = true;
3813           ArgSize = PtrByteSize;
3814         }
3815         // All int arguments reserve stack space in the Darwin ABI.
3816         ArgOffset += PtrByteSize;
3817         break;
3818       }
3819       LLVM_FALLTHROUGH;
3820     case MVT::i64:  // PPC64
3821       if (GPR_idx != Num_GPR_Regs) {
3822         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3823         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3824 
3825         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3826           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3827           // value to MVT::i64 and then truncate to the correct register size.
3828           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3829 
3830         ++GPR_idx;
3831       } else {
3832         needsLoad = true;
3833         ArgSize = PtrByteSize;
3834       }
3835       // All int arguments reserve stack space in the Darwin ABI.
3836       ArgOffset += 8;
3837       break;
3838 
3839     case MVT::f32:
3840     case MVT::f64:
3841       // Every 4 bytes of argument space consumes one of the GPRs available for
3842       // argument passing.
3843       if (GPR_idx != Num_GPR_Regs) {
3844         ++GPR_idx;
3845         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3846           ++GPR_idx;
3847       }
3848       if (FPR_idx != Num_FPR_Regs) {
3849         unsigned VReg;
3850 
3851         if (ObjectVT == MVT::f32)
3852           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3853         else
3854           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3855 
3856         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3857         ++FPR_idx;
3858       } else {
3859         needsLoad = true;
3860       }
3861 
3862       // All FP arguments reserve stack space in the Darwin ABI.
3863       ArgOffset += isPPC64 ? 8 : ObjSize;
3864       break;
3865     case MVT::v4f32:
3866     case MVT::v4i32:
3867     case MVT::v8i16:
3868     case MVT::v16i8:
3869       // Note that vector arguments in registers don't reserve stack space,
3870       // except in varargs functions.
3871       if (VR_idx != Num_VR_Regs) {
3872         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3873         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3874         if (isVarArg) {
3875           while ((ArgOffset % 16) != 0) {
3876             ArgOffset += PtrByteSize;
3877             if (GPR_idx != Num_GPR_Regs)
3878               GPR_idx++;
3879           }
3880           ArgOffset += 16;
3881           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3882         }
3883         ++VR_idx;
3884       } else {
3885         if (!isVarArg && !isPPC64) {
3886           // Vectors go after all the nonvectors.
3887           CurArgOffset = VecArgOffset;
3888           VecArgOffset += 16;
3889         } else {
3890           // Vectors are aligned.
3891           ArgOffset = ((ArgOffset+15)/16)*16;
3892           CurArgOffset = ArgOffset;
3893           ArgOffset += 16;
3894         }
3895         needsLoad = true;
3896       }
3897       break;
3898     }
3899 
3900     // We need to load the argument to a virtual register if we determined above
3901     // that we ran out of physical registers of the appropriate type.
3902     if (needsLoad) {
3903       int FI = MFI.CreateFixedObject(ObjSize,
3904                                      CurArgOffset + (ArgSize - ObjSize),
3905                                      isImmutable);
3906       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3907       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3908     }
3909 
3910     InVals.push_back(ArgVal);
3911   }
3912 
3913   // Allow for Altivec parameters at the end, if needed.
3914   if (nAltivecParamsAtEnd) {
3915     MinReservedArea = ((MinReservedArea+15)/16)*16;
3916     MinReservedArea += 16*nAltivecParamsAtEnd;
3917   }
3918 
3919   // Area that is at least reserved in the caller of this function.
3920   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3921 
3922   // Set the size that is at least reserved in caller of this function.  Tail
3923   // call optimized functions' reserved stack space needs to be aligned so that
3924   // taking the difference between two stack areas will result in an aligned
3925   // stack.
3926   MinReservedArea =
3927       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3928   FuncInfo->setMinReservedArea(MinReservedArea);
3929 
3930   // If the function takes variable number of arguments, make a frame index for
3931   // the start of the first vararg value... for expansion of llvm.va_start.
3932   if (isVarArg) {
3933     int Depth = ArgOffset;
3934 
3935     FuncInfo->setVarArgsFrameIndex(
3936       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3937                             Depth, true));
3938     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3939 
3940     // If this function is vararg, store any remaining integer argument regs
3941     // to their spots on the stack so that they may be loaded by dereferencing
3942     // the result of va_next.
3943     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3944       unsigned VReg;
3945 
3946       if (isPPC64)
3947         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3948       else
3949         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3950 
3951       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3952       SDValue Store =
3953           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3954       MemOps.push_back(Store);
3955       // Increment the address by four for the next argument to store
3956       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3957       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3958     }
3959   }
3960 
3961   if (!MemOps.empty())
3962     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3963 
3964   return Chain;
3965 }
3966 
3967 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3968 /// adjusted to accommodate the arguments for the tailcall.
3969 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3970                                    unsigned ParamSize) {
3971 
3972   if (!isTailCall) return 0;
3973 
3974   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3975   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3976   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3977   // Remember only if the new adjustement is bigger.
3978   if (SPDiff < FI->getTailCallSPDelta())
3979     FI->setTailCallSPDelta(SPDiff);
3980 
3981   return SPDiff;
3982 }
3983 
3984 static bool isFunctionGlobalAddress(SDValue Callee);
3985 
3986 static bool
3987 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3988   // If !G, Callee can be an external symbol.
3989   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3990   if (!G) return false;
3991 
3992   const GlobalValue *GV = G->getGlobal();
3993 
3994   if (GV->isDeclaration()) return false;
3995 
3996   switch(GV->getLinkage()) {
3997   default: llvm_unreachable("unknow linkage type");
3998   case GlobalValue::AvailableExternallyLinkage:
3999   case GlobalValue::ExternalWeakLinkage:
4000     return false;
4001 
4002   // Callee with weak linkage is allowed if it has hidden or protected
4003   // visibility
4004   case GlobalValue::LinkOnceAnyLinkage:
4005   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
4006   case GlobalValue::WeakAnyLinkage:
4007   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
4008     if (GV->hasDefaultVisibility())
4009       return false;
4010 
4011   case GlobalValue::ExternalLinkage:
4012   case GlobalValue::InternalLinkage:
4013   case GlobalValue::PrivateLinkage:
4014     break;
4015   }
4016 
4017   // With '-fPIC', calling default visiblity function need insert 'nop' after
4018   // function call, no matter that function resides in same module or not, so
4019   // we treat it as in different module.
4020   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
4021     return false;
4022 
4023   return true;
4024 }
4025 
4026 static bool
4027 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4028                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4029   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4030 
4031   const unsigned PtrByteSize = 8;
4032   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4033 
4034   static const MCPhysReg GPR[] = {
4035     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4036     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4037   };
4038   static const MCPhysReg VR[] = {
4039     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4040     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4041   };
4042 
4043   const unsigned NumGPRs = array_lengthof(GPR);
4044   const unsigned NumFPRs = 13;
4045   const unsigned NumVRs = array_lengthof(VR);
4046   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4047 
4048   unsigned NumBytes = LinkageSize;
4049   unsigned AvailableFPRs = NumFPRs;
4050   unsigned AvailableVRs = NumVRs;
4051 
4052   for (const ISD::OutputArg& Param : Outs) {
4053     if (Param.Flags.isNest()) continue;
4054 
4055     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4056                                PtrByteSize, LinkageSize, ParamAreaSize,
4057                                NumBytes, AvailableFPRs, AvailableVRs,
4058                                Subtarget.hasQPX()))
4059       return true;
4060   }
4061   return false;
4062 }
4063 
4064 static bool
4065 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4066   if (CS->arg_size() != CallerFn->getArgumentList().size())
4067     return false;
4068 
4069   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4070   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4071   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4072 
4073   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4074     const Value* CalleeArg = *CalleeArgIter;
4075     const Value* CallerArg = &(*CallerArgIter);
4076     if (CalleeArg == CallerArg)
4077       continue;
4078 
4079     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4080     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4081     //      }
4082     // 1st argument of callee is undef and has the same type as caller.
4083     if (CalleeArg->getType() == CallerArg->getType() &&
4084         isa<UndefValue>(CalleeArg))
4085       continue;
4086 
4087     return false;
4088   }
4089 
4090   return true;
4091 }
4092 
4093 bool
4094 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4095                                     SDValue Callee,
4096                                     CallingConv::ID CalleeCC,
4097                                     ImmutableCallSite *CS,
4098                                     bool isVarArg,
4099                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4100                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4101                                     SelectionDAG& DAG) const {
4102   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4103 
4104   if (DisableSCO && !TailCallOpt) return false;
4105 
4106   // Variadic argument functions are not supported.
4107   if (isVarArg) return false;
4108 
4109   MachineFunction &MF = DAG.getMachineFunction();
4110   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4111 
4112   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4113   // the same calling convention
4114   if (CallerCC != CalleeCC) return false;
4115 
4116   // SCO support C calling convention
4117   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4118     return false;
4119 
4120   // Caller contains any byval parameter is not supported.
4121   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4122     return false;
4123 
4124   // Callee contains any byval parameter is not supported, too.
4125   // Note: This is a quick work around, because in some cases, e.g.
4126   // caller's stack size > callee's stack size, we are still able to apply
4127   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4128   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4129     return false;
4130 
4131   // No TCO/SCO on indirect call because Caller have to restore its TOC
4132   if (!isFunctionGlobalAddress(Callee) &&
4133       !isa<ExternalSymbolSDNode>(Callee))
4134     return false;
4135 
4136   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4137   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4138   // module.
4139   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4140   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4141     return false;
4142 
4143   // TCO allows altering callee ABI, so we don't have to check further.
4144   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4145     return true;
4146 
4147   if (DisableSCO) return false;
4148 
4149   // If callee use the same argument list that caller is using, then we can
4150   // apply SCO on this case. If it is not, then we need to check if callee needs
4151   // stack for passing arguments.
4152   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4153       needStackSlotPassParameters(Subtarget, Outs)) {
4154     return false;
4155   }
4156 
4157   return true;
4158 }
4159 
4160 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4161 /// for tail call optimization. Targets which want to do tail call
4162 /// optimization should implement this function.
4163 bool
4164 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4165                                                      CallingConv::ID CalleeCC,
4166                                                      bool isVarArg,
4167                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4168                                                      SelectionDAG& DAG) const {
4169   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4170     return false;
4171 
4172   // Variable argument functions are not supported.
4173   if (isVarArg)
4174     return false;
4175 
4176   MachineFunction &MF = DAG.getMachineFunction();
4177   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4178   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4179     // Functions containing by val parameters are not supported.
4180     for (unsigned i = 0; i != Ins.size(); i++) {
4181        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4182        if (Flags.isByVal()) return false;
4183     }
4184 
4185     // Non-PIC/GOT tail calls are supported.
4186     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4187       return true;
4188 
4189     // At the moment we can only do local tail calls (in same module, hidden
4190     // or protected) if we are generating PIC.
4191     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4192       return G->getGlobal()->hasHiddenVisibility()
4193           || G->getGlobal()->hasProtectedVisibility();
4194   }
4195 
4196   return false;
4197 }
4198 
4199 /// isCallCompatibleAddress - Return the immediate to use if the specified
4200 /// 32-bit value is representable in the immediate field of a BxA instruction.
4201 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4202   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4203   if (!C) return nullptr;
4204 
4205   int Addr = C->getZExtValue();
4206   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4207       SignExtend32<26>(Addr) != Addr)
4208     return nullptr;  // Top 6 bits have to be sext of immediate.
4209 
4210   return DAG
4211       .getConstant(
4212           (int)C->getZExtValue() >> 2, SDLoc(Op),
4213           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4214       .getNode();
4215 }
4216 
4217 namespace {
4218 
4219 struct TailCallArgumentInfo {
4220   SDValue Arg;
4221   SDValue FrameIdxOp;
4222   int       FrameIdx;
4223 
4224   TailCallArgumentInfo() : FrameIdx(0) {}
4225 };
4226 }
4227 
4228 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4229 static void StoreTailCallArgumentsToStackSlot(
4230     SelectionDAG &DAG, SDValue Chain,
4231     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4232     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4233   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4234     SDValue Arg = TailCallArgs[i].Arg;
4235     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4236     int FI = TailCallArgs[i].FrameIdx;
4237     // Store relative to framepointer.
4238     MemOpChains.push_back(DAG.getStore(
4239         Chain, dl, Arg, FIN,
4240         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4241   }
4242 }
4243 
4244 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4245 /// the appropriate stack slot for the tail call optimized function call.
4246 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4247                                              SDValue OldRetAddr, SDValue OldFP,
4248                                              int SPDiff, const SDLoc &dl) {
4249   if (SPDiff) {
4250     // Calculate the new stack slot for the return address.
4251     MachineFunction &MF = DAG.getMachineFunction();
4252     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4253     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4254     bool isPPC64 = Subtarget.isPPC64();
4255     int SlotSize = isPPC64 ? 8 : 4;
4256     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4257     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4258                                                          NewRetAddrLoc, true);
4259     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4260     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4261     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4262                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4263 
4264     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4265     // slot as the FP is never overwritten.
4266     if (Subtarget.isDarwinABI()) {
4267       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4268       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4269                                                          true);
4270       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4271       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4272                            MachinePointerInfo::getFixedStack(
4273                                DAG.getMachineFunction(), NewFPIdx));
4274     }
4275   }
4276   return Chain;
4277 }
4278 
4279 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4280 /// the position of the argument.
4281 static void
4282 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4283                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4284                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4285   int Offset = ArgOffset + SPDiff;
4286   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4287   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4288   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4289   SDValue FIN = DAG.getFrameIndex(FI, VT);
4290   TailCallArgumentInfo Info;
4291   Info.Arg = Arg;
4292   Info.FrameIdxOp = FIN;
4293   Info.FrameIdx = FI;
4294   TailCallArguments.push_back(Info);
4295 }
4296 
4297 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4298 /// stack slot. Returns the chain as result and the loaded frame pointers in
4299 /// LROpOut/FPOpout. Used when tail calling.
4300 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4301     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4302     SDValue &FPOpOut, const SDLoc &dl) const {
4303   if (SPDiff) {
4304     // Load the LR and FP stack slot for later adjusting.
4305     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4306     LROpOut = getReturnAddrFrameIndex(DAG);
4307     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4308     Chain = SDValue(LROpOut.getNode(), 1);
4309 
4310     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4311     // slot as the FP is never overwritten.
4312     if (Subtarget.isDarwinABI()) {
4313       FPOpOut = getFramePointerFrameIndex(DAG);
4314       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4315       Chain = SDValue(FPOpOut.getNode(), 1);
4316     }
4317   }
4318   return Chain;
4319 }
4320 
4321 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4322 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4323 /// specified by the specific parameter attribute. The copy will be passed as
4324 /// a byval function parameter.
4325 /// Sometimes what we are copying is the end of a larger object, the part that
4326 /// does not fit in registers.
4327 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4328                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4329                                          SelectionDAG &DAG, const SDLoc &dl) {
4330   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4331   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4332                        false, false, false, MachinePointerInfo(),
4333                        MachinePointerInfo());
4334 }
4335 
4336 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4337 /// tail calls.
4338 static void LowerMemOpCallTo(
4339     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4340     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4341     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4342     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4343   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4344   if (!isTailCall) {
4345     if (isVector) {
4346       SDValue StackPtr;
4347       if (isPPC64)
4348         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4349       else
4350         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4351       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4352                            DAG.getConstant(ArgOffset, dl, PtrVT));
4353     }
4354     MemOpChains.push_back(
4355         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4356     // Calculate and remember argument location.
4357   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4358                                   TailCallArguments);
4359 }
4360 
4361 static void
4362 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4363                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4364                 SDValue FPOp,
4365                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4366   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4367   // might overwrite each other in case of tail call optimization.
4368   SmallVector<SDValue, 8> MemOpChains2;
4369   // Do not flag preceding copytoreg stuff together with the following stuff.
4370   InFlag = SDValue();
4371   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4372                                     MemOpChains2, dl);
4373   if (!MemOpChains2.empty())
4374     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4375 
4376   // Store the return address to the appropriate stack slot.
4377   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4378 
4379   // Emit callseq_end just before tailcall node.
4380   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4381                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4382   InFlag = Chain.getValue(1);
4383 }
4384 
4385 // Is this global address that of a function that can be called by name? (as
4386 // opposed to something that must hold a descriptor for an indirect call).
4387 static bool isFunctionGlobalAddress(SDValue Callee) {
4388   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4389     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4390         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4391       return false;
4392 
4393     return G->getGlobal()->getValueType()->isFunctionTy();
4394   }
4395 
4396   return false;
4397 }
4398 
4399 static unsigned
4400 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4401             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4402             bool isPatchPoint, bool hasNest,
4403             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4404             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4405             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4406 
4407   bool isPPC64 = Subtarget.isPPC64();
4408   bool isSVR4ABI = Subtarget.isSVR4ABI();
4409   bool isELFv2ABI = Subtarget.isELFv2ABI();
4410 
4411   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4412   NodeTys.push_back(MVT::Other);   // Returns a chain
4413   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4414 
4415   unsigned CallOpc = PPCISD::CALL;
4416 
4417   bool needIndirectCall = true;
4418   if (!isSVR4ABI || !isPPC64)
4419     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4420       // If this is an absolute destination address, use the munged value.
4421       Callee = SDValue(Dest, 0);
4422       needIndirectCall = false;
4423     }
4424 
4425   // PC-relative references to external symbols should go through $stub, unless
4426   // we're building with the leopard linker or later, which automatically
4427   // synthesizes these stubs.
4428   const TargetMachine &TM = DAG.getTarget();
4429   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4430   const GlobalValue *GV = nullptr;
4431   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4432     GV = G->getGlobal();
4433   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4434   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4435 
4436   if (isFunctionGlobalAddress(Callee)) {
4437     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4438     // A call to a TLS address is actually an indirect call to a
4439     // thread-specific pointer.
4440     unsigned OpFlags = 0;
4441     if (UsePlt)
4442       OpFlags = PPCII::MO_PLT;
4443 
4444     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4445     // every direct call is) turn it into a TargetGlobalAddress /
4446     // TargetExternalSymbol node so that legalize doesn't hack it.
4447     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4448                                         Callee.getValueType(), 0, OpFlags);
4449     needIndirectCall = false;
4450   }
4451 
4452   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4453     unsigned char OpFlags = 0;
4454 
4455     if (UsePlt)
4456       OpFlags = PPCII::MO_PLT;
4457 
4458     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4459                                          OpFlags);
4460     needIndirectCall = false;
4461   }
4462 
4463   if (isPatchPoint) {
4464     // We'll form an invalid direct call when lowering a patchpoint; the full
4465     // sequence for an indirect call is complicated, and many of the
4466     // instructions introduced might have side effects (and, thus, can't be
4467     // removed later). The call itself will be removed as soon as the
4468     // argument/return lowering is complete, so the fact that it has the wrong
4469     // kind of operands should not really matter.
4470     needIndirectCall = false;
4471   }
4472 
4473   if (needIndirectCall) {
4474     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4475     // to do the call, we can't use PPCISD::CALL.
4476     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4477 
4478     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4479       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4480       // entry point, but to the function descriptor (the function entry point
4481       // address is part of the function descriptor though).
4482       // The function descriptor is a three doubleword structure with the
4483       // following fields: function entry point, TOC base address and
4484       // environment pointer.
4485       // Thus for a call through a function pointer, the following actions need
4486       // to be performed:
4487       //   1. Save the TOC of the caller in the TOC save area of its stack
4488       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4489       //   2. Load the address of the function entry point from the function
4490       //      descriptor.
4491       //   3. Load the TOC of the callee from the function descriptor into r2.
4492       //   4. Load the environment pointer from the function descriptor into
4493       //      r11.
4494       //   5. Branch to the function entry point address.
4495       //   6. On return of the callee, the TOC of the caller needs to be
4496       //      restored (this is done in FinishCall()).
4497       //
4498       // The loads are scheduled at the beginning of the call sequence, and the
4499       // register copies are flagged together to ensure that no other
4500       // operations can be scheduled in between. E.g. without flagging the
4501       // copies together, a TOC access in the caller could be scheduled between
4502       // the assignment of the callee TOC and the branch to the callee, which
4503       // results in the TOC access going through the TOC of the callee instead
4504       // of going through the TOC of the caller, which leads to incorrect code.
4505 
4506       // Load the address of the function entry point from the function
4507       // descriptor.
4508       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4509       if (LDChain.getValueType() == MVT::Glue)
4510         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4511 
4512       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4513                           ? (MachineMemOperand::MODereferenceable |
4514                              MachineMemOperand::MOInvariant)
4515                           : MachineMemOperand::MONone;
4516 
4517       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4518       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4519                                         /* Alignment = */ 8, MMOFlags);
4520 
4521       // Load environment pointer into r11.
4522       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4523       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4524       SDValue LoadEnvPtr =
4525           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4526                       /* Alignment = */ 8, MMOFlags);
4527 
4528       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4529       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4530       SDValue TOCPtr =
4531           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4532                       /* Alignment = */ 8, MMOFlags);
4533 
4534       setUsesTOCBasePtr(DAG);
4535       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4536                                         InFlag);
4537       Chain = TOCVal.getValue(0);
4538       InFlag = TOCVal.getValue(1);
4539 
4540       // If the function call has an explicit 'nest' parameter, it takes the
4541       // place of the environment pointer.
4542       if (!hasNest) {
4543         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4544                                           InFlag);
4545 
4546         Chain = EnvVal.getValue(0);
4547         InFlag = EnvVal.getValue(1);
4548       }
4549 
4550       MTCTROps[0] = Chain;
4551       MTCTROps[1] = LoadFuncPtr;
4552       MTCTROps[2] = InFlag;
4553     }
4554 
4555     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4556                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4557     InFlag = Chain.getValue(1);
4558 
4559     NodeTys.clear();
4560     NodeTys.push_back(MVT::Other);
4561     NodeTys.push_back(MVT::Glue);
4562     Ops.push_back(Chain);
4563     CallOpc = PPCISD::BCTRL;
4564     Callee.setNode(nullptr);
4565     // Add use of X11 (holding environment pointer)
4566     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4567       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4568     // Add CTR register as callee so a bctr can be emitted later.
4569     if (isTailCall)
4570       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4571   }
4572 
4573   // If this is a direct call, pass the chain and the callee.
4574   if (Callee.getNode()) {
4575     Ops.push_back(Chain);
4576     Ops.push_back(Callee);
4577   }
4578   // If this is a tail call add stack pointer delta.
4579   if (isTailCall)
4580     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4581 
4582   // Add argument registers to the end of the list so that they are known live
4583   // into the call.
4584   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4585     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4586                                   RegsToPass[i].second.getValueType()));
4587 
4588   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4589   // into the call.
4590   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4591     setUsesTOCBasePtr(DAG);
4592     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4593   }
4594 
4595   return CallOpc;
4596 }
4597 
4598 static
4599 bool isLocalCall(const SDValue &Callee)
4600 {
4601   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4602     return G->getGlobal()->isStrongDefinitionForLinker();
4603   return false;
4604 }
4605 
4606 SDValue PPCTargetLowering::LowerCallResult(
4607     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4608     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4609     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4610 
4611   SmallVector<CCValAssign, 16> RVLocs;
4612   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4613                     *DAG.getContext());
4614   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4615 
4616   // Copy all of the result registers out of their specified physreg.
4617   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4618     CCValAssign &VA = RVLocs[i];
4619     assert(VA.isRegLoc() && "Can only return in registers!");
4620 
4621     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4622                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4623     Chain = Val.getValue(1);
4624     InFlag = Val.getValue(2);
4625 
4626     switch (VA.getLocInfo()) {
4627     default: llvm_unreachable("Unknown loc info!");
4628     case CCValAssign::Full: break;
4629     case CCValAssign::AExt:
4630       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4631       break;
4632     case CCValAssign::ZExt:
4633       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4634                         DAG.getValueType(VA.getValVT()));
4635       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4636       break;
4637     case CCValAssign::SExt:
4638       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4639                         DAG.getValueType(VA.getValVT()));
4640       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4641       break;
4642     }
4643 
4644     InVals.push_back(Val);
4645   }
4646 
4647   return Chain;
4648 }
4649 
4650 SDValue PPCTargetLowering::FinishCall(
4651     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4652     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4653     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4654     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4655     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4656     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4657 
4658   std::vector<EVT> NodeTys;
4659   SmallVector<SDValue, 8> Ops;
4660   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4661                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4662                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4663 
4664   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4665   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4666     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4667 
4668   // When performing tail call optimization the callee pops its arguments off
4669   // the stack. Account for this here so these bytes can be pushed back on in
4670   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4671   int BytesCalleePops =
4672     (CallConv == CallingConv::Fast &&
4673      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4674 
4675   // Add a register mask operand representing the call-preserved registers.
4676   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4677   const uint32_t *Mask =
4678       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4679   assert(Mask && "Missing call preserved mask for calling convention");
4680   Ops.push_back(DAG.getRegisterMask(Mask));
4681 
4682   if (InFlag.getNode())
4683     Ops.push_back(InFlag);
4684 
4685   // Emit tail call.
4686   if (isTailCall) {
4687     assert(((Callee.getOpcode() == ISD::Register &&
4688              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4689             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4690             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4691             isa<ConstantSDNode>(Callee)) &&
4692     "Expecting an global address, external symbol, absolute value or register");
4693 
4694     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4695     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4696   }
4697 
4698   // Add a NOP immediately after the branch instruction when using the 64-bit
4699   // SVR4 ABI. At link time, if caller and callee are in a different module and
4700   // thus have a different TOC, the call will be replaced with a call to a stub
4701   // function which saves the current TOC, loads the TOC of the callee and
4702   // branches to the callee. The NOP will be replaced with a load instruction
4703   // which restores the TOC of the caller from the TOC save slot of the current
4704   // stack frame. If caller and callee belong to the same module (and have the
4705   // same TOC), the NOP will remain unchanged.
4706 
4707   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4708       !isPatchPoint) {
4709     if (CallOpc == PPCISD::BCTRL) {
4710       // This is a call through a function pointer.
4711       // Restore the caller TOC from the save area into R2.
4712       // See PrepareCall() for more information about calls through function
4713       // pointers in the 64-bit SVR4 ABI.
4714       // We are using a target-specific load with r2 hard coded, because the
4715       // result of a target-independent load would never go directly into r2,
4716       // since r2 is a reserved register (which prevents the register allocator
4717       // from allocating it), resulting in an additional register being
4718       // allocated and an unnecessary move instruction being generated.
4719       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4720 
4721       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4722       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4723       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4724       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4725       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4726 
4727       // The address needs to go after the chain input but before the flag (or
4728       // any other variadic arguments).
4729       Ops.insert(std::next(Ops.begin()), AddTOC);
4730     } else if ((CallOpc == PPCISD::CALL) &&
4731                (!isLocalCall(Callee) ||
4732                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4733       // Otherwise insert NOP for non-local calls.
4734       CallOpc = PPCISD::CALL_NOP;
4735   }
4736 
4737   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4738   InFlag = Chain.getValue(1);
4739 
4740   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4741                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4742                              InFlag, dl);
4743   if (!Ins.empty())
4744     InFlag = Chain.getValue(1);
4745 
4746   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4747                          Ins, dl, DAG, InVals);
4748 }
4749 
4750 SDValue
4751 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4752                              SmallVectorImpl<SDValue> &InVals) const {
4753   SelectionDAG &DAG                     = CLI.DAG;
4754   SDLoc &dl                             = CLI.DL;
4755   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4756   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4757   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4758   SDValue Chain                         = CLI.Chain;
4759   SDValue Callee                        = CLI.Callee;
4760   bool &isTailCall                      = CLI.IsTailCall;
4761   CallingConv::ID CallConv              = CLI.CallConv;
4762   bool isVarArg                         = CLI.IsVarArg;
4763   bool isPatchPoint                     = CLI.IsPatchPoint;
4764   ImmutableCallSite *CS                 = CLI.CS;
4765 
4766   if (isTailCall) {
4767     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4768       isTailCall = false;
4769     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4770       isTailCall =
4771         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4772                                                  isVarArg, Outs, Ins, DAG);
4773     else
4774       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4775                                                      Ins, DAG);
4776     if (isTailCall) {
4777       ++NumTailCalls;
4778       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4779         ++NumSiblingCalls;
4780 
4781       assert(isa<GlobalAddressSDNode>(Callee) &&
4782              "Callee should be an llvm::Function object.");
4783       DEBUG(
4784         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4785         const unsigned Width = 80 - strlen("TCO caller: ")
4786                                   - strlen(", callee linkage: 0, 0");
4787         dbgs() << "TCO caller: "
4788                << left_justify(DAG.getMachineFunction().getName(), Width)
4789                << ", callee linkage: "
4790                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4791       );
4792     }
4793   }
4794 
4795   if (!isTailCall && CS && CS->isMustTailCall())
4796     report_fatal_error("failed to perform tail call elimination on a call "
4797                        "site marked musttail");
4798 
4799   // When long calls (i.e. indirect calls) are always used, calls are always
4800   // made via function pointer. If we have a function name, first translate it
4801   // into a pointer.
4802   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4803       !isTailCall)
4804     Callee = LowerGlobalAddress(Callee, DAG);
4805 
4806   if (Subtarget.isSVR4ABI()) {
4807     if (Subtarget.isPPC64())
4808       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4809                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4810                               dl, DAG, InVals, CS);
4811     else
4812       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4813                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4814                               dl, DAG, InVals, CS);
4815   }
4816 
4817   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4818                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4819                           dl, DAG, InVals, CS);
4820 }
4821 
4822 SDValue PPCTargetLowering::LowerCall_32SVR4(
4823     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4824     bool isTailCall, bool isPatchPoint,
4825     const SmallVectorImpl<ISD::OutputArg> &Outs,
4826     const SmallVectorImpl<SDValue> &OutVals,
4827     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4828     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4829     ImmutableCallSite *CS) const {
4830   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4831   // of the 32-bit SVR4 ABI stack frame layout.
4832 
4833   assert((CallConv == CallingConv::C ||
4834           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4835 
4836   unsigned PtrByteSize = 4;
4837 
4838   MachineFunction &MF = DAG.getMachineFunction();
4839 
4840   // Mark this function as potentially containing a function that contains a
4841   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4842   // and restoring the callers stack pointer in this functions epilog. This is
4843   // done because by tail calling the called function might overwrite the value
4844   // in this function's (MF) stack pointer stack slot 0(SP).
4845   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4846       CallConv == CallingConv::Fast)
4847     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4848 
4849   // Count how many bytes are to be pushed on the stack, including the linkage
4850   // area, parameter list area and the part of the local variable space which
4851   // contains copies of aggregates which are passed by value.
4852 
4853   // Assign locations to all of the outgoing arguments.
4854   SmallVector<CCValAssign, 16> ArgLocs;
4855   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4856 
4857   // Reserve space for the linkage area on the stack.
4858   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4859                        PtrByteSize);
4860   if (useSoftFloat())
4861     CCInfo.PreAnalyzeCallOperands(Outs);
4862 
4863   if (isVarArg) {
4864     // Handle fixed and variable vector arguments differently.
4865     // Fixed vector arguments go into registers as long as registers are
4866     // available. Variable vector arguments always go into memory.
4867     unsigned NumArgs = Outs.size();
4868 
4869     for (unsigned i = 0; i != NumArgs; ++i) {
4870       MVT ArgVT = Outs[i].VT;
4871       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4872       bool Result;
4873 
4874       if (Outs[i].IsFixed) {
4875         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4876                                CCInfo);
4877       } else {
4878         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4879                                       ArgFlags, CCInfo);
4880       }
4881 
4882       if (Result) {
4883 #ifndef NDEBUG
4884         errs() << "Call operand #" << i << " has unhandled type "
4885              << EVT(ArgVT).getEVTString() << "\n";
4886 #endif
4887         llvm_unreachable(nullptr);
4888       }
4889     }
4890   } else {
4891     // All arguments are treated the same.
4892     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4893   }
4894   CCInfo.clearWasPPCF128();
4895 
4896   // Assign locations to all of the outgoing aggregate by value arguments.
4897   SmallVector<CCValAssign, 16> ByValArgLocs;
4898   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4899 
4900   // Reserve stack space for the allocations in CCInfo.
4901   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4902 
4903   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4904 
4905   // Size of the linkage area, parameter list area and the part of the local
4906   // space variable where copies of aggregates which are passed by value are
4907   // stored.
4908   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4909 
4910   // Calculate by how many bytes the stack has to be adjusted in case of tail
4911   // call optimization.
4912   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4913 
4914   // Adjust the stack pointer for the new arguments...
4915   // These operations are automatically eliminated by the prolog/epilog pass
4916   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4917                                dl);
4918   SDValue CallSeqStart = Chain;
4919 
4920   // Load the return address and frame pointer so it can be moved somewhere else
4921   // later.
4922   SDValue LROp, FPOp;
4923   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4924 
4925   // Set up a copy of the stack pointer for use loading and storing any
4926   // arguments that may not fit in the registers available for argument
4927   // passing.
4928   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4929 
4930   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4931   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4932   SmallVector<SDValue, 8> MemOpChains;
4933 
4934   bool seenFloatArg = false;
4935   // Walk the register/memloc assignments, inserting copies/loads.
4936   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4937        i != e;
4938        ++i) {
4939     CCValAssign &VA = ArgLocs[i];
4940     SDValue Arg = OutVals[i];
4941     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4942 
4943     if (Flags.isByVal()) {
4944       // Argument is an aggregate which is passed by value, thus we need to
4945       // create a copy of it in the local variable space of the current stack
4946       // frame (which is the stack frame of the caller) and pass the address of
4947       // this copy to the callee.
4948       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4949       CCValAssign &ByValVA = ByValArgLocs[j++];
4950       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4951 
4952       // Memory reserved in the local variable space of the callers stack frame.
4953       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4954 
4955       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4956       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4957                            StackPtr, PtrOff);
4958 
4959       // Create a copy of the argument in the local area of the current
4960       // stack frame.
4961       SDValue MemcpyCall =
4962         CreateCopyOfByValArgument(Arg, PtrOff,
4963                                   CallSeqStart.getNode()->getOperand(0),
4964                                   Flags, DAG, dl);
4965 
4966       // This must go outside the CALLSEQ_START..END.
4967       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4968                            CallSeqStart.getNode()->getOperand(1),
4969                            SDLoc(MemcpyCall));
4970       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4971                              NewCallSeqStart.getNode());
4972       Chain = CallSeqStart = NewCallSeqStart;
4973 
4974       // Pass the address of the aggregate copy on the stack either in a
4975       // physical register or in the parameter list area of the current stack
4976       // frame to the callee.
4977       Arg = PtrOff;
4978     }
4979 
4980     if (VA.isRegLoc()) {
4981       if (Arg.getValueType() == MVT::i1)
4982         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4983 
4984       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4985       // Put argument in a physical register.
4986       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4987     } else {
4988       // Put argument in the parameter list area of the current stack frame.
4989       assert(VA.isMemLoc());
4990       unsigned LocMemOffset = VA.getLocMemOffset();
4991 
4992       if (!isTailCall) {
4993         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4994         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4995                              StackPtr, PtrOff);
4996 
4997         MemOpChains.push_back(
4998             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4999       } else {
5000         // Calculate and remember argument location.
5001         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5002                                  TailCallArguments);
5003       }
5004     }
5005   }
5006 
5007   if (!MemOpChains.empty())
5008     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5009 
5010   // Build a sequence of copy-to-reg nodes chained together with token chain
5011   // and flag operands which copy the outgoing args into the appropriate regs.
5012   SDValue InFlag;
5013   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5014     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5015                              RegsToPass[i].second, InFlag);
5016     InFlag = Chain.getValue(1);
5017   }
5018 
5019   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5020   // registers.
5021   if (isVarArg) {
5022     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5023     SDValue Ops[] = { Chain, InFlag };
5024 
5025     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5026                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5027 
5028     InFlag = Chain.getValue(1);
5029   }
5030 
5031   if (isTailCall)
5032     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5033                     TailCallArguments);
5034 
5035   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5036                     /* unused except on PPC64 ELFv1 */ false, DAG,
5037                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5038                     NumBytes, Ins, InVals, CS);
5039 }
5040 
5041 // Copy an argument into memory, being careful to do this outside the
5042 // call sequence for the call to which the argument belongs.
5043 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5044     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5045     SelectionDAG &DAG, const SDLoc &dl) const {
5046   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5047                         CallSeqStart.getNode()->getOperand(0),
5048                         Flags, DAG, dl);
5049   // The MEMCPY must go outside the CALLSEQ_START..END.
5050   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5051                              CallSeqStart.getNode()->getOperand(1),
5052                              SDLoc(MemcpyCall));
5053   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5054                          NewCallSeqStart.getNode());
5055   return NewCallSeqStart;
5056 }
5057 
5058 SDValue PPCTargetLowering::LowerCall_64SVR4(
5059     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5060     bool isTailCall, bool isPatchPoint,
5061     const SmallVectorImpl<ISD::OutputArg> &Outs,
5062     const SmallVectorImpl<SDValue> &OutVals,
5063     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5064     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5065     ImmutableCallSite *CS) const {
5066 
5067   bool isELFv2ABI = Subtarget.isELFv2ABI();
5068   bool isLittleEndian = Subtarget.isLittleEndian();
5069   unsigned NumOps = Outs.size();
5070   bool hasNest = false;
5071   bool IsSibCall = false;
5072 
5073   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5074   unsigned PtrByteSize = 8;
5075 
5076   MachineFunction &MF = DAG.getMachineFunction();
5077 
5078   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5079     IsSibCall = true;
5080 
5081   // Mark this function as potentially containing a function that contains a
5082   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5083   // and restoring the callers stack pointer in this functions epilog. This is
5084   // done because by tail calling the called function might overwrite the value
5085   // in this function's (MF) stack pointer stack slot 0(SP).
5086   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5087       CallConv == CallingConv::Fast)
5088     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5089 
5090   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5091          "fastcc not supported on varargs functions");
5092 
5093   // Count how many bytes are to be pushed on the stack, including the linkage
5094   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5095   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5096   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5097   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5098   unsigned NumBytes = LinkageSize;
5099   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5100   unsigned &QFPR_idx = FPR_idx;
5101 
5102   static const MCPhysReg GPR[] = {
5103     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5104     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5105   };
5106   static const MCPhysReg VR[] = {
5107     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5108     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5109   };
5110 
5111   const unsigned NumGPRs = array_lengthof(GPR);
5112   const unsigned NumFPRs = 13;
5113   const unsigned NumVRs  = array_lengthof(VR);
5114   const unsigned NumQFPRs = NumFPRs;
5115 
5116   // When using the fast calling convention, we don't provide backing for
5117   // arguments that will be in registers.
5118   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5119 
5120   // Add up all the space actually used.
5121   for (unsigned i = 0; i != NumOps; ++i) {
5122     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5123     EVT ArgVT = Outs[i].VT;
5124     EVT OrigVT = Outs[i].ArgVT;
5125 
5126     if (Flags.isNest())
5127       continue;
5128 
5129     if (CallConv == CallingConv::Fast) {
5130       if (Flags.isByVal())
5131         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5132       else
5133         switch (ArgVT.getSimpleVT().SimpleTy) {
5134         default: llvm_unreachable("Unexpected ValueType for argument!");
5135         case MVT::i1:
5136         case MVT::i32:
5137         case MVT::i64:
5138           if (++NumGPRsUsed <= NumGPRs)
5139             continue;
5140           break;
5141         case MVT::v4i32:
5142         case MVT::v8i16:
5143         case MVT::v16i8:
5144         case MVT::v2f64:
5145         case MVT::v2i64:
5146         case MVT::v1i128:
5147           if (++NumVRsUsed <= NumVRs)
5148             continue;
5149           break;
5150         case MVT::v4f32:
5151           // When using QPX, this is handled like a FP register, otherwise, it
5152           // is an Altivec register.
5153           if (Subtarget.hasQPX()) {
5154             if (++NumFPRsUsed <= NumFPRs)
5155               continue;
5156           } else {
5157             if (++NumVRsUsed <= NumVRs)
5158               continue;
5159           }
5160           break;
5161         case MVT::f32:
5162         case MVT::f64:
5163         case MVT::v4f64: // QPX
5164         case MVT::v4i1:  // QPX
5165           if (++NumFPRsUsed <= NumFPRs)
5166             continue;
5167           break;
5168         }
5169     }
5170 
5171     /* Respect alignment of argument on the stack.  */
5172     unsigned Align =
5173       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5174     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5175 
5176     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5177     if (Flags.isInConsecutiveRegsLast())
5178       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5179   }
5180 
5181   unsigned NumBytesActuallyUsed = NumBytes;
5182 
5183   // The prolog code of the callee may store up to 8 GPR argument registers to
5184   // the stack, allowing va_start to index over them in memory if its varargs.
5185   // Because we cannot tell if this is needed on the caller side, we have to
5186   // conservatively assume that it is needed.  As such, make sure we have at
5187   // least enough stack space for the caller to store the 8 GPRs.
5188   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5189   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5190 
5191   // Tail call needs the stack to be aligned.
5192   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5193       CallConv == CallingConv::Fast)
5194     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5195 
5196   int SPDiff = 0;
5197 
5198   // Calculate by how many bytes the stack has to be adjusted in case of tail
5199   // call optimization.
5200   if (!IsSibCall)
5201     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5202 
5203   // To protect arguments on the stack from being clobbered in a tail call,
5204   // force all the loads to happen before doing any other lowering.
5205   if (isTailCall)
5206     Chain = DAG.getStackArgumentTokenFactor(Chain);
5207 
5208   // Adjust the stack pointer for the new arguments...
5209   // These operations are automatically eliminated by the prolog/epilog pass
5210   if (!IsSibCall)
5211     Chain = DAG.getCALLSEQ_START(Chain,
5212                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5213   SDValue CallSeqStart = Chain;
5214 
5215   // Load the return address and frame pointer so it can be move somewhere else
5216   // later.
5217   SDValue LROp, FPOp;
5218   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5219 
5220   // Set up a copy of the stack pointer for use loading and storing any
5221   // arguments that may not fit in the registers available for argument
5222   // passing.
5223   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5224 
5225   // Figure out which arguments are going to go in registers, and which in
5226   // memory.  Also, if this is a vararg function, floating point operations
5227   // must be stored to our stack, and loaded into integer regs as well, if
5228   // any integer regs are available for argument passing.
5229   unsigned ArgOffset = LinkageSize;
5230 
5231   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5232   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5233 
5234   SmallVector<SDValue, 8> MemOpChains;
5235   for (unsigned i = 0; i != NumOps; ++i) {
5236     SDValue Arg = OutVals[i];
5237     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5238     EVT ArgVT = Outs[i].VT;
5239     EVT OrigVT = Outs[i].ArgVT;
5240 
5241     // PtrOff will be used to store the current argument to the stack if a
5242     // register cannot be found for it.
5243     SDValue PtrOff;
5244 
5245     // We re-align the argument offset for each argument, except when using the
5246     // fast calling convention, when we need to make sure we do that only when
5247     // we'll actually use a stack slot.
5248     auto ComputePtrOff = [&]() {
5249       /* Respect alignment of argument on the stack.  */
5250       unsigned Align =
5251         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5252       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5253 
5254       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5255 
5256       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5257     };
5258 
5259     if (CallConv != CallingConv::Fast) {
5260       ComputePtrOff();
5261 
5262       /* Compute GPR index associated with argument offset.  */
5263       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5264       GPR_idx = std::min(GPR_idx, NumGPRs);
5265     }
5266 
5267     // Promote integers to 64-bit values.
5268     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5269       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5270       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5271       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5272     }
5273 
5274     // FIXME memcpy is used way more than necessary.  Correctness first.
5275     // Note: "by value" is code for passing a structure by value, not
5276     // basic types.
5277     if (Flags.isByVal()) {
5278       // Note: Size includes alignment padding, so
5279       //   struct x { short a; char b; }
5280       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5281       // These are the proper values we need for right-justifying the
5282       // aggregate in a parameter register.
5283       unsigned Size = Flags.getByValSize();
5284 
5285       // An empty aggregate parameter takes up no storage and no
5286       // registers.
5287       if (Size == 0)
5288         continue;
5289 
5290       if (CallConv == CallingConv::Fast)
5291         ComputePtrOff();
5292 
5293       // All aggregates smaller than 8 bytes must be passed right-justified.
5294       if (Size==1 || Size==2 || Size==4) {
5295         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5296         if (GPR_idx != NumGPRs) {
5297           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5298                                         MachinePointerInfo(), VT);
5299           MemOpChains.push_back(Load.getValue(1));
5300           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5301 
5302           ArgOffset += PtrByteSize;
5303           continue;
5304         }
5305       }
5306 
5307       if (GPR_idx == NumGPRs && Size < 8) {
5308         SDValue AddPtr = PtrOff;
5309         if (!isLittleEndian) {
5310           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5311                                           PtrOff.getValueType());
5312           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5313         }
5314         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5315                                                           CallSeqStart,
5316                                                           Flags, DAG, dl);
5317         ArgOffset += PtrByteSize;
5318         continue;
5319       }
5320       // Copy entire object into memory.  There are cases where gcc-generated
5321       // code assumes it is there, even if it could be put entirely into
5322       // registers.  (This is not what the doc says.)
5323 
5324       // FIXME: The above statement is likely due to a misunderstanding of the
5325       // documents.  All arguments must be copied into the parameter area BY
5326       // THE CALLEE in the event that the callee takes the address of any
5327       // formal argument.  That has not yet been implemented.  However, it is
5328       // reasonable to use the stack area as a staging area for the register
5329       // load.
5330 
5331       // Skip this for small aggregates, as we will use the same slot for a
5332       // right-justified copy, below.
5333       if (Size >= 8)
5334         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5335                                                           CallSeqStart,
5336                                                           Flags, DAG, dl);
5337 
5338       // When a register is available, pass a small aggregate right-justified.
5339       if (Size < 8 && GPR_idx != NumGPRs) {
5340         // The easiest way to get this right-justified in a register
5341         // is to copy the structure into the rightmost portion of a
5342         // local variable slot, then load the whole slot into the
5343         // register.
5344         // FIXME: The memcpy seems to produce pretty awful code for
5345         // small aggregates, particularly for packed ones.
5346         // FIXME: It would be preferable to use the slot in the
5347         // parameter save area instead of a new local variable.
5348         SDValue AddPtr = PtrOff;
5349         if (!isLittleEndian) {
5350           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5351           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5352         }
5353         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5354                                                           CallSeqStart,
5355                                                           Flags, DAG, dl);
5356 
5357         // Load the slot into the register.
5358         SDValue Load =
5359             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5360         MemOpChains.push_back(Load.getValue(1));
5361         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5362 
5363         // Done with this argument.
5364         ArgOffset += PtrByteSize;
5365         continue;
5366       }
5367 
5368       // For aggregates larger than PtrByteSize, copy the pieces of the
5369       // object that fit into registers from the parameter save area.
5370       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5371         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5372         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5373         if (GPR_idx != NumGPRs) {
5374           SDValue Load =
5375               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5376           MemOpChains.push_back(Load.getValue(1));
5377           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5378           ArgOffset += PtrByteSize;
5379         } else {
5380           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5381           break;
5382         }
5383       }
5384       continue;
5385     }
5386 
5387     switch (Arg.getSimpleValueType().SimpleTy) {
5388     default: llvm_unreachable("Unexpected ValueType for argument!");
5389     case MVT::i1:
5390     case MVT::i32:
5391     case MVT::i64:
5392       if (Flags.isNest()) {
5393         // The 'nest' parameter, if any, is passed in R11.
5394         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5395         hasNest = true;
5396         break;
5397       }
5398 
5399       // These can be scalar arguments or elements of an integer array type
5400       // passed directly.  Clang may use those instead of "byval" aggregate
5401       // types to avoid forcing arguments to memory unnecessarily.
5402       if (GPR_idx != NumGPRs) {
5403         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5404       } else {
5405         if (CallConv == CallingConv::Fast)
5406           ComputePtrOff();
5407 
5408         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5409                          true, isTailCall, false, MemOpChains,
5410                          TailCallArguments, dl);
5411         if (CallConv == CallingConv::Fast)
5412           ArgOffset += PtrByteSize;
5413       }
5414       if (CallConv != CallingConv::Fast)
5415         ArgOffset += PtrByteSize;
5416       break;
5417     case MVT::f32:
5418     case MVT::f64: {
5419       // These can be scalar arguments or elements of a float array type
5420       // passed directly.  The latter are used to implement ELFv2 homogenous
5421       // float aggregates.
5422 
5423       // Named arguments go into FPRs first, and once they overflow, the
5424       // remaining arguments go into GPRs and then the parameter save area.
5425       // Unnamed arguments for vararg functions always go to GPRs and
5426       // then the parameter save area.  For now, put all arguments to vararg
5427       // routines always in both locations (FPR *and* GPR or stack slot).
5428       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5429       bool NeededLoad = false;
5430 
5431       // First load the argument into the next available FPR.
5432       if (FPR_idx != NumFPRs)
5433         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5434 
5435       // Next, load the argument into GPR or stack slot if needed.
5436       if (!NeedGPROrStack)
5437         ;
5438       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5439         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5440         // once we support fp <-> gpr moves.
5441 
5442         // In the non-vararg case, this can only ever happen in the
5443         // presence of f32 array types, since otherwise we never run
5444         // out of FPRs before running out of GPRs.
5445         SDValue ArgVal;
5446 
5447         // Double values are always passed in a single GPR.
5448         if (Arg.getValueType() != MVT::f32) {
5449           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5450 
5451         // Non-array float values are extended and passed in a GPR.
5452         } else if (!Flags.isInConsecutiveRegs()) {
5453           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5454           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5455 
5456         // If we have an array of floats, we collect every odd element
5457         // together with its predecessor into one GPR.
5458         } else if (ArgOffset % PtrByteSize != 0) {
5459           SDValue Lo, Hi;
5460           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5461           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5462           if (!isLittleEndian)
5463             std::swap(Lo, Hi);
5464           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5465 
5466         // The final element, if even, goes into the first half of a GPR.
5467         } else if (Flags.isInConsecutiveRegsLast()) {
5468           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5469           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5470           if (!isLittleEndian)
5471             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5472                                  DAG.getConstant(32, dl, MVT::i32));
5473 
5474         // Non-final even elements are skipped; they will be handled
5475         // together the with subsequent argument on the next go-around.
5476         } else
5477           ArgVal = SDValue();
5478 
5479         if (ArgVal.getNode())
5480           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5481       } else {
5482         if (CallConv == CallingConv::Fast)
5483           ComputePtrOff();
5484 
5485         // Single-precision floating-point values are mapped to the
5486         // second (rightmost) word of the stack doubleword.
5487         if (Arg.getValueType() == MVT::f32 &&
5488             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5489           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5490           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5491         }
5492 
5493         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5494                          true, isTailCall, false, MemOpChains,
5495                          TailCallArguments, dl);
5496 
5497         NeededLoad = true;
5498       }
5499       // When passing an array of floats, the array occupies consecutive
5500       // space in the argument area; only round up to the next doubleword
5501       // at the end of the array.  Otherwise, each float takes 8 bytes.
5502       if (CallConv != CallingConv::Fast || NeededLoad) {
5503         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5504                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5505         if (Flags.isInConsecutiveRegsLast())
5506           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5507       }
5508       break;
5509     }
5510     case MVT::v4f32:
5511     case MVT::v4i32:
5512     case MVT::v8i16:
5513     case MVT::v16i8:
5514     case MVT::v2f64:
5515     case MVT::v2i64:
5516     case MVT::v1i128:
5517       if (!Subtarget.hasQPX()) {
5518       // These can be scalar arguments or elements of a vector array type
5519       // passed directly.  The latter are used to implement ELFv2 homogenous
5520       // vector aggregates.
5521 
5522       // For a varargs call, named arguments go into VRs or on the stack as
5523       // usual; unnamed arguments always go to the stack or the corresponding
5524       // GPRs when within range.  For now, we always put the value in both
5525       // locations (or even all three).
5526       if (isVarArg) {
5527         // We could elide this store in the case where the object fits
5528         // entirely in R registers.  Maybe later.
5529         SDValue Store =
5530             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5531         MemOpChains.push_back(Store);
5532         if (VR_idx != NumVRs) {
5533           SDValue Load =
5534               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5535           MemOpChains.push_back(Load.getValue(1));
5536           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5537         }
5538         ArgOffset += 16;
5539         for (unsigned i=0; i<16; i+=PtrByteSize) {
5540           if (GPR_idx == NumGPRs)
5541             break;
5542           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5543                                    DAG.getConstant(i, dl, PtrVT));
5544           SDValue Load =
5545               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5546           MemOpChains.push_back(Load.getValue(1));
5547           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5548         }
5549         break;
5550       }
5551 
5552       // Non-varargs Altivec params go into VRs or on the stack.
5553       if (VR_idx != NumVRs) {
5554         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5555       } else {
5556         if (CallConv == CallingConv::Fast)
5557           ComputePtrOff();
5558 
5559         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5560                          true, isTailCall, true, MemOpChains,
5561                          TailCallArguments, dl);
5562         if (CallConv == CallingConv::Fast)
5563           ArgOffset += 16;
5564       }
5565 
5566       if (CallConv != CallingConv::Fast)
5567         ArgOffset += 16;
5568       break;
5569       } // not QPX
5570 
5571       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5572              "Invalid QPX parameter type");
5573 
5574       /* fall through */
5575     case MVT::v4f64:
5576     case MVT::v4i1: {
5577       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5578       if (isVarArg) {
5579         // We could elide this store in the case where the object fits
5580         // entirely in R registers.  Maybe later.
5581         SDValue Store =
5582             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5583         MemOpChains.push_back(Store);
5584         if (QFPR_idx != NumQFPRs) {
5585           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5586                                      PtrOff, MachinePointerInfo());
5587           MemOpChains.push_back(Load.getValue(1));
5588           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5589         }
5590         ArgOffset += (IsF32 ? 16 : 32);
5591         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5592           if (GPR_idx == NumGPRs)
5593             break;
5594           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5595                                    DAG.getConstant(i, dl, PtrVT));
5596           SDValue Load =
5597               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5598           MemOpChains.push_back(Load.getValue(1));
5599           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5600         }
5601         break;
5602       }
5603 
5604       // Non-varargs QPX params go into registers or on the stack.
5605       if (QFPR_idx != NumQFPRs) {
5606         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5607       } else {
5608         if (CallConv == CallingConv::Fast)
5609           ComputePtrOff();
5610 
5611         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5612                          true, isTailCall, true, MemOpChains,
5613                          TailCallArguments, dl);
5614         if (CallConv == CallingConv::Fast)
5615           ArgOffset += (IsF32 ? 16 : 32);
5616       }
5617 
5618       if (CallConv != CallingConv::Fast)
5619         ArgOffset += (IsF32 ? 16 : 32);
5620       break;
5621       }
5622     }
5623   }
5624 
5625   assert(NumBytesActuallyUsed == ArgOffset);
5626   (void)NumBytesActuallyUsed;
5627 
5628   if (!MemOpChains.empty())
5629     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5630 
5631   // Check if this is an indirect call (MTCTR/BCTRL).
5632   // See PrepareCall() for more information about calls through function
5633   // pointers in the 64-bit SVR4 ABI.
5634   if (!isTailCall && !isPatchPoint &&
5635       !isFunctionGlobalAddress(Callee) &&
5636       !isa<ExternalSymbolSDNode>(Callee)) {
5637     // Load r2 into a virtual register and store it to the TOC save area.
5638     setUsesTOCBasePtr(DAG);
5639     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5640     // TOC save area offset.
5641     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5642     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5643     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5644     Chain = DAG.getStore(
5645         Val.getValue(1), dl, Val, AddPtr,
5646         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5647     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5648     // This does not mean the MTCTR instruction must use R12; it's easier
5649     // to model this as an extra parameter, so do that.
5650     if (isELFv2ABI && !isPatchPoint)
5651       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5652   }
5653 
5654   // Build a sequence of copy-to-reg nodes chained together with token chain
5655   // and flag operands which copy the outgoing args into the appropriate regs.
5656   SDValue InFlag;
5657   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5658     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5659                              RegsToPass[i].second, InFlag);
5660     InFlag = Chain.getValue(1);
5661   }
5662 
5663   if (isTailCall && !IsSibCall)
5664     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5665                     TailCallArguments);
5666 
5667   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5668                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5669                     SPDiff, NumBytes, Ins, InVals, CS);
5670 }
5671 
5672 SDValue PPCTargetLowering::LowerCall_Darwin(
5673     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5674     bool isTailCall, bool isPatchPoint,
5675     const SmallVectorImpl<ISD::OutputArg> &Outs,
5676     const SmallVectorImpl<SDValue> &OutVals,
5677     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5678     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5679     ImmutableCallSite *CS) const {
5680 
5681   unsigned NumOps = Outs.size();
5682 
5683   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5684   bool isPPC64 = PtrVT == MVT::i64;
5685   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5686 
5687   MachineFunction &MF = DAG.getMachineFunction();
5688 
5689   // Mark this function as potentially containing a function that contains a
5690   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5691   // and restoring the callers stack pointer in this functions epilog. This is
5692   // done because by tail calling the called function might overwrite the value
5693   // in this function's (MF) stack pointer stack slot 0(SP).
5694   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5695       CallConv == CallingConv::Fast)
5696     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5697 
5698   // Count how many bytes are to be pushed on the stack, including the linkage
5699   // area, and parameter passing area.  We start with 24/48 bytes, which is
5700   // prereserved space for [SP][CR][LR][3 x unused].
5701   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5702   unsigned NumBytes = LinkageSize;
5703 
5704   // Add up all the space actually used.
5705   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5706   // they all go in registers, but we must reserve stack space for them for
5707   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5708   // assigned stack space in order, with padding so Altivec parameters are
5709   // 16-byte aligned.
5710   unsigned nAltivecParamsAtEnd = 0;
5711   for (unsigned i = 0; i != NumOps; ++i) {
5712     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5713     EVT ArgVT = Outs[i].VT;
5714     // Varargs Altivec parameters are padded to a 16 byte boundary.
5715     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5716         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5717         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5718       if (!isVarArg && !isPPC64) {
5719         // Non-varargs Altivec parameters go after all the non-Altivec
5720         // parameters; handle those later so we know how much padding we need.
5721         nAltivecParamsAtEnd++;
5722         continue;
5723       }
5724       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5725       NumBytes = ((NumBytes+15)/16)*16;
5726     }
5727     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5728   }
5729 
5730   // Allow for Altivec parameters at the end, if needed.
5731   if (nAltivecParamsAtEnd) {
5732     NumBytes = ((NumBytes+15)/16)*16;
5733     NumBytes += 16*nAltivecParamsAtEnd;
5734   }
5735 
5736   // The prolog code of the callee may store up to 8 GPR argument registers to
5737   // the stack, allowing va_start to index over them in memory if its varargs.
5738   // Because we cannot tell if this is needed on the caller side, we have to
5739   // conservatively assume that it is needed.  As such, make sure we have at
5740   // least enough stack space for the caller to store the 8 GPRs.
5741   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5742 
5743   // Tail call needs the stack to be aligned.
5744   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5745       CallConv == CallingConv::Fast)
5746     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5747 
5748   // Calculate by how many bytes the stack has to be adjusted in case of tail
5749   // call optimization.
5750   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5751 
5752   // To protect arguments on the stack from being clobbered in a tail call,
5753   // force all the loads to happen before doing any other lowering.
5754   if (isTailCall)
5755     Chain = DAG.getStackArgumentTokenFactor(Chain);
5756 
5757   // Adjust the stack pointer for the new arguments...
5758   // These operations are automatically eliminated by the prolog/epilog pass
5759   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5760                                dl);
5761   SDValue CallSeqStart = Chain;
5762 
5763   // Load the return address and frame pointer so it can be move somewhere else
5764   // later.
5765   SDValue LROp, FPOp;
5766   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5767 
5768   // Set up a copy of the stack pointer for use loading and storing any
5769   // arguments that may not fit in the registers available for argument
5770   // passing.
5771   SDValue StackPtr;
5772   if (isPPC64)
5773     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5774   else
5775     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5776 
5777   // Figure out which arguments are going to go in registers, and which in
5778   // memory.  Also, if this is a vararg function, floating point operations
5779   // must be stored to our stack, and loaded into integer regs as well, if
5780   // any integer regs are available for argument passing.
5781   unsigned ArgOffset = LinkageSize;
5782   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5783 
5784   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5785     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5786     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5787   };
5788   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5789     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5790     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5791   };
5792   static const MCPhysReg VR[] = {
5793     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5794     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5795   };
5796   const unsigned NumGPRs = array_lengthof(GPR_32);
5797   const unsigned NumFPRs = 13;
5798   const unsigned NumVRs  = array_lengthof(VR);
5799 
5800   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5801 
5802   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5803   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5804 
5805   SmallVector<SDValue, 8> MemOpChains;
5806   for (unsigned i = 0; i != NumOps; ++i) {
5807     SDValue Arg = OutVals[i];
5808     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5809 
5810     // PtrOff will be used to store the current argument to the stack if a
5811     // register cannot be found for it.
5812     SDValue PtrOff;
5813 
5814     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5815 
5816     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5817 
5818     // On PPC64, promote integers to 64-bit values.
5819     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5820       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5821       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5822       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5823     }
5824 
5825     // FIXME memcpy is used way more than necessary.  Correctness first.
5826     // Note: "by value" is code for passing a structure by value, not
5827     // basic types.
5828     if (Flags.isByVal()) {
5829       unsigned Size = Flags.getByValSize();
5830       // Very small objects are passed right-justified.  Everything else is
5831       // passed left-justified.
5832       if (Size==1 || Size==2) {
5833         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5834         if (GPR_idx != NumGPRs) {
5835           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5836                                         MachinePointerInfo(), VT);
5837           MemOpChains.push_back(Load.getValue(1));
5838           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5839 
5840           ArgOffset += PtrByteSize;
5841         } else {
5842           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5843                                           PtrOff.getValueType());
5844           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5845           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5846                                                             CallSeqStart,
5847                                                             Flags, DAG, dl);
5848           ArgOffset += PtrByteSize;
5849         }
5850         continue;
5851       }
5852       // Copy entire object into memory.  There are cases where gcc-generated
5853       // code assumes it is there, even if it could be put entirely into
5854       // registers.  (This is not what the doc says.)
5855       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5856                                                         CallSeqStart,
5857                                                         Flags, DAG, dl);
5858 
5859       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5860       // copy the pieces of the object that fit into registers from the
5861       // parameter save area.
5862       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5863         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5864         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5865         if (GPR_idx != NumGPRs) {
5866           SDValue Load =
5867               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5868           MemOpChains.push_back(Load.getValue(1));
5869           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5870           ArgOffset += PtrByteSize;
5871         } else {
5872           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5873           break;
5874         }
5875       }
5876       continue;
5877     }
5878 
5879     switch (Arg.getSimpleValueType().SimpleTy) {
5880     default: llvm_unreachable("Unexpected ValueType for argument!");
5881     case MVT::i1:
5882     case MVT::i32:
5883     case MVT::i64:
5884       if (GPR_idx != NumGPRs) {
5885         if (Arg.getValueType() == MVT::i1)
5886           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5887 
5888         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5889       } else {
5890         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5891                          isPPC64, isTailCall, false, MemOpChains,
5892                          TailCallArguments, dl);
5893       }
5894       ArgOffset += PtrByteSize;
5895       break;
5896     case MVT::f32:
5897     case MVT::f64:
5898       if (FPR_idx != NumFPRs) {
5899         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5900 
5901         if (isVarArg) {
5902           SDValue Store =
5903               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5904           MemOpChains.push_back(Store);
5905 
5906           // Float varargs are always shadowed in available integer registers
5907           if (GPR_idx != NumGPRs) {
5908             SDValue Load =
5909                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5910             MemOpChains.push_back(Load.getValue(1));
5911             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5912           }
5913           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5914             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5915             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5916             SDValue Load =
5917                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5918             MemOpChains.push_back(Load.getValue(1));
5919             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5920           }
5921         } else {
5922           // If we have any FPRs remaining, we may also have GPRs remaining.
5923           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5924           // GPRs.
5925           if (GPR_idx != NumGPRs)
5926             ++GPR_idx;
5927           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5928               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5929             ++GPR_idx;
5930         }
5931       } else
5932         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5933                          isPPC64, isTailCall, false, MemOpChains,
5934                          TailCallArguments, dl);
5935       if (isPPC64)
5936         ArgOffset += 8;
5937       else
5938         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5939       break;
5940     case MVT::v4f32:
5941     case MVT::v4i32:
5942     case MVT::v8i16:
5943     case MVT::v16i8:
5944       if (isVarArg) {
5945         // These go aligned on the stack, or in the corresponding R registers
5946         // when within range.  The Darwin PPC ABI doc claims they also go in
5947         // V registers; in fact gcc does this only for arguments that are
5948         // prototyped, not for those that match the ...  We do it for all
5949         // arguments, seems to work.
5950         while (ArgOffset % 16 !=0) {
5951           ArgOffset += PtrByteSize;
5952           if (GPR_idx != NumGPRs)
5953             GPR_idx++;
5954         }
5955         // We could elide this store in the case where the object fits
5956         // entirely in R registers.  Maybe later.
5957         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5958                              DAG.getConstant(ArgOffset, dl, PtrVT));
5959         SDValue Store =
5960             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5961         MemOpChains.push_back(Store);
5962         if (VR_idx != NumVRs) {
5963           SDValue Load =
5964               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5965           MemOpChains.push_back(Load.getValue(1));
5966           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5967         }
5968         ArgOffset += 16;
5969         for (unsigned i=0; i<16; i+=PtrByteSize) {
5970           if (GPR_idx == NumGPRs)
5971             break;
5972           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5973                                    DAG.getConstant(i, dl, PtrVT));
5974           SDValue Load =
5975               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5976           MemOpChains.push_back(Load.getValue(1));
5977           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5978         }
5979         break;
5980       }
5981 
5982       // Non-varargs Altivec params generally go in registers, but have
5983       // stack space allocated at the end.
5984       if (VR_idx != NumVRs) {
5985         // Doesn't have GPR space allocated.
5986         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5987       } else if (nAltivecParamsAtEnd==0) {
5988         // We are emitting Altivec params in order.
5989         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5990                          isPPC64, isTailCall, true, MemOpChains,
5991                          TailCallArguments, dl);
5992         ArgOffset += 16;
5993       }
5994       break;
5995     }
5996   }
5997   // If all Altivec parameters fit in registers, as they usually do,
5998   // they get stack space following the non-Altivec parameters.  We
5999   // don't track this here because nobody below needs it.
6000   // If there are more Altivec parameters than fit in registers emit
6001   // the stores here.
6002   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6003     unsigned j = 0;
6004     // Offset is aligned; skip 1st 12 params which go in V registers.
6005     ArgOffset = ((ArgOffset+15)/16)*16;
6006     ArgOffset += 12*16;
6007     for (unsigned i = 0; i != NumOps; ++i) {
6008       SDValue Arg = OutVals[i];
6009       EVT ArgType = Outs[i].VT;
6010       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6011           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6012         if (++j > NumVRs) {
6013           SDValue PtrOff;
6014           // We are emitting Altivec params in order.
6015           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6016                            isPPC64, isTailCall, true, MemOpChains,
6017                            TailCallArguments, dl);
6018           ArgOffset += 16;
6019         }
6020       }
6021     }
6022   }
6023 
6024   if (!MemOpChains.empty())
6025     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6026 
6027   // On Darwin, R12 must contain the address of an indirect callee.  This does
6028   // not mean the MTCTR instruction must use R12; it's easier to model this as
6029   // an extra parameter, so do that.
6030   if (!isTailCall &&
6031       !isFunctionGlobalAddress(Callee) &&
6032       !isa<ExternalSymbolSDNode>(Callee) &&
6033       !isBLACompatibleAddress(Callee, DAG))
6034     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6035                                                    PPC::R12), Callee));
6036 
6037   // Build a sequence of copy-to-reg nodes chained together with token chain
6038   // and flag operands which copy the outgoing args into the appropriate regs.
6039   SDValue InFlag;
6040   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6041     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6042                              RegsToPass[i].second, InFlag);
6043     InFlag = Chain.getValue(1);
6044   }
6045 
6046   if (isTailCall)
6047     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6048                     TailCallArguments);
6049 
6050   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6051                     /* unused except on PPC64 ELFv1 */ false, DAG,
6052                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6053                     NumBytes, Ins, InVals, CS);
6054 }
6055 
6056 bool
6057 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6058                                   MachineFunction &MF, bool isVarArg,
6059                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6060                                   LLVMContext &Context) const {
6061   SmallVector<CCValAssign, 16> RVLocs;
6062   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6063   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6064 }
6065 
6066 SDValue
6067 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6068                                bool isVarArg,
6069                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6070                                const SmallVectorImpl<SDValue> &OutVals,
6071                                const SDLoc &dl, SelectionDAG &DAG) const {
6072 
6073   SmallVector<CCValAssign, 16> RVLocs;
6074   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6075                  *DAG.getContext());
6076   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6077 
6078   SDValue Flag;
6079   SmallVector<SDValue, 4> RetOps(1, Chain);
6080 
6081   // Copy the result values into the output registers.
6082   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6083     CCValAssign &VA = RVLocs[i];
6084     assert(VA.isRegLoc() && "Can only return in registers!");
6085 
6086     SDValue Arg = OutVals[i];
6087 
6088     switch (VA.getLocInfo()) {
6089     default: llvm_unreachable("Unknown loc info!");
6090     case CCValAssign::Full: break;
6091     case CCValAssign::AExt:
6092       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6093       break;
6094     case CCValAssign::ZExt:
6095       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6096       break;
6097     case CCValAssign::SExt:
6098       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6099       break;
6100     }
6101 
6102     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6103     Flag = Chain.getValue(1);
6104     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6105   }
6106 
6107   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6108   const MCPhysReg *I =
6109     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6110   if (I) {
6111     for (; *I; ++I) {
6112 
6113       if (PPC::G8RCRegClass.contains(*I))
6114         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6115       else if (PPC::F8RCRegClass.contains(*I))
6116         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6117       else if (PPC::CRRCRegClass.contains(*I))
6118         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6119       else if (PPC::VRRCRegClass.contains(*I))
6120         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6121       else
6122         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6123     }
6124   }
6125 
6126   RetOps[0] = Chain;  // Update chain.
6127 
6128   // Add the flag if we have it.
6129   if (Flag.getNode())
6130     RetOps.push_back(Flag);
6131 
6132   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6133 }
6134 
6135 SDValue
6136 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6137                                                 SelectionDAG &DAG) const {
6138   SDLoc dl(Op);
6139 
6140   // Get the corect type for integers.
6141   EVT IntVT = Op.getValueType();
6142 
6143   // Get the inputs.
6144   SDValue Chain = Op.getOperand(0);
6145   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6146   // Build a DYNAREAOFFSET node.
6147   SDValue Ops[2] = {Chain, FPSIdx};
6148   SDVTList VTs = DAG.getVTList(IntVT);
6149   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6150 }
6151 
6152 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6153                                              SelectionDAG &DAG) const {
6154   // When we pop the dynamic allocation we need to restore the SP link.
6155   SDLoc dl(Op);
6156 
6157   // Get the corect type for pointers.
6158   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6159 
6160   // Construct the stack pointer operand.
6161   bool isPPC64 = Subtarget.isPPC64();
6162   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6163   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6164 
6165   // Get the operands for the STACKRESTORE.
6166   SDValue Chain = Op.getOperand(0);
6167   SDValue SaveSP = Op.getOperand(1);
6168 
6169   // Load the old link SP.
6170   SDValue LoadLinkSP =
6171       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6172 
6173   // Restore the stack pointer.
6174   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6175 
6176   // Store the old link SP.
6177   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6178 }
6179 
6180 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6181   MachineFunction &MF = DAG.getMachineFunction();
6182   bool isPPC64 = Subtarget.isPPC64();
6183   EVT PtrVT = getPointerTy(MF.getDataLayout());
6184 
6185   // Get current frame pointer save index.  The users of this index will be
6186   // primarily DYNALLOC instructions.
6187   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6188   int RASI = FI->getReturnAddrSaveIndex();
6189 
6190   // If the frame pointer save index hasn't been defined yet.
6191   if (!RASI) {
6192     // Find out what the fix offset of the frame pointer save area.
6193     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6194     // Allocate the frame index for frame pointer save area.
6195     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6196     // Save the result.
6197     FI->setReturnAddrSaveIndex(RASI);
6198   }
6199   return DAG.getFrameIndex(RASI, PtrVT);
6200 }
6201 
6202 SDValue
6203 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6204   MachineFunction &MF = DAG.getMachineFunction();
6205   bool isPPC64 = Subtarget.isPPC64();
6206   EVT PtrVT = getPointerTy(MF.getDataLayout());
6207 
6208   // Get current frame pointer save index.  The users of this index will be
6209   // primarily DYNALLOC instructions.
6210   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6211   int FPSI = FI->getFramePointerSaveIndex();
6212 
6213   // If the frame pointer save index hasn't been defined yet.
6214   if (!FPSI) {
6215     // Find out what the fix offset of the frame pointer save area.
6216     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6217     // Allocate the frame index for frame pointer save area.
6218     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6219     // Save the result.
6220     FI->setFramePointerSaveIndex(FPSI);
6221   }
6222   return DAG.getFrameIndex(FPSI, PtrVT);
6223 }
6224 
6225 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6226                                                    SelectionDAG &DAG) const {
6227   // Get the inputs.
6228   SDValue Chain = Op.getOperand(0);
6229   SDValue Size  = Op.getOperand(1);
6230   SDLoc dl(Op);
6231 
6232   // Get the corect type for pointers.
6233   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6234   // Negate the size.
6235   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6236                                 DAG.getConstant(0, dl, PtrVT), Size);
6237   // Construct a node for the frame pointer save index.
6238   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6239   // Build a DYNALLOC node.
6240   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6241   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6242   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6243 }
6244 
6245 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6246                                                      SelectionDAG &DAG) const {
6247   MachineFunction &MF = DAG.getMachineFunction();
6248 
6249   bool isPPC64 = Subtarget.isPPC64();
6250   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6251 
6252   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6253   return DAG.getFrameIndex(FI, PtrVT);
6254 }
6255 
6256 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6257                                                SelectionDAG &DAG) const {
6258   SDLoc DL(Op);
6259   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6260                      DAG.getVTList(MVT::i32, MVT::Other),
6261                      Op.getOperand(0), Op.getOperand(1));
6262 }
6263 
6264 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6265                                                 SelectionDAG &DAG) const {
6266   SDLoc DL(Op);
6267   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6268                      Op.getOperand(0), Op.getOperand(1));
6269 }
6270 
6271 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6272   if (Op.getValueType().isVector())
6273     return LowerVectorLoad(Op, DAG);
6274 
6275   assert(Op.getValueType() == MVT::i1 &&
6276          "Custom lowering only for i1 loads");
6277 
6278   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6279 
6280   SDLoc dl(Op);
6281   LoadSDNode *LD = cast<LoadSDNode>(Op);
6282 
6283   SDValue Chain = LD->getChain();
6284   SDValue BasePtr = LD->getBasePtr();
6285   MachineMemOperand *MMO = LD->getMemOperand();
6286 
6287   SDValue NewLD =
6288       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6289                      BasePtr, MVT::i8, MMO);
6290   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6291 
6292   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6293   return DAG.getMergeValues(Ops, dl);
6294 }
6295 
6296 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6297   if (Op.getOperand(1).getValueType().isVector())
6298     return LowerVectorStore(Op, DAG);
6299 
6300   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6301          "Custom lowering only for i1 stores");
6302 
6303   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6304 
6305   SDLoc dl(Op);
6306   StoreSDNode *ST = cast<StoreSDNode>(Op);
6307 
6308   SDValue Chain = ST->getChain();
6309   SDValue BasePtr = ST->getBasePtr();
6310   SDValue Value = ST->getValue();
6311   MachineMemOperand *MMO = ST->getMemOperand();
6312 
6313   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6314                       Value);
6315   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6316 }
6317 
6318 // FIXME: Remove this once the ANDI glue bug is fixed:
6319 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6320   assert(Op.getValueType() == MVT::i1 &&
6321          "Custom lowering only for i1 results");
6322 
6323   SDLoc DL(Op);
6324   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6325                      Op.getOperand(0));
6326 }
6327 
6328 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6329 /// possible.
6330 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6331   // Not FP? Not a fsel.
6332   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6333       !Op.getOperand(2).getValueType().isFloatingPoint())
6334     return Op;
6335 
6336   // We might be able to do better than this under some circumstances, but in
6337   // general, fsel-based lowering of select is a finite-math-only optimization.
6338   // For more information, see section F.3 of the 2.06 ISA specification.
6339   if (!DAG.getTarget().Options.NoInfsFPMath ||
6340       !DAG.getTarget().Options.NoNaNsFPMath)
6341     return Op;
6342   // TODO: Propagate flags from the select rather than global settings.
6343   SDNodeFlags Flags;
6344   Flags.setNoInfs(true);
6345   Flags.setNoNaNs(true);
6346 
6347   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6348 
6349   EVT ResVT = Op.getValueType();
6350   EVT CmpVT = Op.getOperand(0).getValueType();
6351   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6352   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6353   SDLoc dl(Op);
6354 
6355   // If the RHS of the comparison is a 0.0, we don't need to do the
6356   // subtraction at all.
6357   SDValue Sel1;
6358   if (isFloatingPointZero(RHS))
6359     switch (CC) {
6360     default: break;       // SETUO etc aren't handled by fsel.
6361     case ISD::SETNE:
6362       std::swap(TV, FV);
6363     case ISD::SETEQ:
6364       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6365         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6366       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6367       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6368         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6369       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6370                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6371     case ISD::SETULT:
6372     case ISD::SETLT:
6373       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6374     case ISD::SETOGE:
6375     case ISD::SETGE:
6376       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6377         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6378       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6379     case ISD::SETUGT:
6380     case ISD::SETGT:
6381       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6382     case ISD::SETOLE:
6383     case ISD::SETLE:
6384       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6385         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6386       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6387                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6388     }
6389 
6390   SDValue Cmp;
6391   switch (CC) {
6392   default: break;       // SETUO etc aren't handled by fsel.
6393   case ISD::SETNE:
6394     std::swap(TV, FV);
6395   case ISD::SETEQ:
6396     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6397     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6398       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6399     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6400     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6401       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6402     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6403                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6404   case ISD::SETULT:
6405   case ISD::SETLT:
6406     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6407     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6408       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6409     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6410   case ISD::SETOGE:
6411   case ISD::SETGE:
6412     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6413     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6414       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6415     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6416   case ISD::SETUGT:
6417   case ISD::SETGT:
6418     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6419     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6420       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6421     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6422   case ISD::SETOLE:
6423   case ISD::SETLE:
6424     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6425     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6426       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6427     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6428   }
6429   return Op;
6430 }
6431 
6432 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6433                                                SelectionDAG &DAG,
6434                                                const SDLoc &dl) const {
6435   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6436   SDValue Src = Op.getOperand(0);
6437   if (Src.getValueType() == MVT::f32)
6438     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6439 
6440   SDValue Tmp;
6441   switch (Op.getSimpleValueType().SimpleTy) {
6442   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6443   case MVT::i32:
6444     Tmp = DAG.getNode(
6445         Op.getOpcode() == ISD::FP_TO_SINT
6446             ? PPCISD::FCTIWZ
6447             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6448         dl, MVT::f64, Src);
6449     break;
6450   case MVT::i64:
6451     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6452            "i64 FP_TO_UINT is supported only with FPCVT");
6453     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6454                                                         PPCISD::FCTIDUZ,
6455                       dl, MVT::f64, Src);
6456     break;
6457   }
6458 
6459   // Convert the FP value to an int value through memory.
6460   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6461     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6462   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6463   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6464   MachinePointerInfo MPI =
6465       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6466 
6467   // Emit a store to the stack slot.
6468   SDValue Chain;
6469   if (i32Stack) {
6470     MachineFunction &MF = DAG.getMachineFunction();
6471     MachineMemOperand *MMO =
6472       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6473     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6474     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6475               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6476   } else
6477     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6478 
6479   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6480   // add in a bias on big endian.
6481   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6482     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6483                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6484     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6485   }
6486 
6487   RLI.Chain = Chain;
6488   RLI.Ptr = FIPtr;
6489   RLI.MPI = MPI;
6490 }
6491 
6492 /// \brief Custom lowers floating point to integer conversions to use
6493 /// the direct move instructions available in ISA 2.07 to avoid the
6494 /// need for load/store combinations.
6495 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6496                                                     SelectionDAG &DAG,
6497                                                     const SDLoc &dl) const {
6498   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6499   SDValue Src = Op.getOperand(0);
6500 
6501   if (Src.getValueType() == MVT::f32)
6502     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6503 
6504   SDValue Tmp;
6505   switch (Op.getSimpleValueType().SimpleTy) {
6506   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6507   case MVT::i32:
6508     Tmp = DAG.getNode(
6509         Op.getOpcode() == ISD::FP_TO_SINT
6510             ? PPCISD::FCTIWZ
6511             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6512         dl, MVT::f64, Src);
6513     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6514     break;
6515   case MVT::i64:
6516     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6517            "i64 FP_TO_UINT is supported only with FPCVT");
6518     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6519                                                         PPCISD::FCTIDUZ,
6520                       dl, MVT::f64, Src);
6521     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6522     break;
6523   }
6524   return Tmp;
6525 }
6526 
6527 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6528                                           const SDLoc &dl) const {
6529   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6530     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6531 
6532   ReuseLoadInfo RLI;
6533   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6534 
6535   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6536                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6537 }
6538 
6539 // We're trying to insert a regular store, S, and then a load, L. If the
6540 // incoming value, O, is a load, we might just be able to have our load use the
6541 // address used by O. However, we don't know if anything else will store to
6542 // that address before we can load from it. To prevent this situation, we need
6543 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6544 // the same chain operand as O, we create a token factor from the chain results
6545 // of O and L, and we replace all uses of O's chain result with that token
6546 // factor (see spliceIntoChain below for this last part).
6547 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6548                                             ReuseLoadInfo &RLI,
6549                                             SelectionDAG &DAG,
6550                                             ISD::LoadExtType ET) const {
6551   SDLoc dl(Op);
6552   if (ET == ISD::NON_EXTLOAD &&
6553       (Op.getOpcode() == ISD::FP_TO_UINT ||
6554        Op.getOpcode() == ISD::FP_TO_SINT) &&
6555       isOperationLegalOrCustom(Op.getOpcode(),
6556                                Op.getOperand(0).getValueType())) {
6557 
6558     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6559     return true;
6560   }
6561 
6562   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6563   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6564       LD->isNonTemporal())
6565     return false;
6566   if (LD->getMemoryVT() != MemVT)
6567     return false;
6568 
6569   RLI.Ptr = LD->getBasePtr();
6570   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6571     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6572            "Non-pre-inc AM on PPC?");
6573     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6574                           LD->getOffset());
6575   }
6576 
6577   RLI.Chain = LD->getChain();
6578   RLI.MPI = LD->getPointerInfo();
6579   RLI.IsDereferenceable = LD->isDereferenceable();
6580   RLI.IsInvariant = LD->isInvariant();
6581   RLI.Alignment = LD->getAlignment();
6582   RLI.AAInfo = LD->getAAInfo();
6583   RLI.Ranges = LD->getRanges();
6584 
6585   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6586   return true;
6587 }
6588 
6589 // Given the head of the old chain, ResChain, insert a token factor containing
6590 // it and NewResChain, and make users of ResChain now be users of that token
6591 // factor.
6592 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6593                                         SDValue NewResChain,
6594                                         SelectionDAG &DAG) const {
6595   if (!ResChain)
6596     return;
6597 
6598   SDLoc dl(NewResChain);
6599 
6600   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6601                            NewResChain, DAG.getUNDEF(MVT::Other));
6602   assert(TF.getNode() != NewResChain.getNode() &&
6603          "A new TF really is required here");
6604 
6605   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6606   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6607 }
6608 
6609 /// \brief Analyze profitability of direct move
6610 /// prefer float load to int load plus direct move
6611 /// when there is no integer use of int load
6612 static bool directMoveIsProfitable(const SDValue &Op) {
6613   SDNode *Origin = Op.getOperand(0).getNode();
6614   if (Origin->getOpcode() != ISD::LOAD)
6615     return true;
6616 
6617   for (SDNode::use_iterator UI = Origin->use_begin(),
6618                             UE = Origin->use_end();
6619        UI != UE; ++UI) {
6620 
6621     // Only look at the users of the loaded value.
6622     if (UI.getUse().get().getResNo() != 0)
6623       continue;
6624 
6625     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6626         UI->getOpcode() != ISD::UINT_TO_FP)
6627       return true;
6628   }
6629 
6630   return false;
6631 }
6632 
6633 /// \brief Custom lowers integer to floating point conversions to use
6634 /// the direct move instructions available in ISA 2.07 to avoid the
6635 /// need for load/store combinations.
6636 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6637                                                     SelectionDAG &DAG,
6638                                                     const SDLoc &dl) const {
6639   assert((Op.getValueType() == MVT::f32 ||
6640           Op.getValueType() == MVT::f64) &&
6641          "Invalid floating point type as target of conversion");
6642   assert(Subtarget.hasFPCVT() &&
6643          "Int to FP conversions with direct moves require FPCVT");
6644   SDValue FP;
6645   SDValue Src = Op.getOperand(0);
6646   bool SinglePrec = Op.getValueType() == MVT::f32;
6647   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6648   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6649   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6650                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6651 
6652   if (WordInt) {
6653     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6654                      dl, MVT::f64, Src);
6655     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6656   }
6657   else {
6658     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6659     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6660   }
6661 
6662   return FP;
6663 }
6664 
6665 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6666                                           SelectionDAG &DAG) const {
6667   SDLoc dl(Op);
6668 
6669   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6670     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6671       return SDValue();
6672 
6673     SDValue Value = Op.getOperand(0);
6674     // The values are now known to be -1 (false) or 1 (true). To convert this
6675     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6676     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6677     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6678 
6679     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6680 
6681     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6682 
6683     if (Op.getValueType() != MVT::v4f64)
6684       Value = DAG.getNode(ISD::FP_ROUND, dl,
6685                           Op.getValueType(), Value,
6686                           DAG.getIntPtrConstant(1, dl));
6687     return Value;
6688   }
6689 
6690   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6691   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6692     return SDValue();
6693 
6694   if (Op.getOperand(0).getValueType() == MVT::i1)
6695     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6696                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6697                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6698 
6699   // If we have direct moves, we can do all the conversion, skip the store/load
6700   // however, without FPCVT we can't do most conversions.
6701   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6702       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6703     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6704 
6705   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6706          "UINT_TO_FP is supported only with FPCVT");
6707 
6708   // If we have FCFIDS, then use it when converting to single-precision.
6709   // Otherwise, convert to double-precision and then round.
6710   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6711                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6712                                                             : PPCISD::FCFIDS)
6713                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6714                                                             : PPCISD::FCFID);
6715   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6716                   ? MVT::f32
6717                   : MVT::f64;
6718 
6719   if (Op.getOperand(0).getValueType() == MVT::i64) {
6720     SDValue SINT = Op.getOperand(0);
6721     // When converting to single-precision, we actually need to convert
6722     // to double-precision first and then round to single-precision.
6723     // To avoid double-rounding effects during that operation, we have
6724     // to prepare the input operand.  Bits that might be truncated when
6725     // converting to double-precision are replaced by a bit that won't
6726     // be lost at this stage, but is below the single-precision rounding
6727     // position.
6728     //
6729     // However, if -enable-unsafe-fp-math is in effect, accept double
6730     // rounding to avoid the extra overhead.
6731     if (Op.getValueType() == MVT::f32 &&
6732         !Subtarget.hasFPCVT() &&
6733         !DAG.getTarget().Options.UnsafeFPMath) {
6734 
6735       // Twiddle input to make sure the low 11 bits are zero.  (If this
6736       // is the case, we are guaranteed the value will fit into the 53 bit
6737       // mantissa of an IEEE double-precision value without rounding.)
6738       // If any of those low 11 bits were not zero originally, make sure
6739       // bit 12 (value 2048) is set instead, so that the final rounding
6740       // to single-precision gets the correct result.
6741       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6742                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6743       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6744                           Round, DAG.getConstant(2047, dl, MVT::i64));
6745       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6746       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6747                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6748 
6749       // However, we cannot use that value unconditionally: if the magnitude
6750       // of the input value is small, the bit-twiddling we did above might
6751       // end up visibly changing the output.  Fortunately, in that case, we
6752       // don't need to twiddle bits since the original input will convert
6753       // exactly to double-precision floating-point already.  Therefore,
6754       // construct a conditional to use the original value if the top 11
6755       // bits are all sign-bit copies, and use the rounded value computed
6756       // above otherwise.
6757       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6758                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6759       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6760                          Cond, DAG.getConstant(1, dl, MVT::i64));
6761       Cond = DAG.getSetCC(dl, MVT::i32,
6762                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6763 
6764       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6765     }
6766 
6767     ReuseLoadInfo RLI;
6768     SDValue Bits;
6769 
6770     MachineFunction &MF = DAG.getMachineFunction();
6771     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6772       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6773                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6774       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6775     } else if (Subtarget.hasLFIWAX() &&
6776                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6777       MachineMemOperand *MMO =
6778         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6779                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6780       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6781       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6782                                      DAG.getVTList(MVT::f64, MVT::Other),
6783                                      Ops, MVT::i32, MMO);
6784       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6785     } else if (Subtarget.hasFPCVT() &&
6786                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6787       MachineMemOperand *MMO =
6788         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6789                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6790       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6791       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6792                                      DAG.getVTList(MVT::f64, MVT::Other),
6793                                      Ops, MVT::i32, MMO);
6794       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6795     } else if (((Subtarget.hasLFIWAX() &&
6796                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6797                 (Subtarget.hasFPCVT() &&
6798                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6799                SINT.getOperand(0).getValueType() == MVT::i32) {
6800       MachineFrameInfo &MFI = MF.getFrameInfo();
6801       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6802 
6803       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6804       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6805 
6806       SDValue Store =
6807           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6808                        MachinePointerInfo::getFixedStack(
6809                            DAG.getMachineFunction(), FrameIdx));
6810 
6811       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6812              "Expected an i32 store");
6813 
6814       RLI.Ptr = FIdx;
6815       RLI.Chain = Store;
6816       RLI.MPI =
6817           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6818       RLI.Alignment = 4;
6819 
6820       MachineMemOperand *MMO =
6821         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6822                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6823       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6824       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6825                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6826                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6827                                      Ops, MVT::i32, MMO);
6828     } else
6829       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6830 
6831     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6832 
6833     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6834       FP = DAG.getNode(ISD::FP_ROUND, dl,
6835                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6836     return FP;
6837   }
6838 
6839   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6840          "Unhandled INT_TO_FP type in custom expander!");
6841   // Since we only generate this in 64-bit mode, we can take advantage of
6842   // 64-bit registers.  In particular, sign extend the input value into the
6843   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6844   // then lfd it and fcfid it.
6845   MachineFunction &MF = DAG.getMachineFunction();
6846   MachineFrameInfo &MFI = MF.getFrameInfo();
6847   EVT PtrVT = getPointerTy(MF.getDataLayout());
6848 
6849   SDValue Ld;
6850   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6851     ReuseLoadInfo RLI;
6852     bool ReusingLoad;
6853     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6854                                             DAG))) {
6855       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6856       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6857 
6858       SDValue Store =
6859           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6860                        MachinePointerInfo::getFixedStack(
6861                            DAG.getMachineFunction(), FrameIdx));
6862 
6863       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6864              "Expected an i32 store");
6865 
6866       RLI.Ptr = FIdx;
6867       RLI.Chain = Store;
6868       RLI.MPI =
6869           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6870       RLI.Alignment = 4;
6871     }
6872 
6873     MachineMemOperand *MMO =
6874       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6875                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6876     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6877     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6878                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6879                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6880                                  Ops, MVT::i32, MMO);
6881     if (ReusingLoad)
6882       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6883   } else {
6884     assert(Subtarget.isPPC64() &&
6885            "i32->FP without LFIWAX supported only on PPC64");
6886 
6887     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6888     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6889 
6890     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6891                                 Op.getOperand(0));
6892 
6893     // STD the extended value into the stack slot.
6894     SDValue Store = DAG.getStore(
6895         DAG.getEntryNode(), dl, Ext64, FIdx,
6896         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6897 
6898     // Load the value as a double.
6899     Ld = DAG.getLoad(
6900         MVT::f64, dl, Store, FIdx,
6901         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6902   }
6903 
6904   // FCFID it and return it.
6905   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6906   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6907     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6908                      DAG.getIntPtrConstant(0, dl));
6909   return FP;
6910 }
6911 
6912 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6913                                             SelectionDAG &DAG) const {
6914   SDLoc dl(Op);
6915   /*
6916    The rounding mode is in bits 30:31 of FPSR, and has the following
6917    settings:
6918      00 Round to nearest
6919      01 Round to 0
6920      10 Round to +inf
6921      11 Round to -inf
6922 
6923   FLT_ROUNDS, on the other hand, expects the following:
6924     -1 Undefined
6925      0 Round to 0
6926      1 Round to nearest
6927      2 Round to +inf
6928      3 Round to -inf
6929 
6930   To perform the conversion, we do:
6931     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6932   */
6933 
6934   MachineFunction &MF = DAG.getMachineFunction();
6935   EVT VT = Op.getValueType();
6936   EVT PtrVT = getPointerTy(MF.getDataLayout());
6937 
6938   // Save FP Control Word to register
6939   EVT NodeTys[] = {
6940     MVT::f64,    // return register
6941     MVT::Glue    // unused in this context
6942   };
6943   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6944 
6945   // Save FP register to stack slot
6946   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
6947   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6948   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
6949                                MachinePointerInfo());
6950 
6951   // Load FP Control Word from low 32 bits of stack slot.
6952   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6953   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6954   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
6955 
6956   // Transform as necessary
6957   SDValue CWD1 =
6958     DAG.getNode(ISD::AND, dl, MVT::i32,
6959                 CWD, DAG.getConstant(3, dl, MVT::i32));
6960   SDValue CWD2 =
6961     DAG.getNode(ISD::SRL, dl, MVT::i32,
6962                 DAG.getNode(ISD::AND, dl, MVT::i32,
6963                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6964                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6965                             DAG.getConstant(3, dl, MVT::i32)),
6966                 DAG.getConstant(1, dl, MVT::i32));
6967 
6968   SDValue RetVal =
6969     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6970 
6971   return DAG.getNode((VT.getSizeInBits() < 16 ?
6972                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6973 }
6974 
6975 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6976   EVT VT = Op.getValueType();
6977   unsigned BitWidth = VT.getSizeInBits();
6978   SDLoc dl(Op);
6979   assert(Op.getNumOperands() == 3 &&
6980          VT == Op.getOperand(1).getValueType() &&
6981          "Unexpected SHL!");
6982 
6983   // Expand into a bunch of logical ops.  Note that these ops
6984   // depend on the PPC behavior for oversized shift amounts.
6985   SDValue Lo = Op.getOperand(0);
6986   SDValue Hi = Op.getOperand(1);
6987   SDValue Amt = Op.getOperand(2);
6988   EVT AmtVT = Amt.getValueType();
6989 
6990   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6991                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6992   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6993   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6994   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6995   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6996                              DAG.getConstant(-BitWidth, dl, AmtVT));
6997   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6998   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6999   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7000   SDValue OutOps[] = { OutLo, OutHi };
7001   return DAG.getMergeValues(OutOps, dl);
7002 }
7003 
7004 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7005   EVT VT = Op.getValueType();
7006   SDLoc dl(Op);
7007   unsigned BitWidth = VT.getSizeInBits();
7008   assert(Op.getNumOperands() == 3 &&
7009          VT == Op.getOperand(1).getValueType() &&
7010          "Unexpected SRL!");
7011 
7012   // Expand into a bunch of logical ops.  Note that these ops
7013   // depend on the PPC behavior for oversized shift amounts.
7014   SDValue Lo = Op.getOperand(0);
7015   SDValue Hi = Op.getOperand(1);
7016   SDValue Amt = Op.getOperand(2);
7017   EVT AmtVT = Amt.getValueType();
7018 
7019   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7020                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7021   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7022   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7023   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7024   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7025                              DAG.getConstant(-BitWidth, dl, AmtVT));
7026   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7027   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7028   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7029   SDValue OutOps[] = { OutLo, OutHi };
7030   return DAG.getMergeValues(OutOps, dl);
7031 }
7032 
7033 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7034   SDLoc dl(Op);
7035   EVT VT = Op.getValueType();
7036   unsigned BitWidth = VT.getSizeInBits();
7037   assert(Op.getNumOperands() == 3 &&
7038          VT == Op.getOperand(1).getValueType() &&
7039          "Unexpected SRA!");
7040 
7041   // Expand into a bunch of logical ops, followed by a select_cc.
7042   SDValue Lo = Op.getOperand(0);
7043   SDValue Hi = Op.getOperand(1);
7044   SDValue Amt = Op.getOperand(2);
7045   EVT AmtVT = Amt.getValueType();
7046 
7047   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7048                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7049   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7050   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7051   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7052   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7053                              DAG.getConstant(-BitWidth, dl, AmtVT));
7054   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7055   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7056   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7057                                   Tmp4, Tmp6, ISD::SETLE);
7058   SDValue OutOps[] = { OutLo, OutHi };
7059   return DAG.getMergeValues(OutOps, dl);
7060 }
7061 
7062 //===----------------------------------------------------------------------===//
7063 // Vector related lowering.
7064 //
7065 
7066 /// BuildSplatI - Build a canonical splati of Val with an element size of
7067 /// SplatSize.  Cast the result to VT.
7068 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7069                            SelectionDAG &DAG, const SDLoc &dl) {
7070   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7071 
7072   static const MVT VTys[] = { // canonical VT to use for each size.
7073     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7074   };
7075 
7076   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7077 
7078   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7079   if (Val == -1)
7080     SplatSize = 1;
7081 
7082   EVT CanonicalVT = VTys[SplatSize-1];
7083 
7084   // Build a canonical splat for this value.
7085   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7086 }
7087 
7088 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7089 /// specified intrinsic ID.
7090 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7091                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7092   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7093   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7094                      DAG.getConstant(IID, dl, MVT::i32), Op);
7095 }
7096 
7097 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7098 /// specified intrinsic ID.
7099 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7100                                 SelectionDAG &DAG, const SDLoc &dl,
7101                                 EVT DestVT = MVT::Other) {
7102   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7103   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7104                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7105 }
7106 
7107 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7108 /// specified intrinsic ID.
7109 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7110                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7111                                 EVT DestVT = MVT::Other) {
7112   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7113   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7114                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7115 }
7116 
7117 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7118 /// amount.  The result has the specified value type.
7119 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7120                            SelectionDAG &DAG, const SDLoc &dl) {
7121   // Force LHS/RHS to be the right type.
7122   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7123   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7124 
7125   int Ops[16];
7126   for (unsigned i = 0; i != 16; ++i)
7127     Ops[i] = i + Amt;
7128   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7129   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7130 }
7131 
7132 static bool isNonConstSplatBV(BuildVectorSDNode *BVN, EVT Type) {
7133   if (BVN->isConstant() || BVN->getValueType(0) != Type)
7134     return false;
7135   auto OpZero = BVN->getOperand(0);
7136   for (int i = 1, e = BVN->getNumOperands(); i < e; i++)
7137     if (BVN->getOperand(i) != OpZero)
7138       return false;
7139   return true;
7140 }
7141 
7142 // If this is a case we can't handle, return null and let the default
7143 // expansion code take care of it.  If we CAN select this case, and if it
7144 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7145 // this case more efficiently than a constant pool load, lower it to the
7146 // sequence of ops that should be used.
7147 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7148                                              SelectionDAG &DAG) const {
7149   SDLoc dl(Op);
7150   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7151   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7152 
7153   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7154     // We first build an i32 vector, load it into a QPX register,
7155     // then convert it to a floating-point vector and compare it
7156     // to a zero vector to get the boolean result.
7157     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7158     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7159     MachinePointerInfo PtrInfo =
7160         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7161     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7162     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7163 
7164     assert(BVN->getNumOperands() == 4 &&
7165       "BUILD_VECTOR for v4i1 does not have 4 operands");
7166 
7167     bool IsConst = true;
7168     for (unsigned i = 0; i < 4; ++i) {
7169       if (BVN->getOperand(i).isUndef()) continue;
7170       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7171         IsConst = false;
7172         break;
7173       }
7174     }
7175 
7176     if (IsConst) {
7177       Constant *One =
7178         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7179       Constant *NegOne =
7180         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7181 
7182       Constant *CV[4];
7183       for (unsigned i = 0; i < 4; ++i) {
7184         if (BVN->getOperand(i).isUndef())
7185           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7186         else if (isNullConstant(BVN->getOperand(i)))
7187           CV[i] = NegOne;
7188         else
7189           CV[i] = One;
7190       }
7191 
7192       Constant *CP = ConstantVector::get(CV);
7193       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7194                                           16 /* alignment */);
7195 
7196       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7197       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7198       return DAG.getMemIntrinsicNode(
7199           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7200           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7201     }
7202 
7203     SmallVector<SDValue, 4> Stores;
7204     for (unsigned i = 0; i < 4; ++i) {
7205       if (BVN->getOperand(i).isUndef()) continue;
7206 
7207       unsigned Offset = 4*i;
7208       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7209       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7210 
7211       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7212       if (StoreSize > 4) {
7213         Stores.push_back(
7214             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7215                               PtrInfo.getWithOffset(Offset), MVT::i32));
7216       } else {
7217         SDValue StoreValue = BVN->getOperand(i);
7218         if (StoreSize < 4)
7219           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7220 
7221         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7222                                       PtrInfo.getWithOffset(Offset)));
7223       }
7224     }
7225 
7226     SDValue StoreChain;
7227     if (!Stores.empty())
7228       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7229     else
7230       StoreChain = DAG.getEntryNode();
7231 
7232     // Now load from v4i32 into the QPX register; this will extend it to
7233     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7234     // is typed as v4f64 because the QPX register integer states are not
7235     // explicitly represented.
7236 
7237     SDValue Ops[] = {StoreChain,
7238                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7239                      FIdx};
7240     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7241 
7242     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7243       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7244     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7245       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7246       LoadedVect);
7247 
7248     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7249 
7250     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7251   }
7252 
7253   // All other QPX vectors are handled by generic code.
7254   if (Subtarget.hasQPX())
7255     return SDValue();
7256 
7257   // Check if this is a splat of a constant value.
7258   APInt APSplatBits, APSplatUndef;
7259   unsigned SplatBitSize;
7260   bool HasAnyUndefs;
7261   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7262                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7263       SplatBitSize > 32) {
7264     // We can splat a non-const value on CPU's that implement ISA 3.0
7265     // in two ways: LXVWSX (load and splat) and MTVSRWS(move and splat).
7266     auto OpZero = BVN->getOperand(0);
7267     bool CanLoadAndSplat = OpZero.getOpcode() == ISD::LOAD &&
7268       BVN->isOnlyUserOf(OpZero.getNode());
7269     if (Subtarget.isISA3_0() && !CanLoadAndSplat &&
7270         (isNonConstSplatBV(BVN, MVT::v4i32) ||
7271          isNonConstSplatBV(BVN, MVT::v2i64)))
7272       return Op;
7273     return SDValue();
7274   }
7275 
7276   unsigned SplatBits = APSplatBits.getZExtValue();
7277   unsigned SplatUndef = APSplatUndef.getZExtValue();
7278   unsigned SplatSize = SplatBitSize / 8;
7279 
7280   // First, handle single instruction cases.
7281 
7282   // All zeros?
7283   if (SplatBits == 0) {
7284     // Canonicalize all zero vectors to be v4i32.
7285     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7286       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7287       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7288     }
7289     return Op;
7290   }
7291 
7292   // We have XXSPLTIB for constant splats one byte wide
7293   if (Subtarget.isISA3_0() && Op.getValueType() == MVT::v16i8)
7294     return Op;
7295 
7296   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7297   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7298                     (32-SplatBitSize));
7299   if (SextVal >= -16 && SextVal <= 15)
7300     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7301 
7302   // Two instruction sequences.
7303 
7304   // If this value is in the range [-32,30] and is even, use:
7305   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7306   // If this value is in the range [17,31] and is odd, use:
7307   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7308   // If this value is in the range [-31,-17] and is odd, use:
7309   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7310   // Note the last two are three-instruction sequences.
7311   if (SextVal >= -32 && SextVal <= 31) {
7312     // To avoid having these optimizations undone by constant folding,
7313     // we convert to a pseudo that will be expanded later into one of
7314     // the above forms.
7315     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7316     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7317               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7318     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7319     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7320     if (VT == Op.getValueType())
7321       return RetVal;
7322     else
7323       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7324   }
7325 
7326   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7327   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7328   // for fneg/fabs.
7329   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7330     // Make -1 and vspltisw -1:
7331     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7332 
7333     // Make the VSLW intrinsic, computing 0x8000_0000.
7334     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7335                                    OnesV, DAG, dl);
7336 
7337     // xor by OnesV to invert it.
7338     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7339     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7340   }
7341 
7342   // Check to see if this is a wide variety of vsplti*, binop self cases.
7343   static const signed char SplatCsts[] = {
7344     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7345     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7346   };
7347 
7348   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7349     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7350     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7351     int i = SplatCsts[idx];
7352 
7353     // Figure out what shift amount will be used by altivec if shifted by i in
7354     // this splat size.
7355     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7356 
7357     // vsplti + shl self.
7358     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7359       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7360       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7361         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7362         Intrinsic::ppc_altivec_vslw
7363       };
7364       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7365       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7366     }
7367 
7368     // vsplti + srl self.
7369     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7370       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7371       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7372         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7373         Intrinsic::ppc_altivec_vsrw
7374       };
7375       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7376       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7377     }
7378 
7379     // vsplti + sra self.
7380     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7381       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7382       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7383         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7384         Intrinsic::ppc_altivec_vsraw
7385       };
7386       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7387       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7388     }
7389 
7390     // vsplti + rol self.
7391     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7392                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7393       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7394       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7395         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7396         Intrinsic::ppc_altivec_vrlw
7397       };
7398       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7399       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7400     }
7401 
7402     // t = vsplti c, result = vsldoi t, t, 1
7403     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7404       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7405       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7406       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7407     }
7408     // t = vsplti c, result = vsldoi t, t, 2
7409     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7410       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7411       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7412       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7413     }
7414     // t = vsplti c, result = vsldoi t, t, 3
7415     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7416       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7417       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7418       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7419     }
7420   }
7421 
7422   return SDValue();
7423 }
7424 
7425 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7426 /// the specified operations to build the shuffle.
7427 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7428                                       SDValue RHS, SelectionDAG &DAG,
7429                                       const SDLoc &dl) {
7430   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7431   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7432   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7433 
7434   enum {
7435     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7436     OP_VMRGHW,
7437     OP_VMRGLW,
7438     OP_VSPLTISW0,
7439     OP_VSPLTISW1,
7440     OP_VSPLTISW2,
7441     OP_VSPLTISW3,
7442     OP_VSLDOI4,
7443     OP_VSLDOI8,
7444     OP_VSLDOI12
7445   };
7446 
7447   if (OpNum == OP_COPY) {
7448     if (LHSID == (1*9+2)*9+3) return LHS;
7449     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7450     return RHS;
7451   }
7452 
7453   SDValue OpLHS, OpRHS;
7454   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7455   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7456 
7457   int ShufIdxs[16];
7458   switch (OpNum) {
7459   default: llvm_unreachable("Unknown i32 permute!");
7460   case OP_VMRGHW:
7461     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7462     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7463     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7464     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7465     break;
7466   case OP_VMRGLW:
7467     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7468     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7469     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7470     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7471     break;
7472   case OP_VSPLTISW0:
7473     for (unsigned i = 0; i != 16; ++i)
7474       ShufIdxs[i] = (i&3)+0;
7475     break;
7476   case OP_VSPLTISW1:
7477     for (unsigned i = 0; i != 16; ++i)
7478       ShufIdxs[i] = (i&3)+4;
7479     break;
7480   case OP_VSPLTISW2:
7481     for (unsigned i = 0; i != 16; ++i)
7482       ShufIdxs[i] = (i&3)+8;
7483     break;
7484   case OP_VSPLTISW3:
7485     for (unsigned i = 0; i != 16; ++i)
7486       ShufIdxs[i] = (i&3)+12;
7487     break;
7488   case OP_VSLDOI4:
7489     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7490   case OP_VSLDOI8:
7491     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7492   case OP_VSLDOI12:
7493     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7494   }
7495   EVT VT = OpLHS.getValueType();
7496   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7497   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7498   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7499   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7500 }
7501 
7502 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7503 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7504 /// return the code it can be lowered into.  Worst case, it can always be
7505 /// lowered into a vperm.
7506 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7507                                                SelectionDAG &DAG) const {
7508   SDLoc dl(Op);
7509   SDValue V1 = Op.getOperand(0);
7510   SDValue V2 = Op.getOperand(1);
7511   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7512   EVT VT = Op.getValueType();
7513   bool isLittleEndian = Subtarget.isLittleEndian();
7514 
7515   unsigned ShiftElts, InsertAtByte;
7516   bool Swap;
7517   if (Subtarget.hasP9Vector() &&
7518       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7519                            isLittleEndian)) {
7520     if (Swap)
7521       std::swap(V1, V2);
7522     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7523     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7524     if (ShiftElts) {
7525       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7526                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7527       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7528                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7529       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7530     }
7531     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7532                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7533     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7534   }
7535 
7536   if (Subtarget.hasVSX()) {
7537     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7538       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7539 
7540       // If the source for the shuffle is a scalar_to_vector that came from a
7541       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7542       if (Subtarget.isISA3_0() &&
7543           ((isLittleEndian && SplatIdx == 3) ||
7544            (!isLittleEndian && SplatIdx == 0))) {
7545         SDValue Src = V1.getOperand(0);
7546         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7547             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7548             Src.getOperand(0).hasOneUse())
7549           return V1;
7550       }
7551       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7552       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7553                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7554       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7555     }
7556 
7557     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7558     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7559       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7560       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7561       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7562     }
7563 
7564   }
7565 
7566   if (Subtarget.hasQPX()) {
7567     if (VT.getVectorNumElements() != 4)
7568       return SDValue();
7569 
7570     if (V2.isUndef()) V2 = V1;
7571 
7572     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7573     if (AlignIdx != -1) {
7574       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7575                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7576     } else if (SVOp->isSplat()) {
7577       int SplatIdx = SVOp->getSplatIndex();
7578       if (SplatIdx >= 4) {
7579         std::swap(V1, V2);
7580         SplatIdx -= 4;
7581       }
7582 
7583       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7584                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7585     }
7586 
7587     // Lower this into a qvgpci/qvfperm pair.
7588 
7589     // Compute the qvgpci literal
7590     unsigned idx = 0;
7591     for (unsigned i = 0; i < 4; ++i) {
7592       int m = SVOp->getMaskElt(i);
7593       unsigned mm = m >= 0 ? (unsigned) m : i;
7594       idx |= mm << (3-i)*3;
7595     }
7596 
7597     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7598                              DAG.getConstant(idx, dl, MVT::i32));
7599     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7600   }
7601 
7602   // Cases that are handled by instructions that take permute immediates
7603   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7604   // selected by the instruction selector.
7605   if (V2.isUndef()) {
7606     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7607         PPC::isSplatShuffleMask(SVOp, 2) ||
7608         PPC::isSplatShuffleMask(SVOp, 4) ||
7609         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7610         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7611         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7612         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7613         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7614         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7615         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7616         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7617         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7618         (Subtarget.hasP8Altivec() && (
7619          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7620          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7621          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7622       return Op;
7623     }
7624   }
7625 
7626   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7627   // and produce a fixed permutation.  If any of these match, do not lower to
7628   // VPERM.
7629   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7630   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7631       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7632       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7633       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7634       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7635       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7636       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7637       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7638       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7639       (Subtarget.hasP8Altivec() && (
7640        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7641        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7642        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7643     return Op;
7644 
7645   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7646   // perfect shuffle table to emit an optimal matching sequence.
7647   ArrayRef<int> PermMask = SVOp->getMask();
7648 
7649   unsigned PFIndexes[4];
7650   bool isFourElementShuffle = true;
7651   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7652     unsigned EltNo = 8;   // Start out undef.
7653     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7654       if (PermMask[i*4+j] < 0)
7655         continue;   // Undef, ignore it.
7656 
7657       unsigned ByteSource = PermMask[i*4+j];
7658       if ((ByteSource & 3) != j) {
7659         isFourElementShuffle = false;
7660         break;
7661       }
7662 
7663       if (EltNo == 8) {
7664         EltNo = ByteSource/4;
7665       } else if (EltNo != ByteSource/4) {
7666         isFourElementShuffle = false;
7667         break;
7668       }
7669     }
7670     PFIndexes[i] = EltNo;
7671   }
7672 
7673   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7674   // perfect shuffle vector to determine if it is cost effective to do this as
7675   // discrete instructions, or whether we should use a vperm.
7676   // For now, we skip this for little endian until such time as we have a
7677   // little-endian perfect shuffle table.
7678   if (isFourElementShuffle && !isLittleEndian) {
7679     // Compute the index in the perfect shuffle table.
7680     unsigned PFTableIndex =
7681       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7682 
7683     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7684     unsigned Cost  = (PFEntry >> 30);
7685 
7686     // Determining when to avoid vperm is tricky.  Many things affect the cost
7687     // of vperm, particularly how many times the perm mask needs to be computed.
7688     // For example, if the perm mask can be hoisted out of a loop or is already
7689     // used (perhaps because there are multiple permutes with the same shuffle
7690     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7691     // the loop requires an extra register.
7692     //
7693     // As a compromise, we only emit discrete instructions if the shuffle can be
7694     // generated in 3 or fewer operations.  When we have loop information
7695     // available, if this block is within a loop, we should avoid using vperm
7696     // for 3-operation perms and use a constant pool load instead.
7697     if (Cost < 3)
7698       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7699   }
7700 
7701   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7702   // vector that will get spilled to the constant pool.
7703   if (V2.isUndef()) V2 = V1;
7704 
7705   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7706   // that it is in input element units, not in bytes.  Convert now.
7707 
7708   // For little endian, the order of the input vectors is reversed, and
7709   // the permutation mask is complemented with respect to 31.  This is
7710   // necessary to produce proper semantics with the big-endian-biased vperm
7711   // instruction.
7712   EVT EltVT = V1.getValueType().getVectorElementType();
7713   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7714 
7715   SmallVector<SDValue, 16> ResultMask;
7716   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7717     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7718 
7719     for (unsigned j = 0; j != BytesPerElement; ++j)
7720       if (isLittleEndian)
7721         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7722                                              dl, MVT::i32));
7723       else
7724         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7725                                              MVT::i32));
7726   }
7727 
7728   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7729   if (isLittleEndian)
7730     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7731                        V2, V1, VPermMask);
7732   else
7733     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7734                        V1, V2, VPermMask);
7735 }
7736 
7737 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7738 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7739 /// information about the intrinsic.
7740 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7741                                  bool &isDot, const PPCSubtarget &Subtarget) {
7742   unsigned IntrinsicID =
7743     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7744   CompareOpc = -1;
7745   isDot = false;
7746   switch (IntrinsicID) {
7747   default: return false;
7748     // Comparison predicates.
7749   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7750   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7751   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7752   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7753   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7754   case Intrinsic::ppc_altivec_vcmpequd_p:
7755     if (Subtarget.hasP8Altivec()) {
7756       CompareOpc = 199;
7757       isDot = 1;
7758     } else
7759       return false;
7760 
7761     break;
7762   case Intrinsic::ppc_altivec_vcmpneb_p:
7763   case Intrinsic::ppc_altivec_vcmpneh_p:
7764   case Intrinsic::ppc_altivec_vcmpnew_p:
7765   case Intrinsic::ppc_altivec_vcmpnezb_p:
7766   case Intrinsic::ppc_altivec_vcmpnezh_p:
7767   case Intrinsic::ppc_altivec_vcmpnezw_p:
7768     if (Subtarget.hasP9Altivec()) {
7769       switch(IntrinsicID) {
7770       default: llvm_unreachable("Unknown comparison intrinsic.");
7771       case Intrinsic::ppc_altivec_vcmpneb_p: CompareOpc = 7; break;
7772       case Intrinsic::ppc_altivec_vcmpneh_p: CompareOpc = 71; break;
7773       case Intrinsic::ppc_altivec_vcmpnew_p: CompareOpc = 135; break;
7774       case Intrinsic::ppc_altivec_vcmpnezb_p: CompareOpc = 263; break;
7775       case Intrinsic::ppc_altivec_vcmpnezh_p: CompareOpc = 327; break;
7776       case Intrinsic::ppc_altivec_vcmpnezw_p: CompareOpc = 391; break;
7777       }
7778       isDot = 1;
7779     } else
7780       return false;
7781 
7782     break;
7783   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7784   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7785   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7786   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7787   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7788   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7789     if (Subtarget.hasP8Altivec()) {
7790       CompareOpc = 967;
7791       isDot = 1;
7792     } else
7793       return false;
7794 
7795     break;
7796   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7797   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7798   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7799   case Intrinsic::ppc_altivec_vcmpgtud_p:
7800     if (Subtarget.hasP8Altivec()) {
7801       CompareOpc = 711;
7802       isDot = 1;
7803     } else
7804       return false;
7805 
7806     break;
7807     // VSX predicate comparisons use the same infrastructure
7808   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7809   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7810   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7811   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7812   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7813   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7814     if (Subtarget.hasVSX()) {
7815       switch (IntrinsicID) {
7816       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7817       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7818       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7819       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7820       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7821       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7822       }
7823       isDot = 1;
7824     }
7825     else
7826       return false;
7827 
7828     break;
7829 
7830     // Normal Comparisons.
7831   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7832   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7833   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7834   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7835   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7836   case Intrinsic::ppc_altivec_vcmpequd:
7837     if (Subtarget.hasP8Altivec()) {
7838       CompareOpc = 199;
7839       isDot = 0;
7840     } else
7841       return false;
7842 
7843     break;
7844   case Intrinsic::ppc_altivec_vcmpneb:
7845   case Intrinsic::ppc_altivec_vcmpneh:
7846   case Intrinsic::ppc_altivec_vcmpnew:
7847   case Intrinsic::ppc_altivec_vcmpnezb:
7848   case Intrinsic::ppc_altivec_vcmpnezh:
7849   case Intrinsic::ppc_altivec_vcmpnezw:
7850     if (Subtarget.hasP9Altivec()) {
7851       switch (IntrinsicID) {
7852       default: llvm_unreachable("Unknown comparison intrinsic.");
7853       case Intrinsic::ppc_altivec_vcmpneb: CompareOpc = 7; break;
7854       case Intrinsic::ppc_altivec_vcmpneh: CompareOpc = 71; break;
7855       case Intrinsic::ppc_altivec_vcmpnew: CompareOpc = 135; break;
7856       case Intrinsic::ppc_altivec_vcmpnezb: CompareOpc = 263; break;
7857       case Intrinsic::ppc_altivec_vcmpnezh: CompareOpc = 327; break;
7858       case Intrinsic::ppc_altivec_vcmpnezw: CompareOpc = 391; break;
7859       }
7860       isDot = 0;
7861     } else
7862       return false;
7863     break;
7864   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7865   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7866   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7867   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7868   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7869   case Intrinsic::ppc_altivec_vcmpgtsd:
7870     if (Subtarget.hasP8Altivec()) {
7871       CompareOpc = 967;
7872       isDot = 0;
7873     } else
7874       return false;
7875 
7876     break;
7877   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7878   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7879   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7880   case Intrinsic::ppc_altivec_vcmpgtud:
7881     if (Subtarget.hasP8Altivec()) {
7882       CompareOpc = 711;
7883       isDot = 0;
7884     } else
7885       return false;
7886 
7887     break;
7888   }
7889   return true;
7890 }
7891 
7892 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7893 /// lower, do it, otherwise return null.
7894 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7895                                                    SelectionDAG &DAG) const {
7896   unsigned IntrinsicID =
7897     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7898 
7899   if (IntrinsicID == Intrinsic::thread_pointer) {
7900     // Reads the thread pointer register, used for __builtin_thread_pointer.
7901     bool is64bit = Subtarget.isPPC64();
7902     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7903                            is64bit ? MVT::i64 : MVT::i32);
7904   }
7905 
7906   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7907   // opcode number of the comparison.
7908   SDLoc dl(Op);
7909   int CompareOpc;
7910   bool isDot;
7911   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7912     return SDValue();    // Don't custom lower most intrinsics.
7913 
7914   // If this is a non-dot comparison, make the VCMP node and we are done.
7915   if (!isDot) {
7916     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7917                               Op.getOperand(1), Op.getOperand(2),
7918                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7919     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7920   }
7921 
7922   // Create the PPCISD altivec 'dot' comparison node.
7923   SDValue Ops[] = {
7924     Op.getOperand(2),  // LHS
7925     Op.getOperand(3),  // RHS
7926     DAG.getConstant(CompareOpc, dl, MVT::i32)
7927   };
7928   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7929   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7930 
7931   // Now that we have the comparison, emit a copy from the CR to a GPR.
7932   // This is flagged to the above dot comparison.
7933   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7934                                 DAG.getRegister(PPC::CR6, MVT::i32),
7935                                 CompNode.getValue(1));
7936 
7937   // Unpack the result based on how the target uses it.
7938   unsigned BitNo;   // Bit # of CR6.
7939   bool InvertBit;   // Invert result?
7940   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7941   default:  // Can't happen, don't crash on invalid number though.
7942   case 0:   // Return the value of the EQ bit of CR6.
7943     BitNo = 0; InvertBit = false;
7944     break;
7945   case 1:   // Return the inverted value of the EQ bit of CR6.
7946     BitNo = 0; InvertBit = true;
7947     break;
7948   case 2:   // Return the value of the LT bit of CR6.
7949     BitNo = 2; InvertBit = false;
7950     break;
7951   case 3:   // Return the inverted value of the LT bit of CR6.
7952     BitNo = 2; InvertBit = true;
7953     break;
7954   }
7955 
7956   // Shift the bit into the low position.
7957   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7958                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7959   // Isolate the bit.
7960   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7961                       DAG.getConstant(1, dl, MVT::i32));
7962 
7963   // If we are supposed to, toggle the bit.
7964   if (InvertBit)
7965     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7966                         DAG.getConstant(1, dl, MVT::i32));
7967   return Flags;
7968 }
7969 
7970 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7971                                                   SelectionDAG &DAG) const {
7972   SDLoc dl(Op);
7973   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7974   // instructions), but for smaller types, we need to first extend up to v2i32
7975   // before doing going farther.
7976   if (Op.getValueType() == MVT::v2i64) {
7977     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7978     if (ExtVT != MVT::v2i32) {
7979       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7980       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7981                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7982                                         ExtVT.getVectorElementType(), 4)));
7983       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7984       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7985                        DAG.getValueType(MVT::v2i32));
7986     }
7987 
7988     return Op;
7989   }
7990 
7991   return SDValue();
7992 }
7993 
7994 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7995                                                    SelectionDAG &DAG) const {
7996   SDLoc dl(Op);
7997   // Create a stack slot that is 16-byte aligned.
7998   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7999   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8000   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8001   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8002 
8003   // Store the input value into Value#0 of the stack slot.
8004   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8005                                MachinePointerInfo());
8006   // Load it out.
8007   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8008 }
8009 
8010 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8011                                                   SelectionDAG &DAG) const {
8012   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8013          "Should only be called for ISD::INSERT_VECTOR_ELT");
8014   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8015   // We have legal lowering for constant indices but not for variable ones.
8016   if (C)
8017     return Op;
8018   return SDValue();
8019 }
8020 
8021 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8022                                                    SelectionDAG &DAG) const {
8023   SDLoc dl(Op);
8024   SDNode *N = Op.getNode();
8025 
8026   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8027          "Unknown extract_vector_elt type");
8028 
8029   SDValue Value = N->getOperand(0);
8030 
8031   // The first part of this is like the store lowering except that we don't
8032   // need to track the chain.
8033 
8034   // The values are now known to be -1 (false) or 1 (true). To convert this
8035   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8036   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8037   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8038 
8039   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8040   // understand how to form the extending load.
8041   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8042 
8043   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8044 
8045   // Now convert to an integer and store.
8046   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8047     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8048     Value);
8049 
8050   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8051   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8052   MachinePointerInfo PtrInfo =
8053       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8054   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8055   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8056 
8057   SDValue StoreChain = DAG.getEntryNode();
8058   SDValue Ops[] = {StoreChain,
8059                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8060                    Value, FIdx};
8061   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8062 
8063   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8064     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8065 
8066   // Extract the value requested.
8067   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8068   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8069   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8070 
8071   SDValue IntVal =
8072       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8073 
8074   if (!Subtarget.useCRBits())
8075     return IntVal;
8076 
8077   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8078 }
8079 
8080 /// Lowering for QPX v4i1 loads
8081 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8082                                            SelectionDAG &DAG) const {
8083   SDLoc dl(Op);
8084   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8085   SDValue LoadChain = LN->getChain();
8086   SDValue BasePtr = LN->getBasePtr();
8087 
8088   if (Op.getValueType() == MVT::v4f64 ||
8089       Op.getValueType() == MVT::v4f32) {
8090     EVT MemVT = LN->getMemoryVT();
8091     unsigned Alignment = LN->getAlignment();
8092 
8093     // If this load is properly aligned, then it is legal.
8094     if (Alignment >= MemVT.getStoreSize())
8095       return Op;
8096 
8097     EVT ScalarVT = Op.getValueType().getScalarType(),
8098         ScalarMemVT = MemVT.getScalarType();
8099     unsigned Stride = ScalarMemVT.getStoreSize();
8100 
8101     SDValue Vals[4], LoadChains[4];
8102     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8103       SDValue Load;
8104       if (ScalarVT != ScalarMemVT)
8105         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8106                               BasePtr,
8107                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8108                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8109                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8110       else
8111         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8112                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8113                            MinAlign(Alignment, Idx * Stride),
8114                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8115 
8116       if (Idx == 0 && LN->isIndexed()) {
8117         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8118                "Unknown addressing mode on vector load");
8119         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8120                                   LN->getAddressingMode());
8121       }
8122 
8123       Vals[Idx] = Load;
8124       LoadChains[Idx] = Load.getValue(1);
8125 
8126       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8127                             DAG.getConstant(Stride, dl,
8128                                             BasePtr.getValueType()));
8129     }
8130 
8131     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8132     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8133 
8134     if (LN->isIndexed()) {
8135       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8136       return DAG.getMergeValues(RetOps, dl);
8137     }
8138 
8139     SDValue RetOps[] = { Value, TF };
8140     return DAG.getMergeValues(RetOps, dl);
8141   }
8142 
8143   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8144   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8145 
8146   // To lower v4i1 from a byte array, we load the byte elements of the
8147   // vector and then reuse the BUILD_VECTOR logic.
8148 
8149   SDValue VectElmts[4], VectElmtChains[4];
8150   for (unsigned i = 0; i < 4; ++i) {
8151     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8152     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8153 
8154     VectElmts[i] = DAG.getExtLoad(
8155         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8156         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8157         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8158     VectElmtChains[i] = VectElmts[i].getValue(1);
8159   }
8160 
8161   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8162   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8163 
8164   SDValue RVals[] = { Value, LoadChain };
8165   return DAG.getMergeValues(RVals, dl);
8166 }
8167 
8168 /// Lowering for QPX v4i1 stores
8169 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8170                                             SelectionDAG &DAG) const {
8171   SDLoc dl(Op);
8172   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8173   SDValue StoreChain = SN->getChain();
8174   SDValue BasePtr = SN->getBasePtr();
8175   SDValue Value = SN->getValue();
8176 
8177   if (Value.getValueType() == MVT::v4f64 ||
8178       Value.getValueType() == MVT::v4f32) {
8179     EVT MemVT = SN->getMemoryVT();
8180     unsigned Alignment = SN->getAlignment();
8181 
8182     // If this store is properly aligned, then it is legal.
8183     if (Alignment >= MemVT.getStoreSize())
8184       return Op;
8185 
8186     EVT ScalarVT = Value.getValueType().getScalarType(),
8187         ScalarMemVT = MemVT.getScalarType();
8188     unsigned Stride = ScalarMemVT.getStoreSize();
8189 
8190     SDValue Stores[4];
8191     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8192       SDValue Ex = DAG.getNode(
8193           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8194           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8195       SDValue Store;
8196       if (ScalarVT != ScalarMemVT)
8197         Store =
8198             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8199                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8200                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8201                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8202       else
8203         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8204                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8205                              MinAlign(Alignment, Idx * Stride),
8206                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8207 
8208       if (Idx == 0 && SN->isIndexed()) {
8209         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8210                "Unknown addressing mode on vector store");
8211         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8212                                     SN->getAddressingMode());
8213       }
8214 
8215       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8216                             DAG.getConstant(Stride, dl,
8217                                             BasePtr.getValueType()));
8218       Stores[Idx] = Store;
8219     }
8220 
8221     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8222 
8223     if (SN->isIndexed()) {
8224       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8225       return DAG.getMergeValues(RetOps, dl);
8226     }
8227 
8228     return TF;
8229   }
8230 
8231   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8232   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8233 
8234   // The values are now known to be -1 (false) or 1 (true). To convert this
8235   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8236   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8237   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8238 
8239   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8240   // understand how to form the extending load.
8241   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8242 
8243   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8244 
8245   // Now convert to an integer and store.
8246   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8247     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8248     Value);
8249 
8250   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8251   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8252   MachinePointerInfo PtrInfo =
8253       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8254   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8255   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8256 
8257   SDValue Ops[] = {StoreChain,
8258                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8259                    Value, FIdx};
8260   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8261 
8262   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8263     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8264 
8265   // Move data into the byte array.
8266   SDValue Loads[4], LoadChains[4];
8267   for (unsigned i = 0; i < 4; ++i) {
8268     unsigned Offset = 4*i;
8269     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8270     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8271 
8272     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8273                            PtrInfo.getWithOffset(Offset));
8274     LoadChains[i] = Loads[i].getValue(1);
8275   }
8276 
8277   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8278 
8279   SDValue Stores[4];
8280   for (unsigned i = 0; i < 4; ++i) {
8281     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8282     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8283 
8284     Stores[i] = DAG.getTruncStore(
8285         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8286         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8287         SN->getAAInfo());
8288   }
8289 
8290   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8291 
8292   return StoreChain;
8293 }
8294 
8295 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8296   SDLoc dl(Op);
8297   if (Op.getValueType() == MVT::v4i32) {
8298     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8299 
8300     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8301     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8302 
8303     SDValue RHSSwap =   // = vrlw RHS, 16
8304       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8305 
8306     // Shrinkify inputs to v8i16.
8307     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8308     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8309     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8310 
8311     // Low parts multiplied together, generating 32-bit results (we ignore the
8312     // top parts).
8313     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8314                                         LHS, RHS, DAG, dl, MVT::v4i32);
8315 
8316     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8317                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8318     // Shift the high parts up 16 bits.
8319     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8320                               Neg16, DAG, dl);
8321     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8322   } else if (Op.getValueType() == MVT::v8i16) {
8323     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8324 
8325     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8326 
8327     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8328                             LHS, RHS, Zero, DAG, dl);
8329   } else if (Op.getValueType() == MVT::v16i8) {
8330     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8331     bool isLittleEndian = Subtarget.isLittleEndian();
8332 
8333     // Multiply the even 8-bit parts, producing 16-bit sums.
8334     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8335                                            LHS, RHS, DAG, dl, MVT::v8i16);
8336     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8337 
8338     // Multiply the odd 8-bit parts, producing 16-bit sums.
8339     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8340                                           LHS, RHS, DAG, dl, MVT::v8i16);
8341     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8342 
8343     // Merge the results together.  Because vmuleub and vmuloub are
8344     // instructions with a big-endian bias, we must reverse the
8345     // element numbering and reverse the meaning of "odd" and "even"
8346     // when generating little endian code.
8347     int Ops[16];
8348     for (unsigned i = 0; i != 8; ++i) {
8349       if (isLittleEndian) {
8350         Ops[i*2  ] = 2*i;
8351         Ops[i*2+1] = 2*i+16;
8352       } else {
8353         Ops[i*2  ] = 2*i+1;
8354         Ops[i*2+1] = 2*i+1+16;
8355       }
8356     }
8357     if (isLittleEndian)
8358       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8359     else
8360       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8361   } else {
8362     llvm_unreachable("Unknown mul to lower!");
8363   }
8364 }
8365 
8366 /// LowerOperation - Provide custom lowering hooks for some operations.
8367 ///
8368 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8369   switch (Op.getOpcode()) {
8370   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8371   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8372   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8373   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8374   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8375   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8376   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8377   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8378   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8379   case ISD::VASTART:
8380     return LowerVASTART(Op, DAG);
8381 
8382   case ISD::VAARG:
8383     return LowerVAARG(Op, DAG);
8384 
8385   case ISD::VACOPY:
8386     return LowerVACOPY(Op, DAG);
8387 
8388   case ISD::STACKRESTORE:
8389     return LowerSTACKRESTORE(Op, DAG);
8390 
8391   case ISD::DYNAMIC_STACKALLOC:
8392     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8393 
8394   case ISD::GET_DYNAMIC_AREA_OFFSET:
8395     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8396 
8397   case ISD::EH_DWARF_CFA:
8398     return LowerEH_DWARF_CFA(Op, DAG);
8399 
8400   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8401   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8402 
8403   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8404   case ISD::STORE:              return LowerSTORE(Op, DAG);
8405   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8406   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8407   case ISD::FP_TO_UINT:
8408   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8409                                                       SDLoc(Op));
8410   case ISD::UINT_TO_FP:
8411   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8412   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8413 
8414   // Lower 64-bit shifts.
8415   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8416   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8417   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8418 
8419   // Vector-related lowering.
8420   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8421   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8422   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8423   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8424   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8425   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8426   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8427   case ISD::MUL:                return LowerMUL(Op, DAG);
8428 
8429   // For counter-based loop handling.
8430   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8431 
8432   // Frame & Return address.
8433   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8434   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8435   }
8436 }
8437 
8438 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8439                                            SmallVectorImpl<SDValue>&Results,
8440                                            SelectionDAG &DAG) const {
8441   SDLoc dl(N);
8442   switch (N->getOpcode()) {
8443   default:
8444     llvm_unreachable("Do not know how to custom type legalize this operation!");
8445   case ISD::READCYCLECOUNTER: {
8446     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8447     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8448 
8449     Results.push_back(RTB);
8450     Results.push_back(RTB.getValue(1));
8451     Results.push_back(RTB.getValue(2));
8452     break;
8453   }
8454   case ISD::INTRINSIC_W_CHAIN: {
8455     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8456         Intrinsic::ppc_is_decremented_ctr_nonzero)
8457       break;
8458 
8459     assert(N->getValueType(0) == MVT::i1 &&
8460            "Unexpected result type for CTR decrement intrinsic");
8461     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8462                                  N->getValueType(0));
8463     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8464     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8465                                  N->getOperand(1));
8466 
8467     Results.push_back(NewInt);
8468     Results.push_back(NewInt.getValue(1));
8469     break;
8470   }
8471   case ISD::VAARG: {
8472     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8473       return;
8474 
8475     EVT VT = N->getValueType(0);
8476 
8477     if (VT == MVT::i64) {
8478       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8479 
8480       Results.push_back(NewNode);
8481       Results.push_back(NewNode.getValue(1));
8482     }
8483     return;
8484   }
8485   case ISD::FP_ROUND_INREG: {
8486     assert(N->getValueType(0) == MVT::ppcf128);
8487     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8488     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8489                              MVT::f64, N->getOperand(0),
8490                              DAG.getIntPtrConstant(0, dl));
8491     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8492                              MVT::f64, N->getOperand(0),
8493                              DAG.getIntPtrConstant(1, dl));
8494 
8495     // Add the two halves of the long double in round-to-zero mode.
8496     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8497 
8498     // We know the low half is about to be thrown away, so just use something
8499     // convenient.
8500     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8501                                 FPreg, FPreg));
8502     return;
8503   }
8504   case ISD::FP_TO_SINT:
8505   case ISD::FP_TO_UINT:
8506     // LowerFP_TO_INT() can only handle f32 and f64.
8507     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8508       return;
8509     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8510     return;
8511   }
8512 }
8513 
8514 //===----------------------------------------------------------------------===//
8515 //  Other Lowering Code
8516 //===----------------------------------------------------------------------===//
8517 
8518 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8519   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8520   Function *Func = Intrinsic::getDeclaration(M, Id);
8521   return Builder.CreateCall(Func, {});
8522 }
8523 
8524 // The mappings for emitLeading/TrailingFence is taken from
8525 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8526 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8527                                          AtomicOrdering Ord, bool IsStore,
8528                                          bool IsLoad) const {
8529   if (Ord == AtomicOrdering::SequentiallyConsistent)
8530     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8531   if (isReleaseOrStronger(Ord))
8532     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8533   return nullptr;
8534 }
8535 
8536 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8537                                           AtomicOrdering Ord, bool IsStore,
8538                                           bool IsLoad) const {
8539   if (IsLoad && isAcquireOrStronger(Ord))
8540     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8541   // FIXME: this is too conservative, a dependent branch + isync is enough.
8542   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8543   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8544   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8545   return nullptr;
8546 }
8547 
8548 MachineBasicBlock *
8549 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8550                                     unsigned AtomicSize,
8551                                     unsigned BinOpcode,
8552                                     unsigned CmpOpcode,
8553                                     unsigned CmpPred) const {
8554   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8555   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8556 
8557   auto LoadMnemonic = PPC::LDARX;
8558   auto StoreMnemonic = PPC::STDCX;
8559   switch (AtomicSize) {
8560   default:
8561     llvm_unreachable("Unexpected size of atomic entity");
8562   case 1:
8563     LoadMnemonic = PPC::LBARX;
8564     StoreMnemonic = PPC::STBCX;
8565     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8566     break;
8567   case 2:
8568     LoadMnemonic = PPC::LHARX;
8569     StoreMnemonic = PPC::STHCX;
8570     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8571     break;
8572   case 4:
8573     LoadMnemonic = PPC::LWARX;
8574     StoreMnemonic = PPC::STWCX;
8575     break;
8576   case 8:
8577     LoadMnemonic = PPC::LDARX;
8578     StoreMnemonic = PPC::STDCX;
8579     break;
8580   }
8581 
8582   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8583   MachineFunction *F = BB->getParent();
8584   MachineFunction::iterator It = ++BB->getIterator();
8585 
8586   unsigned dest = MI.getOperand(0).getReg();
8587   unsigned ptrA = MI.getOperand(1).getReg();
8588   unsigned ptrB = MI.getOperand(2).getReg();
8589   unsigned incr = MI.getOperand(3).getReg();
8590   DebugLoc dl = MI.getDebugLoc();
8591 
8592   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8593   MachineBasicBlock *loop2MBB =
8594     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8595   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8596   F->insert(It, loopMBB);
8597   if (CmpOpcode)
8598     F->insert(It, loop2MBB);
8599   F->insert(It, exitMBB);
8600   exitMBB->splice(exitMBB->begin(), BB,
8601                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8602   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8603 
8604   MachineRegisterInfo &RegInfo = F->getRegInfo();
8605   unsigned TmpReg = (!BinOpcode) ? incr :
8606     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8607                                            : &PPC::GPRCRegClass);
8608 
8609   //  thisMBB:
8610   //   ...
8611   //   fallthrough --> loopMBB
8612   BB->addSuccessor(loopMBB);
8613 
8614   //  loopMBB:
8615   //   l[wd]arx dest, ptr
8616   //   add r0, dest, incr
8617   //   st[wd]cx. r0, ptr
8618   //   bne- loopMBB
8619   //   fallthrough --> exitMBB
8620 
8621   // For max/min...
8622   //  loopMBB:
8623   //   l[wd]arx dest, ptr
8624   //   cmpl?[wd] incr, dest
8625   //   bgt exitMBB
8626   //  loop2MBB:
8627   //   st[wd]cx. dest, ptr
8628   //   bne- loopMBB
8629   //   fallthrough --> exitMBB
8630 
8631   BB = loopMBB;
8632   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8633     .addReg(ptrA).addReg(ptrB);
8634   if (BinOpcode)
8635     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8636   if (CmpOpcode) {
8637     // Signed comparisons of byte or halfword values must be sign-extended.
8638     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8639       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8640       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8641               ExtReg).addReg(dest);
8642       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8643         .addReg(incr).addReg(ExtReg);
8644     } else
8645       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8646         .addReg(incr).addReg(dest);
8647 
8648     BuildMI(BB, dl, TII->get(PPC::BCC))
8649       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8650     BB->addSuccessor(loop2MBB);
8651     BB->addSuccessor(exitMBB);
8652     BB = loop2MBB;
8653   }
8654   BuildMI(BB, dl, TII->get(StoreMnemonic))
8655     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8656   BuildMI(BB, dl, TII->get(PPC::BCC))
8657     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8658   BB->addSuccessor(loopMBB);
8659   BB->addSuccessor(exitMBB);
8660 
8661   //  exitMBB:
8662   //   ...
8663   BB = exitMBB;
8664   return BB;
8665 }
8666 
8667 MachineBasicBlock *
8668 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8669                                             MachineBasicBlock *BB,
8670                                             bool is8bit, // operation
8671                                             unsigned BinOpcode,
8672                                             unsigned CmpOpcode,
8673                                             unsigned CmpPred) const {
8674   // If we support part-word atomic mnemonics, just use them
8675   if (Subtarget.hasPartwordAtomics())
8676     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8677                             CmpOpcode, CmpPred);
8678 
8679   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8680   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8681   // In 64 bit mode we have to use 64 bits for addresses, even though the
8682   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8683   // registers without caring whether they're 32 or 64, but here we're
8684   // doing actual arithmetic on the addresses.
8685   bool is64bit = Subtarget.isPPC64();
8686   bool isLittleEndian = Subtarget.isLittleEndian();
8687   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8688 
8689   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8690   MachineFunction *F = BB->getParent();
8691   MachineFunction::iterator It = ++BB->getIterator();
8692 
8693   unsigned dest = MI.getOperand(0).getReg();
8694   unsigned ptrA = MI.getOperand(1).getReg();
8695   unsigned ptrB = MI.getOperand(2).getReg();
8696   unsigned incr = MI.getOperand(3).getReg();
8697   DebugLoc dl = MI.getDebugLoc();
8698 
8699   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8700   MachineBasicBlock *loop2MBB =
8701     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8702   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8703   F->insert(It, loopMBB);
8704   if (CmpOpcode)
8705     F->insert(It, loop2MBB);
8706   F->insert(It, exitMBB);
8707   exitMBB->splice(exitMBB->begin(), BB,
8708                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8709   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8710 
8711   MachineRegisterInfo &RegInfo = F->getRegInfo();
8712   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8713                                           : &PPC::GPRCRegClass;
8714   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8715   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8716   unsigned ShiftReg =
8717     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8718   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8719   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8720   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8721   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8722   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8723   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8724   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8725   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8726   unsigned Ptr1Reg;
8727   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8728 
8729   //  thisMBB:
8730   //   ...
8731   //   fallthrough --> loopMBB
8732   BB->addSuccessor(loopMBB);
8733 
8734   // The 4-byte load must be aligned, while a char or short may be
8735   // anywhere in the word.  Hence all this nasty bookkeeping code.
8736   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8737   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8738   //   xori shift, shift1, 24 [16]
8739   //   rlwinm ptr, ptr1, 0, 0, 29
8740   //   slw incr2, incr, shift
8741   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8742   //   slw mask, mask2, shift
8743   //  loopMBB:
8744   //   lwarx tmpDest, ptr
8745   //   add tmp, tmpDest, incr2
8746   //   andc tmp2, tmpDest, mask
8747   //   and tmp3, tmp, mask
8748   //   or tmp4, tmp3, tmp2
8749   //   stwcx. tmp4, ptr
8750   //   bne- loopMBB
8751   //   fallthrough --> exitMBB
8752   //   srw dest, tmpDest, shift
8753   if (ptrA != ZeroReg) {
8754     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8755     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8756       .addReg(ptrA).addReg(ptrB);
8757   } else {
8758     Ptr1Reg = ptrB;
8759   }
8760   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8761       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8762   if (!isLittleEndian)
8763     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8764         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8765   if (is64bit)
8766     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8767       .addReg(Ptr1Reg).addImm(0).addImm(61);
8768   else
8769     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8770       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8771   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8772       .addReg(incr).addReg(ShiftReg);
8773   if (is8bit)
8774     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8775   else {
8776     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8777     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8778   }
8779   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8780       .addReg(Mask2Reg).addReg(ShiftReg);
8781 
8782   BB = loopMBB;
8783   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8784     .addReg(ZeroReg).addReg(PtrReg);
8785   if (BinOpcode)
8786     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8787       .addReg(Incr2Reg).addReg(TmpDestReg);
8788   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8789     .addReg(TmpDestReg).addReg(MaskReg);
8790   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8791     .addReg(TmpReg).addReg(MaskReg);
8792   if (CmpOpcode) {
8793     // For unsigned comparisons, we can directly compare the shifted values.
8794     // For signed comparisons we shift and sign extend.
8795     unsigned SReg = RegInfo.createVirtualRegister(RC);
8796     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
8797       .addReg(TmpDestReg).addReg(MaskReg);
8798     unsigned ValueReg = SReg;
8799     unsigned CmpReg = Incr2Reg;
8800     if (CmpOpcode == PPC::CMPW) {
8801       ValueReg = RegInfo.createVirtualRegister(RC);
8802       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
8803         .addReg(SReg).addReg(ShiftReg);
8804       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
8805       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
8806         .addReg(ValueReg);
8807       ValueReg = ValueSReg;
8808       CmpReg = incr;
8809     }
8810     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8811       .addReg(CmpReg).addReg(ValueReg);
8812     BuildMI(BB, dl, TII->get(PPC::BCC))
8813       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8814     BB->addSuccessor(loop2MBB);
8815     BB->addSuccessor(exitMBB);
8816     BB = loop2MBB;
8817   }
8818   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8819     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8820   BuildMI(BB, dl, TII->get(PPC::STWCX))
8821     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8822   BuildMI(BB, dl, TII->get(PPC::BCC))
8823     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8824   BB->addSuccessor(loopMBB);
8825   BB->addSuccessor(exitMBB);
8826 
8827   //  exitMBB:
8828   //   ...
8829   BB = exitMBB;
8830   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8831     .addReg(ShiftReg);
8832   return BB;
8833 }
8834 
8835 llvm::MachineBasicBlock *
8836 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8837                                     MachineBasicBlock *MBB) const {
8838   DebugLoc DL = MI.getDebugLoc();
8839   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8840 
8841   MachineFunction *MF = MBB->getParent();
8842   MachineRegisterInfo &MRI = MF->getRegInfo();
8843 
8844   const BasicBlock *BB = MBB->getBasicBlock();
8845   MachineFunction::iterator I = ++MBB->getIterator();
8846 
8847   // Memory Reference
8848   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8849   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8850 
8851   unsigned DstReg = MI.getOperand(0).getReg();
8852   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8853   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8854   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8855   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8856 
8857   MVT PVT = getPointerTy(MF->getDataLayout());
8858   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8859          "Invalid Pointer Size!");
8860   // For v = setjmp(buf), we generate
8861   //
8862   // thisMBB:
8863   //  SjLjSetup mainMBB
8864   //  bl mainMBB
8865   //  v_restore = 1
8866   //  b sinkMBB
8867   //
8868   // mainMBB:
8869   //  buf[LabelOffset] = LR
8870   //  v_main = 0
8871   //
8872   // sinkMBB:
8873   //  v = phi(main, restore)
8874   //
8875 
8876   MachineBasicBlock *thisMBB = MBB;
8877   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8878   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8879   MF->insert(I, mainMBB);
8880   MF->insert(I, sinkMBB);
8881 
8882   MachineInstrBuilder MIB;
8883 
8884   // Transfer the remainder of BB and its successor edges to sinkMBB.
8885   sinkMBB->splice(sinkMBB->begin(), MBB,
8886                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8887   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8888 
8889   // Note that the structure of the jmp_buf used here is not compatible
8890   // with that used by libc, and is not designed to be. Specifically, it
8891   // stores only those 'reserved' registers that LLVM does not otherwise
8892   // understand how to spill. Also, by convention, by the time this
8893   // intrinsic is called, Clang has already stored the frame address in the
8894   // first slot of the buffer and stack address in the third. Following the
8895   // X86 target code, we'll store the jump address in the second slot. We also
8896   // need to save the TOC pointer (R2) to handle jumps between shared
8897   // libraries, and that will be stored in the fourth slot. The thread
8898   // identifier (R13) is not affected.
8899 
8900   // thisMBB:
8901   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8902   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8903   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8904 
8905   // Prepare IP either in reg.
8906   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8907   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8908   unsigned BufReg = MI.getOperand(1).getReg();
8909 
8910   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8911     setUsesTOCBasePtr(*MBB->getParent());
8912     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8913             .addReg(PPC::X2)
8914             .addImm(TOCOffset)
8915             .addReg(BufReg);
8916     MIB.setMemRefs(MMOBegin, MMOEnd);
8917   }
8918 
8919   // Naked functions never have a base pointer, and so we use r1. For all
8920   // other functions, this decision must be delayed until during PEI.
8921   unsigned BaseReg;
8922   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8923     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8924   else
8925     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8926 
8927   MIB = BuildMI(*thisMBB, MI, DL,
8928                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8929             .addReg(BaseReg)
8930             .addImm(BPOffset)
8931             .addReg(BufReg);
8932   MIB.setMemRefs(MMOBegin, MMOEnd);
8933 
8934   // Setup
8935   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8936   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8937   MIB.addRegMask(TRI->getNoPreservedMask());
8938 
8939   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8940 
8941   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8942           .addMBB(mainMBB);
8943   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8944 
8945   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8946   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8947 
8948   // mainMBB:
8949   //  mainDstReg = 0
8950   MIB =
8951       BuildMI(mainMBB, DL,
8952               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8953 
8954   // Store IP
8955   if (Subtarget.isPPC64()) {
8956     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8957             .addReg(LabelReg)
8958             .addImm(LabelOffset)
8959             .addReg(BufReg);
8960   } else {
8961     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8962             .addReg(LabelReg)
8963             .addImm(LabelOffset)
8964             .addReg(BufReg);
8965   }
8966 
8967   MIB.setMemRefs(MMOBegin, MMOEnd);
8968 
8969   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8970   mainMBB->addSuccessor(sinkMBB);
8971 
8972   // sinkMBB:
8973   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8974           TII->get(PPC::PHI), DstReg)
8975     .addReg(mainDstReg).addMBB(mainMBB)
8976     .addReg(restoreDstReg).addMBB(thisMBB);
8977 
8978   MI.eraseFromParent();
8979   return sinkMBB;
8980 }
8981 
8982 MachineBasicBlock *
8983 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8984                                      MachineBasicBlock *MBB) const {
8985   DebugLoc DL = MI.getDebugLoc();
8986   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8987 
8988   MachineFunction *MF = MBB->getParent();
8989   MachineRegisterInfo &MRI = MF->getRegInfo();
8990 
8991   // Memory Reference
8992   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8993   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8994 
8995   MVT PVT = getPointerTy(MF->getDataLayout());
8996   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8997          "Invalid Pointer Size!");
8998 
8999   const TargetRegisterClass *RC =
9000     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9001   unsigned Tmp = MRI.createVirtualRegister(RC);
9002   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9003   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9004   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9005   unsigned BP =
9006       (PVT == MVT::i64)
9007           ? PPC::X30
9008           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9009                                                               : PPC::R30);
9010 
9011   MachineInstrBuilder MIB;
9012 
9013   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9014   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9015   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9016   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9017 
9018   unsigned BufReg = MI.getOperand(0).getReg();
9019 
9020   // Reload FP (the jumped-to function may not have had a
9021   // frame pointer, and if so, then its r31 will be restored
9022   // as necessary).
9023   if (PVT == MVT::i64) {
9024     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9025             .addImm(0)
9026             .addReg(BufReg);
9027   } else {
9028     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9029             .addImm(0)
9030             .addReg(BufReg);
9031   }
9032   MIB.setMemRefs(MMOBegin, MMOEnd);
9033 
9034   // Reload IP
9035   if (PVT == MVT::i64) {
9036     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9037             .addImm(LabelOffset)
9038             .addReg(BufReg);
9039   } else {
9040     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9041             .addImm(LabelOffset)
9042             .addReg(BufReg);
9043   }
9044   MIB.setMemRefs(MMOBegin, MMOEnd);
9045 
9046   // Reload SP
9047   if (PVT == MVT::i64) {
9048     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9049             .addImm(SPOffset)
9050             .addReg(BufReg);
9051   } else {
9052     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9053             .addImm(SPOffset)
9054             .addReg(BufReg);
9055   }
9056   MIB.setMemRefs(MMOBegin, MMOEnd);
9057 
9058   // Reload BP
9059   if (PVT == MVT::i64) {
9060     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9061             .addImm(BPOffset)
9062             .addReg(BufReg);
9063   } else {
9064     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9065             .addImm(BPOffset)
9066             .addReg(BufReg);
9067   }
9068   MIB.setMemRefs(MMOBegin, MMOEnd);
9069 
9070   // Reload TOC
9071   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9072     setUsesTOCBasePtr(*MBB->getParent());
9073     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9074             .addImm(TOCOffset)
9075             .addReg(BufReg);
9076 
9077     MIB.setMemRefs(MMOBegin, MMOEnd);
9078   }
9079 
9080   // Jump
9081   BuildMI(*MBB, MI, DL,
9082           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9083   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9084 
9085   MI.eraseFromParent();
9086   return MBB;
9087 }
9088 
9089 MachineBasicBlock *
9090 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9091                                                MachineBasicBlock *BB) const {
9092   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9093       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9094     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9095         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9096       // Call lowering should have added an r2 operand to indicate a dependence
9097       // on the TOC base pointer value. It can't however, because there is no
9098       // way to mark the dependence as implicit there, and so the stackmap code
9099       // will confuse it with a regular operand. Instead, add the dependence
9100       // here.
9101       setUsesTOCBasePtr(*BB->getParent());
9102       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9103     }
9104 
9105     return emitPatchPoint(MI, BB);
9106   }
9107 
9108   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9109       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9110     return emitEHSjLjSetJmp(MI, BB);
9111   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9112              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9113     return emitEHSjLjLongJmp(MI, BB);
9114   }
9115 
9116   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9117 
9118   // To "insert" these instructions we actually have to insert their
9119   // control-flow patterns.
9120   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9121   MachineFunction::iterator It = ++BB->getIterator();
9122 
9123   MachineFunction *F = BB->getParent();
9124 
9125   if (Subtarget.hasISEL() &&
9126       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9127        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9128        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
9129     SmallVector<MachineOperand, 2> Cond;
9130     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9131         MI.getOpcode() == PPC::SELECT_CC_I8)
9132       Cond.push_back(MI.getOperand(4));
9133     else
9134       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9135     Cond.push_back(MI.getOperand(1));
9136 
9137     DebugLoc dl = MI.getDebugLoc();
9138     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9139                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9140   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9141              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9142              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9143              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9144              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9145              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9146              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9147              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9148              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9149              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9150              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9151              MI.getOpcode() == PPC::SELECT_I4 ||
9152              MI.getOpcode() == PPC::SELECT_I8 ||
9153              MI.getOpcode() == PPC::SELECT_F4 ||
9154              MI.getOpcode() == PPC::SELECT_F8 ||
9155              MI.getOpcode() == PPC::SELECT_QFRC ||
9156              MI.getOpcode() == PPC::SELECT_QSRC ||
9157              MI.getOpcode() == PPC::SELECT_QBRC ||
9158              MI.getOpcode() == PPC::SELECT_VRRC ||
9159              MI.getOpcode() == PPC::SELECT_VSFRC ||
9160              MI.getOpcode() == PPC::SELECT_VSSRC ||
9161              MI.getOpcode() == PPC::SELECT_VSRC) {
9162     // The incoming instruction knows the destination vreg to set, the
9163     // condition code register to branch on, the true/false values to
9164     // select between, and a branch opcode to use.
9165 
9166     //  thisMBB:
9167     //  ...
9168     //   TrueVal = ...
9169     //   cmpTY ccX, r1, r2
9170     //   bCC copy1MBB
9171     //   fallthrough --> copy0MBB
9172     MachineBasicBlock *thisMBB = BB;
9173     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9174     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9175     DebugLoc dl = MI.getDebugLoc();
9176     F->insert(It, copy0MBB);
9177     F->insert(It, sinkMBB);
9178 
9179     // Transfer the remainder of BB and its successor edges to sinkMBB.
9180     sinkMBB->splice(sinkMBB->begin(), BB,
9181                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9182     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9183 
9184     // Next, add the true and fallthrough blocks as its successors.
9185     BB->addSuccessor(copy0MBB);
9186     BB->addSuccessor(sinkMBB);
9187 
9188     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9189         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9190         MI.getOpcode() == PPC::SELECT_QFRC ||
9191         MI.getOpcode() == PPC::SELECT_QSRC ||
9192         MI.getOpcode() == PPC::SELECT_QBRC ||
9193         MI.getOpcode() == PPC::SELECT_VRRC ||
9194         MI.getOpcode() == PPC::SELECT_VSFRC ||
9195         MI.getOpcode() == PPC::SELECT_VSSRC ||
9196         MI.getOpcode() == PPC::SELECT_VSRC) {
9197       BuildMI(BB, dl, TII->get(PPC::BC))
9198           .addReg(MI.getOperand(1).getReg())
9199           .addMBB(sinkMBB);
9200     } else {
9201       unsigned SelectPred = MI.getOperand(4).getImm();
9202       BuildMI(BB, dl, TII->get(PPC::BCC))
9203           .addImm(SelectPred)
9204           .addReg(MI.getOperand(1).getReg())
9205           .addMBB(sinkMBB);
9206     }
9207 
9208     //  copy0MBB:
9209     //   %FalseValue = ...
9210     //   # fallthrough to sinkMBB
9211     BB = copy0MBB;
9212 
9213     // Update machine-CFG edges
9214     BB->addSuccessor(sinkMBB);
9215 
9216     //  sinkMBB:
9217     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9218     //  ...
9219     BB = sinkMBB;
9220     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9221         .addReg(MI.getOperand(3).getReg())
9222         .addMBB(copy0MBB)
9223         .addReg(MI.getOperand(2).getReg())
9224         .addMBB(thisMBB);
9225   } else if (MI.getOpcode() == PPC::ReadTB) {
9226     // To read the 64-bit time-base register on a 32-bit target, we read the
9227     // two halves. Should the counter have wrapped while it was being read, we
9228     // need to try again.
9229     // ...
9230     // readLoop:
9231     // mfspr Rx,TBU # load from TBU
9232     // mfspr Ry,TB  # load from TB
9233     // mfspr Rz,TBU # load from TBU
9234     // cmpw crX,Rx,Rz # check if 'old'='new'
9235     // bne readLoop   # branch if they're not equal
9236     // ...
9237 
9238     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9239     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9240     DebugLoc dl = MI.getDebugLoc();
9241     F->insert(It, readMBB);
9242     F->insert(It, sinkMBB);
9243 
9244     // Transfer the remainder of BB and its successor edges to sinkMBB.
9245     sinkMBB->splice(sinkMBB->begin(), BB,
9246                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9247     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9248 
9249     BB->addSuccessor(readMBB);
9250     BB = readMBB;
9251 
9252     MachineRegisterInfo &RegInfo = F->getRegInfo();
9253     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9254     unsigned LoReg = MI.getOperand(0).getReg();
9255     unsigned HiReg = MI.getOperand(1).getReg();
9256 
9257     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9258     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9259     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9260 
9261     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9262 
9263     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9264       .addReg(HiReg).addReg(ReadAgainReg);
9265     BuildMI(BB, dl, TII->get(PPC::BCC))
9266       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9267 
9268     BB->addSuccessor(readMBB);
9269     BB->addSuccessor(sinkMBB);
9270   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9271     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9272   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9273     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9274   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9275     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9276   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9277     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9278 
9279   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9280     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9281   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9282     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9283   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9284     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9286     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9287 
9288   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9289     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9290   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9291     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9293     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9295     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9296 
9297   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9298     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9299   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9300     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9301   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9302     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9304     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9305 
9306   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9307     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9308   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9309     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9311     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9313     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9314 
9315   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9316     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9317   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9318     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9320     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9322     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9323 
9324   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9325     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9326   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9327     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9328   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9329     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9330   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9331     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9332 
9333   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9334     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9335   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9336     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9337   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9338     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9339   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9340     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9341 
9342   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9343     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9344   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9345     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9347     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9348   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9349     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9350 
9351   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9352     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9353   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9354     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9356     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9357   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9358     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9359 
9360   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9361     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9362   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9363     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9364   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9365     BB = EmitAtomicBinary(MI, BB, 4, 0);
9366   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9367     BB = EmitAtomicBinary(MI, BB, 8, 0);
9368 
9369   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9370            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9371            (Subtarget.hasPartwordAtomics() &&
9372             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9373            (Subtarget.hasPartwordAtomics() &&
9374             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9375     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9376 
9377     auto LoadMnemonic = PPC::LDARX;
9378     auto StoreMnemonic = PPC::STDCX;
9379     switch (MI.getOpcode()) {
9380     default:
9381       llvm_unreachable("Compare and swap of unknown size");
9382     case PPC::ATOMIC_CMP_SWAP_I8:
9383       LoadMnemonic = PPC::LBARX;
9384       StoreMnemonic = PPC::STBCX;
9385       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9386       break;
9387     case PPC::ATOMIC_CMP_SWAP_I16:
9388       LoadMnemonic = PPC::LHARX;
9389       StoreMnemonic = PPC::STHCX;
9390       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9391       break;
9392     case PPC::ATOMIC_CMP_SWAP_I32:
9393       LoadMnemonic = PPC::LWARX;
9394       StoreMnemonic = PPC::STWCX;
9395       break;
9396     case PPC::ATOMIC_CMP_SWAP_I64:
9397       LoadMnemonic = PPC::LDARX;
9398       StoreMnemonic = PPC::STDCX;
9399       break;
9400     }
9401     unsigned dest = MI.getOperand(0).getReg();
9402     unsigned ptrA = MI.getOperand(1).getReg();
9403     unsigned ptrB = MI.getOperand(2).getReg();
9404     unsigned oldval = MI.getOperand(3).getReg();
9405     unsigned newval = MI.getOperand(4).getReg();
9406     DebugLoc dl = MI.getDebugLoc();
9407 
9408     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9409     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9410     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9411     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9412     F->insert(It, loop1MBB);
9413     F->insert(It, loop2MBB);
9414     F->insert(It, midMBB);
9415     F->insert(It, exitMBB);
9416     exitMBB->splice(exitMBB->begin(), BB,
9417                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9418     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9419 
9420     //  thisMBB:
9421     //   ...
9422     //   fallthrough --> loopMBB
9423     BB->addSuccessor(loop1MBB);
9424 
9425     // loop1MBB:
9426     //   l[bhwd]arx dest, ptr
9427     //   cmp[wd] dest, oldval
9428     //   bne- midMBB
9429     // loop2MBB:
9430     //   st[bhwd]cx. newval, ptr
9431     //   bne- loopMBB
9432     //   b exitBB
9433     // midMBB:
9434     //   st[bhwd]cx. dest, ptr
9435     // exitBB:
9436     BB = loop1MBB;
9437     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9438       .addReg(ptrA).addReg(ptrB);
9439     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9440       .addReg(oldval).addReg(dest);
9441     BuildMI(BB, dl, TII->get(PPC::BCC))
9442       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9443     BB->addSuccessor(loop2MBB);
9444     BB->addSuccessor(midMBB);
9445 
9446     BB = loop2MBB;
9447     BuildMI(BB, dl, TII->get(StoreMnemonic))
9448       .addReg(newval).addReg(ptrA).addReg(ptrB);
9449     BuildMI(BB, dl, TII->get(PPC::BCC))
9450       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9451     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9452     BB->addSuccessor(loop1MBB);
9453     BB->addSuccessor(exitMBB);
9454 
9455     BB = midMBB;
9456     BuildMI(BB, dl, TII->get(StoreMnemonic))
9457       .addReg(dest).addReg(ptrA).addReg(ptrB);
9458     BB->addSuccessor(exitMBB);
9459 
9460     //  exitMBB:
9461     //   ...
9462     BB = exitMBB;
9463   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9464              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9465     // We must use 64-bit registers for addresses when targeting 64-bit,
9466     // since we're actually doing arithmetic on them.  Other registers
9467     // can be 32-bit.
9468     bool is64bit = Subtarget.isPPC64();
9469     bool isLittleEndian = Subtarget.isLittleEndian();
9470     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9471 
9472     unsigned dest = MI.getOperand(0).getReg();
9473     unsigned ptrA = MI.getOperand(1).getReg();
9474     unsigned ptrB = MI.getOperand(2).getReg();
9475     unsigned oldval = MI.getOperand(3).getReg();
9476     unsigned newval = MI.getOperand(4).getReg();
9477     DebugLoc dl = MI.getDebugLoc();
9478 
9479     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9480     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9481     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9482     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9483     F->insert(It, loop1MBB);
9484     F->insert(It, loop2MBB);
9485     F->insert(It, midMBB);
9486     F->insert(It, exitMBB);
9487     exitMBB->splice(exitMBB->begin(), BB,
9488                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9489     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9490 
9491     MachineRegisterInfo &RegInfo = F->getRegInfo();
9492     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9493                                             : &PPC::GPRCRegClass;
9494     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9495     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9496     unsigned ShiftReg =
9497       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9498     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9499     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9500     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9501     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9502     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9503     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9504     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9505     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9506     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9507     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9508     unsigned Ptr1Reg;
9509     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9510     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9511     //  thisMBB:
9512     //   ...
9513     //   fallthrough --> loopMBB
9514     BB->addSuccessor(loop1MBB);
9515 
9516     // The 4-byte load must be aligned, while a char or short may be
9517     // anywhere in the word.  Hence all this nasty bookkeeping code.
9518     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9519     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9520     //   xori shift, shift1, 24 [16]
9521     //   rlwinm ptr, ptr1, 0, 0, 29
9522     //   slw newval2, newval, shift
9523     //   slw oldval2, oldval,shift
9524     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9525     //   slw mask, mask2, shift
9526     //   and newval3, newval2, mask
9527     //   and oldval3, oldval2, mask
9528     // loop1MBB:
9529     //   lwarx tmpDest, ptr
9530     //   and tmp, tmpDest, mask
9531     //   cmpw tmp, oldval3
9532     //   bne- midMBB
9533     // loop2MBB:
9534     //   andc tmp2, tmpDest, mask
9535     //   or tmp4, tmp2, newval3
9536     //   stwcx. tmp4, ptr
9537     //   bne- loop1MBB
9538     //   b exitBB
9539     // midMBB:
9540     //   stwcx. tmpDest, ptr
9541     // exitBB:
9542     //   srw dest, tmpDest, shift
9543     if (ptrA != ZeroReg) {
9544       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9545       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9546         .addReg(ptrA).addReg(ptrB);
9547     } else {
9548       Ptr1Reg = ptrB;
9549     }
9550     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9551         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9552     if (!isLittleEndian)
9553       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9554           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9555     if (is64bit)
9556       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9557         .addReg(Ptr1Reg).addImm(0).addImm(61);
9558     else
9559       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9560         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9561     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9562         .addReg(newval).addReg(ShiftReg);
9563     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9564         .addReg(oldval).addReg(ShiftReg);
9565     if (is8bit)
9566       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9567     else {
9568       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9569       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9570         .addReg(Mask3Reg).addImm(65535);
9571     }
9572     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9573         .addReg(Mask2Reg).addReg(ShiftReg);
9574     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9575         .addReg(NewVal2Reg).addReg(MaskReg);
9576     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9577         .addReg(OldVal2Reg).addReg(MaskReg);
9578 
9579     BB = loop1MBB;
9580     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9581         .addReg(ZeroReg).addReg(PtrReg);
9582     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9583         .addReg(TmpDestReg).addReg(MaskReg);
9584     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9585         .addReg(TmpReg).addReg(OldVal3Reg);
9586     BuildMI(BB, dl, TII->get(PPC::BCC))
9587         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9588     BB->addSuccessor(loop2MBB);
9589     BB->addSuccessor(midMBB);
9590 
9591     BB = loop2MBB;
9592     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9593         .addReg(TmpDestReg).addReg(MaskReg);
9594     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9595         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9596     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9597         .addReg(ZeroReg).addReg(PtrReg);
9598     BuildMI(BB, dl, TII->get(PPC::BCC))
9599       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9600     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9601     BB->addSuccessor(loop1MBB);
9602     BB->addSuccessor(exitMBB);
9603 
9604     BB = midMBB;
9605     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9606       .addReg(ZeroReg).addReg(PtrReg);
9607     BB->addSuccessor(exitMBB);
9608 
9609     //  exitMBB:
9610     //   ...
9611     BB = exitMBB;
9612     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9613       .addReg(ShiftReg);
9614   } else if (MI.getOpcode() == PPC::FADDrtz) {
9615     // This pseudo performs an FADD with rounding mode temporarily forced
9616     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9617     // is not modeled at the SelectionDAG level.
9618     unsigned Dest = MI.getOperand(0).getReg();
9619     unsigned Src1 = MI.getOperand(1).getReg();
9620     unsigned Src2 = MI.getOperand(2).getReg();
9621     DebugLoc dl = MI.getDebugLoc();
9622 
9623     MachineRegisterInfo &RegInfo = F->getRegInfo();
9624     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9625 
9626     // Save FPSCR value.
9627     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9628 
9629     // Set rounding mode to round-to-zero.
9630     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9631     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9632 
9633     // Perform addition.
9634     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9635 
9636     // Restore FPSCR value.
9637     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9638   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9639              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9640              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9641              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9642     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9643                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9644                           ? PPC::ANDIo8
9645                           : PPC::ANDIo;
9646     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9647                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9648 
9649     MachineRegisterInfo &RegInfo = F->getRegInfo();
9650     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9651                                                   &PPC::GPRCRegClass :
9652                                                   &PPC::G8RCRegClass);
9653 
9654     DebugLoc dl = MI.getDebugLoc();
9655     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9656         .addReg(MI.getOperand(1).getReg())
9657         .addImm(1);
9658     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9659             MI.getOperand(0).getReg())
9660         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9661   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9662     DebugLoc Dl = MI.getDebugLoc();
9663     MachineRegisterInfo &RegInfo = F->getRegInfo();
9664     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9665     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9666     return BB;
9667   } else {
9668     llvm_unreachable("Unexpected instr type to insert");
9669   }
9670 
9671   MI.eraseFromParent(); // The pseudo instruction is gone now.
9672   return BB;
9673 }
9674 
9675 //===----------------------------------------------------------------------===//
9676 // Target Optimization Hooks
9677 //===----------------------------------------------------------------------===//
9678 
9679 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9680   // For the estimates, convergence is quadratic, so we essentially double the
9681   // number of digits correct after every iteration. For both FRE and FRSQRTE,
9682   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9683   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9684   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9685   if (VT.getScalarType() == MVT::f64)
9686     RefinementSteps++;
9687   return RefinementSteps;
9688 }
9689 
9690 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9691                                            int Enabled, int &RefinementSteps,
9692                                            bool &UseOneConstNR,
9693                                            bool Reciprocal) const {
9694   EVT VT = Operand.getValueType();
9695   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9696       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9697       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9698       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9699       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9700       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9701     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9702       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9703 
9704     UseOneConstNR = true;
9705     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9706   }
9707   return SDValue();
9708 }
9709 
9710 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9711                                             int Enabled,
9712                                             int &RefinementSteps) const {
9713   EVT VT = Operand.getValueType();
9714   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9715       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9716       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9717       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9718       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9719       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9720     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9721       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9722     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9723   }
9724   return SDValue();
9725 }
9726 
9727 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9728   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9729   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9730   // enabled for division), this functionality is redundant with the default
9731   // combiner logic (once the division -> reciprocal/multiply transformation
9732   // has taken place). As a result, this matters more for older cores than for
9733   // newer ones.
9734 
9735   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9736   // reciprocal if there are two or more FDIVs (for embedded cores with only
9737   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9738   switch (Subtarget.getDarwinDirective()) {
9739   default:
9740     return 3;
9741   case PPC::DIR_440:
9742   case PPC::DIR_A2:
9743   case PPC::DIR_E500mc:
9744   case PPC::DIR_E5500:
9745     return 2;
9746   }
9747 }
9748 
9749 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9750 // collapsed, and so we need to look through chains of them.
9751 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9752                                      int64_t& Offset, SelectionDAG &DAG) {
9753   if (DAG.isBaseWithConstantOffset(Loc)) {
9754     Base = Loc.getOperand(0);
9755     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9756 
9757     // The base might itself be a base plus an offset, and if so, accumulate
9758     // that as well.
9759     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9760   }
9761 }
9762 
9763 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9764                             unsigned Bytes, int Dist,
9765                             SelectionDAG &DAG) {
9766   if (VT.getSizeInBits() / 8 != Bytes)
9767     return false;
9768 
9769   SDValue BaseLoc = Base->getBasePtr();
9770   if (Loc.getOpcode() == ISD::FrameIndex) {
9771     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9772       return false;
9773     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9774     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9775     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9776     int FS  = MFI.getObjectSize(FI);
9777     int BFS = MFI.getObjectSize(BFI);
9778     if (FS != BFS || FS != (int)Bytes) return false;
9779     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9780   }
9781 
9782   SDValue Base1 = Loc, Base2 = BaseLoc;
9783   int64_t Offset1 = 0, Offset2 = 0;
9784   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9785   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9786   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9787     return true;
9788 
9789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9790   const GlobalValue *GV1 = nullptr;
9791   const GlobalValue *GV2 = nullptr;
9792   Offset1 = 0;
9793   Offset2 = 0;
9794   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9795   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9796   if (isGA1 && isGA2 && GV1 == GV2)
9797     return Offset1 == (Offset2 + Dist*Bytes);
9798   return false;
9799 }
9800 
9801 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9802 // not enforce equality of the chain operands.
9803 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9804                             unsigned Bytes, int Dist,
9805                             SelectionDAG &DAG) {
9806   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9807     EVT VT = LS->getMemoryVT();
9808     SDValue Loc = LS->getBasePtr();
9809     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9810   }
9811 
9812   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9813     EVT VT;
9814     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9815     default: return false;
9816     case Intrinsic::ppc_qpx_qvlfd:
9817     case Intrinsic::ppc_qpx_qvlfda:
9818       VT = MVT::v4f64;
9819       break;
9820     case Intrinsic::ppc_qpx_qvlfs:
9821     case Intrinsic::ppc_qpx_qvlfsa:
9822       VT = MVT::v4f32;
9823       break;
9824     case Intrinsic::ppc_qpx_qvlfcd:
9825     case Intrinsic::ppc_qpx_qvlfcda:
9826       VT = MVT::v2f64;
9827       break;
9828     case Intrinsic::ppc_qpx_qvlfcs:
9829     case Intrinsic::ppc_qpx_qvlfcsa:
9830       VT = MVT::v2f32;
9831       break;
9832     case Intrinsic::ppc_qpx_qvlfiwa:
9833     case Intrinsic::ppc_qpx_qvlfiwz:
9834     case Intrinsic::ppc_altivec_lvx:
9835     case Intrinsic::ppc_altivec_lvxl:
9836     case Intrinsic::ppc_vsx_lxvw4x:
9837     case Intrinsic::ppc_vsx_lxvw4x_be:
9838       VT = MVT::v4i32;
9839       break;
9840     case Intrinsic::ppc_vsx_lxvd2x:
9841     case Intrinsic::ppc_vsx_lxvd2x_be:
9842       VT = MVT::v2f64;
9843       break;
9844     case Intrinsic::ppc_altivec_lvebx:
9845       VT = MVT::i8;
9846       break;
9847     case Intrinsic::ppc_altivec_lvehx:
9848       VT = MVT::i16;
9849       break;
9850     case Intrinsic::ppc_altivec_lvewx:
9851       VT = MVT::i32;
9852       break;
9853     }
9854 
9855     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9856   }
9857 
9858   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9859     EVT VT;
9860     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9861     default: return false;
9862     case Intrinsic::ppc_qpx_qvstfd:
9863     case Intrinsic::ppc_qpx_qvstfda:
9864       VT = MVT::v4f64;
9865       break;
9866     case Intrinsic::ppc_qpx_qvstfs:
9867     case Intrinsic::ppc_qpx_qvstfsa:
9868       VT = MVT::v4f32;
9869       break;
9870     case Intrinsic::ppc_qpx_qvstfcd:
9871     case Intrinsic::ppc_qpx_qvstfcda:
9872       VT = MVT::v2f64;
9873       break;
9874     case Intrinsic::ppc_qpx_qvstfcs:
9875     case Intrinsic::ppc_qpx_qvstfcsa:
9876       VT = MVT::v2f32;
9877       break;
9878     case Intrinsic::ppc_qpx_qvstfiw:
9879     case Intrinsic::ppc_qpx_qvstfiwa:
9880     case Intrinsic::ppc_altivec_stvx:
9881     case Intrinsic::ppc_altivec_stvxl:
9882     case Intrinsic::ppc_vsx_stxvw4x:
9883       VT = MVT::v4i32;
9884       break;
9885     case Intrinsic::ppc_vsx_stxvd2x:
9886       VT = MVT::v2f64;
9887       break;
9888     case Intrinsic::ppc_vsx_stxvw4x_be:
9889       VT = MVT::v4i32;
9890       break;
9891     case Intrinsic::ppc_vsx_stxvd2x_be:
9892       VT = MVT::v2f64;
9893       break;
9894     case Intrinsic::ppc_altivec_stvebx:
9895       VT = MVT::i8;
9896       break;
9897     case Intrinsic::ppc_altivec_stvehx:
9898       VT = MVT::i16;
9899       break;
9900     case Intrinsic::ppc_altivec_stvewx:
9901       VT = MVT::i32;
9902       break;
9903     }
9904 
9905     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9906   }
9907 
9908   return false;
9909 }
9910 
9911 // Return true is there is a nearyby consecutive load to the one provided
9912 // (regardless of alignment). We search up and down the chain, looking though
9913 // token factors and other loads (but nothing else). As a result, a true result
9914 // indicates that it is safe to create a new consecutive load adjacent to the
9915 // load provided.
9916 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9917   SDValue Chain = LD->getChain();
9918   EVT VT = LD->getMemoryVT();
9919 
9920   SmallSet<SDNode *, 16> LoadRoots;
9921   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9922   SmallSet<SDNode *, 16> Visited;
9923 
9924   // First, search up the chain, branching to follow all token-factor operands.
9925   // If we find a consecutive load, then we're done, otherwise, record all
9926   // nodes just above the top-level loads and token factors.
9927   while (!Queue.empty()) {
9928     SDNode *ChainNext = Queue.pop_back_val();
9929     if (!Visited.insert(ChainNext).second)
9930       continue;
9931 
9932     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9933       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9934         return true;
9935 
9936       if (!Visited.count(ChainLD->getChain().getNode()))
9937         Queue.push_back(ChainLD->getChain().getNode());
9938     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9939       for (const SDUse &O : ChainNext->ops())
9940         if (!Visited.count(O.getNode()))
9941           Queue.push_back(O.getNode());
9942     } else
9943       LoadRoots.insert(ChainNext);
9944   }
9945 
9946   // Second, search down the chain, starting from the top-level nodes recorded
9947   // in the first phase. These top-level nodes are the nodes just above all
9948   // loads and token factors. Starting with their uses, recursively look though
9949   // all loads (just the chain uses) and token factors to find a consecutive
9950   // load.
9951   Visited.clear();
9952   Queue.clear();
9953 
9954   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9955        IE = LoadRoots.end(); I != IE; ++I) {
9956     Queue.push_back(*I);
9957 
9958     while (!Queue.empty()) {
9959       SDNode *LoadRoot = Queue.pop_back_val();
9960       if (!Visited.insert(LoadRoot).second)
9961         continue;
9962 
9963       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9964         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9965           return true;
9966 
9967       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9968            UE = LoadRoot->use_end(); UI != UE; ++UI)
9969         if (((isa<MemSDNode>(*UI) &&
9970             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9971             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9972           Queue.push_back(*UI);
9973     }
9974   }
9975 
9976   return false;
9977 }
9978 
9979 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9980                                                   DAGCombinerInfo &DCI) const {
9981   SelectionDAG &DAG = DCI.DAG;
9982   SDLoc dl(N);
9983 
9984   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9985   // If we're tracking CR bits, we need to be careful that we don't have:
9986   //   trunc(binary-ops(zext(x), zext(y)))
9987   // or
9988   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9989   // such that we're unnecessarily moving things into GPRs when it would be
9990   // better to keep them in CR bits.
9991 
9992   // Note that trunc here can be an actual i1 trunc, or can be the effective
9993   // truncation that comes from a setcc or select_cc.
9994   if (N->getOpcode() == ISD::TRUNCATE &&
9995       N->getValueType(0) != MVT::i1)
9996     return SDValue();
9997 
9998   if (N->getOperand(0).getValueType() != MVT::i32 &&
9999       N->getOperand(0).getValueType() != MVT::i64)
10000     return SDValue();
10001 
10002   if (N->getOpcode() == ISD::SETCC ||
10003       N->getOpcode() == ISD::SELECT_CC) {
10004     // If we're looking at a comparison, then we need to make sure that the
10005     // high bits (all except for the first) don't matter the result.
10006     ISD::CondCode CC =
10007       cast<CondCodeSDNode>(N->getOperand(
10008         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10009     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10010 
10011     if (ISD::isSignedIntSetCC(CC)) {
10012       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10013           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10014         return SDValue();
10015     } else if (ISD::isUnsignedIntSetCC(CC)) {
10016       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10017                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10018           !DAG.MaskedValueIsZero(N->getOperand(1),
10019                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10020         return SDValue();
10021     } else {
10022       // This is neither a signed nor an unsigned comparison, just make sure
10023       // that the high bits are equal.
10024       APInt Op1Zero, Op1One;
10025       APInt Op2Zero, Op2One;
10026       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
10027       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
10028 
10029       // We don't really care about what is known about the first bit (if
10030       // anything), so clear it in all masks prior to comparing them.
10031       Op1Zero.clearBit(0); Op1One.clearBit(0);
10032       Op2Zero.clearBit(0); Op2One.clearBit(0);
10033 
10034       if (Op1Zero != Op2Zero || Op1One != Op2One)
10035         return SDValue();
10036     }
10037   }
10038 
10039   // We now know that the higher-order bits are irrelevant, we just need to
10040   // make sure that all of the intermediate operations are bit operations, and
10041   // all inputs are extensions.
10042   if (N->getOperand(0).getOpcode() != ISD::AND &&
10043       N->getOperand(0).getOpcode() != ISD::OR  &&
10044       N->getOperand(0).getOpcode() != ISD::XOR &&
10045       N->getOperand(0).getOpcode() != ISD::SELECT &&
10046       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10047       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10048       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10049       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10050       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10051     return SDValue();
10052 
10053   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10054       N->getOperand(1).getOpcode() != ISD::AND &&
10055       N->getOperand(1).getOpcode() != ISD::OR  &&
10056       N->getOperand(1).getOpcode() != ISD::XOR &&
10057       N->getOperand(1).getOpcode() != ISD::SELECT &&
10058       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10059       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10060       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10061       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10062       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10063     return SDValue();
10064 
10065   SmallVector<SDValue, 4> Inputs;
10066   SmallVector<SDValue, 8> BinOps, PromOps;
10067   SmallPtrSet<SDNode *, 16> Visited;
10068 
10069   for (unsigned i = 0; i < 2; ++i) {
10070     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10071           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10072           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10073           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10074         isa<ConstantSDNode>(N->getOperand(i)))
10075       Inputs.push_back(N->getOperand(i));
10076     else
10077       BinOps.push_back(N->getOperand(i));
10078 
10079     if (N->getOpcode() == ISD::TRUNCATE)
10080       break;
10081   }
10082 
10083   // Visit all inputs, collect all binary operations (and, or, xor and
10084   // select) that are all fed by extensions.
10085   while (!BinOps.empty()) {
10086     SDValue BinOp = BinOps.back();
10087     BinOps.pop_back();
10088 
10089     if (!Visited.insert(BinOp.getNode()).second)
10090       continue;
10091 
10092     PromOps.push_back(BinOp);
10093 
10094     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10095       // The condition of the select is not promoted.
10096       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10097         continue;
10098       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10099         continue;
10100 
10101       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10102             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10103             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10104            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10105           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10106         Inputs.push_back(BinOp.getOperand(i));
10107       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10108                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10109                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10110                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10111                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10112                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10113                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10114                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10115                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10116         BinOps.push_back(BinOp.getOperand(i));
10117       } else {
10118         // We have an input that is not an extension or another binary
10119         // operation; we'll abort this transformation.
10120         return SDValue();
10121       }
10122     }
10123   }
10124 
10125   // Make sure that this is a self-contained cluster of operations (which
10126   // is not quite the same thing as saying that everything has only one
10127   // use).
10128   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10129     if (isa<ConstantSDNode>(Inputs[i]))
10130       continue;
10131 
10132     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10133                               UE = Inputs[i].getNode()->use_end();
10134          UI != UE; ++UI) {
10135       SDNode *User = *UI;
10136       if (User != N && !Visited.count(User))
10137         return SDValue();
10138 
10139       // Make sure that we're not going to promote the non-output-value
10140       // operand(s) or SELECT or SELECT_CC.
10141       // FIXME: Although we could sometimes handle this, and it does occur in
10142       // practice that one of the condition inputs to the select is also one of
10143       // the outputs, we currently can't deal with this.
10144       if (User->getOpcode() == ISD::SELECT) {
10145         if (User->getOperand(0) == Inputs[i])
10146           return SDValue();
10147       } else if (User->getOpcode() == ISD::SELECT_CC) {
10148         if (User->getOperand(0) == Inputs[i] ||
10149             User->getOperand(1) == Inputs[i])
10150           return SDValue();
10151       }
10152     }
10153   }
10154 
10155   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10156     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10157                               UE = PromOps[i].getNode()->use_end();
10158          UI != UE; ++UI) {
10159       SDNode *User = *UI;
10160       if (User != N && !Visited.count(User))
10161         return SDValue();
10162 
10163       // Make sure that we're not going to promote the non-output-value
10164       // operand(s) or SELECT or SELECT_CC.
10165       // FIXME: Although we could sometimes handle this, and it does occur in
10166       // practice that one of the condition inputs to the select is also one of
10167       // the outputs, we currently can't deal with this.
10168       if (User->getOpcode() == ISD::SELECT) {
10169         if (User->getOperand(0) == PromOps[i])
10170           return SDValue();
10171       } else if (User->getOpcode() == ISD::SELECT_CC) {
10172         if (User->getOperand(0) == PromOps[i] ||
10173             User->getOperand(1) == PromOps[i])
10174           return SDValue();
10175       }
10176     }
10177   }
10178 
10179   // Replace all inputs with the extension operand.
10180   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10181     // Constants may have users outside the cluster of to-be-promoted nodes,
10182     // and so we need to replace those as we do the promotions.
10183     if (isa<ConstantSDNode>(Inputs[i]))
10184       continue;
10185     else
10186       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10187   }
10188 
10189   std::list<HandleSDNode> PromOpHandles;
10190   for (auto &PromOp : PromOps)
10191     PromOpHandles.emplace_back(PromOp);
10192 
10193   // Replace all operations (these are all the same, but have a different
10194   // (i1) return type). DAG.getNode will validate that the types of
10195   // a binary operator match, so go through the list in reverse so that
10196   // we've likely promoted both operands first. Any intermediate truncations or
10197   // extensions disappear.
10198   while (!PromOpHandles.empty()) {
10199     SDValue PromOp = PromOpHandles.back().getValue();
10200     PromOpHandles.pop_back();
10201 
10202     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10203         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10204         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10205         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10206       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10207           PromOp.getOperand(0).getValueType() != MVT::i1) {
10208         // The operand is not yet ready (see comment below).
10209         PromOpHandles.emplace_front(PromOp);
10210         continue;
10211       }
10212 
10213       SDValue RepValue = PromOp.getOperand(0);
10214       if (isa<ConstantSDNode>(RepValue))
10215         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10216 
10217       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10218       continue;
10219     }
10220 
10221     unsigned C;
10222     switch (PromOp.getOpcode()) {
10223     default:             C = 0; break;
10224     case ISD::SELECT:    C = 1; break;
10225     case ISD::SELECT_CC: C = 2; break;
10226     }
10227 
10228     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10229          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10230         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10231          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10232       // The to-be-promoted operands of this node have not yet been
10233       // promoted (this should be rare because we're going through the
10234       // list backward, but if one of the operands has several users in
10235       // this cluster of to-be-promoted nodes, it is possible).
10236       PromOpHandles.emplace_front(PromOp);
10237       continue;
10238     }
10239 
10240     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10241                                 PromOp.getNode()->op_end());
10242 
10243     // If there are any constant inputs, make sure they're replaced now.
10244     for (unsigned i = 0; i < 2; ++i)
10245       if (isa<ConstantSDNode>(Ops[C+i]))
10246         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10247 
10248     DAG.ReplaceAllUsesOfValueWith(PromOp,
10249       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10250   }
10251 
10252   // Now we're left with the initial truncation itself.
10253   if (N->getOpcode() == ISD::TRUNCATE)
10254     return N->getOperand(0);
10255 
10256   // Otherwise, this is a comparison. The operands to be compared have just
10257   // changed type (to i1), but everything else is the same.
10258   return SDValue(N, 0);
10259 }
10260 
10261 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10262                                                   DAGCombinerInfo &DCI) const {
10263   SelectionDAG &DAG = DCI.DAG;
10264   SDLoc dl(N);
10265 
10266   // If we're tracking CR bits, we need to be careful that we don't have:
10267   //   zext(binary-ops(trunc(x), trunc(y)))
10268   // or
10269   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10270   // such that we're unnecessarily moving things into CR bits that can more
10271   // efficiently stay in GPRs. Note that if we're not certain that the high
10272   // bits are set as required by the final extension, we still may need to do
10273   // some masking to get the proper behavior.
10274 
10275   // This same functionality is important on PPC64 when dealing with
10276   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10277   // the return values of functions. Because it is so similar, it is handled
10278   // here as well.
10279 
10280   if (N->getValueType(0) != MVT::i32 &&
10281       N->getValueType(0) != MVT::i64)
10282     return SDValue();
10283 
10284   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10285         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10286     return SDValue();
10287 
10288   if (N->getOperand(0).getOpcode() != ISD::AND &&
10289       N->getOperand(0).getOpcode() != ISD::OR  &&
10290       N->getOperand(0).getOpcode() != ISD::XOR &&
10291       N->getOperand(0).getOpcode() != ISD::SELECT &&
10292       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10293     return SDValue();
10294 
10295   SmallVector<SDValue, 4> Inputs;
10296   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10297   SmallPtrSet<SDNode *, 16> Visited;
10298 
10299   // Visit all inputs, collect all binary operations (and, or, xor and
10300   // select) that are all fed by truncations.
10301   while (!BinOps.empty()) {
10302     SDValue BinOp = BinOps.back();
10303     BinOps.pop_back();
10304 
10305     if (!Visited.insert(BinOp.getNode()).second)
10306       continue;
10307 
10308     PromOps.push_back(BinOp);
10309 
10310     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10311       // The condition of the select is not promoted.
10312       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10313         continue;
10314       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10315         continue;
10316 
10317       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10318           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10319         Inputs.push_back(BinOp.getOperand(i));
10320       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10321                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10322                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10323                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10324                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10325         BinOps.push_back(BinOp.getOperand(i));
10326       } else {
10327         // We have an input that is not a truncation or another binary
10328         // operation; we'll abort this transformation.
10329         return SDValue();
10330       }
10331     }
10332   }
10333 
10334   // The operands of a select that must be truncated when the select is
10335   // promoted because the operand is actually part of the to-be-promoted set.
10336   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10337 
10338   // Make sure that this is a self-contained cluster of operations (which
10339   // is not quite the same thing as saying that everything has only one
10340   // use).
10341   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10342     if (isa<ConstantSDNode>(Inputs[i]))
10343       continue;
10344 
10345     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10346                               UE = Inputs[i].getNode()->use_end();
10347          UI != UE; ++UI) {
10348       SDNode *User = *UI;
10349       if (User != N && !Visited.count(User))
10350         return SDValue();
10351 
10352       // If we're going to promote the non-output-value operand(s) or SELECT or
10353       // SELECT_CC, record them for truncation.
10354       if (User->getOpcode() == ISD::SELECT) {
10355         if (User->getOperand(0) == Inputs[i])
10356           SelectTruncOp[0].insert(std::make_pair(User,
10357                                     User->getOperand(0).getValueType()));
10358       } else if (User->getOpcode() == ISD::SELECT_CC) {
10359         if (User->getOperand(0) == Inputs[i])
10360           SelectTruncOp[0].insert(std::make_pair(User,
10361                                     User->getOperand(0).getValueType()));
10362         if (User->getOperand(1) == Inputs[i])
10363           SelectTruncOp[1].insert(std::make_pair(User,
10364                                     User->getOperand(1).getValueType()));
10365       }
10366     }
10367   }
10368 
10369   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10370     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10371                               UE = PromOps[i].getNode()->use_end();
10372          UI != UE; ++UI) {
10373       SDNode *User = *UI;
10374       if (User != N && !Visited.count(User))
10375         return SDValue();
10376 
10377       // If we're going to promote the non-output-value operand(s) or SELECT or
10378       // SELECT_CC, record them for truncation.
10379       if (User->getOpcode() == ISD::SELECT) {
10380         if (User->getOperand(0) == PromOps[i])
10381           SelectTruncOp[0].insert(std::make_pair(User,
10382                                     User->getOperand(0).getValueType()));
10383       } else if (User->getOpcode() == ISD::SELECT_CC) {
10384         if (User->getOperand(0) == PromOps[i])
10385           SelectTruncOp[0].insert(std::make_pair(User,
10386                                     User->getOperand(0).getValueType()));
10387         if (User->getOperand(1) == PromOps[i])
10388           SelectTruncOp[1].insert(std::make_pair(User,
10389                                     User->getOperand(1).getValueType()));
10390       }
10391     }
10392   }
10393 
10394   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10395   bool ReallyNeedsExt = false;
10396   if (N->getOpcode() != ISD::ANY_EXTEND) {
10397     // If all of the inputs are not already sign/zero extended, then
10398     // we'll still need to do that at the end.
10399     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10400       if (isa<ConstantSDNode>(Inputs[i]))
10401         continue;
10402 
10403       unsigned OpBits =
10404         Inputs[i].getOperand(0).getValueSizeInBits();
10405       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10406 
10407       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10408            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10409                                   APInt::getHighBitsSet(OpBits,
10410                                                         OpBits-PromBits))) ||
10411           (N->getOpcode() == ISD::SIGN_EXTEND &&
10412            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10413              (OpBits-(PromBits-1)))) {
10414         ReallyNeedsExt = true;
10415         break;
10416       }
10417     }
10418   }
10419 
10420   // Replace all inputs, either with the truncation operand, or a
10421   // truncation or extension to the final output type.
10422   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10423     // Constant inputs need to be replaced with the to-be-promoted nodes that
10424     // use them because they might have users outside of the cluster of
10425     // promoted nodes.
10426     if (isa<ConstantSDNode>(Inputs[i]))
10427       continue;
10428 
10429     SDValue InSrc = Inputs[i].getOperand(0);
10430     if (Inputs[i].getValueType() == N->getValueType(0))
10431       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10432     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10433       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10434         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10435     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10436       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10437         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10438     else
10439       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10440         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10441   }
10442 
10443   std::list<HandleSDNode> PromOpHandles;
10444   for (auto &PromOp : PromOps)
10445     PromOpHandles.emplace_back(PromOp);
10446 
10447   // Replace all operations (these are all the same, but have a different
10448   // (promoted) return type). DAG.getNode will validate that the types of
10449   // a binary operator match, so go through the list in reverse so that
10450   // we've likely promoted both operands first.
10451   while (!PromOpHandles.empty()) {
10452     SDValue PromOp = PromOpHandles.back().getValue();
10453     PromOpHandles.pop_back();
10454 
10455     unsigned C;
10456     switch (PromOp.getOpcode()) {
10457     default:             C = 0; break;
10458     case ISD::SELECT:    C = 1; break;
10459     case ISD::SELECT_CC: C = 2; break;
10460     }
10461 
10462     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10463          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10464         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10465          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10466       // The to-be-promoted operands of this node have not yet been
10467       // promoted (this should be rare because we're going through the
10468       // list backward, but if one of the operands has several users in
10469       // this cluster of to-be-promoted nodes, it is possible).
10470       PromOpHandles.emplace_front(PromOp);
10471       continue;
10472     }
10473 
10474     // For SELECT and SELECT_CC nodes, we do a similar check for any
10475     // to-be-promoted comparison inputs.
10476     if (PromOp.getOpcode() == ISD::SELECT ||
10477         PromOp.getOpcode() == ISD::SELECT_CC) {
10478       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10479            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10480           (SelectTruncOp[1].count(PromOp.getNode()) &&
10481            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10482         PromOpHandles.emplace_front(PromOp);
10483         continue;
10484       }
10485     }
10486 
10487     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10488                                 PromOp.getNode()->op_end());
10489 
10490     // If this node has constant inputs, then they'll need to be promoted here.
10491     for (unsigned i = 0; i < 2; ++i) {
10492       if (!isa<ConstantSDNode>(Ops[C+i]))
10493         continue;
10494       if (Ops[C+i].getValueType() == N->getValueType(0))
10495         continue;
10496 
10497       if (N->getOpcode() == ISD::SIGN_EXTEND)
10498         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10499       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10500         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10501       else
10502         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10503     }
10504 
10505     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10506     // truncate them again to the original value type.
10507     if (PromOp.getOpcode() == ISD::SELECT ||
10508         PromOp.getOpcode() == ISD::SELECT_CC) {
10509       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10510       if (SI0 != SelectTruncOp[0].end())
10511         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10512       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10513       if (SI1 != SelectTruncOp[1].end())
10514         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10515     }
10516 
10517     DAG.ReplaceAllUsesOfValueWith(PromOp,
10518       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10519   }
10520 
10521   // Now we're left with the initial extension itself.
10522   if (!ReallyNeedsExt)
10523     return N->getOperand(0);
10524 
10525   // To zero extend, just mask off everything except for the first bit (in the
10526   // i1 case).
10527   if (N->getOpcode() == ISD::ZERO_EXTEND)
10528     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10529                        DAG.getConstant(APInt::getLowBitsSet(
10530                                          N->getValueSizeInBits(0), PromBits),
10531                                        dl, N->getValueType(0)));
10532 
10533   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10534          "Invalid extension type");
10535   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10536   SDValue ShiftCst =
10537       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10538   return DAG.getNode(
10539       ISD::SRA, dl, N->getValueType(0),
10540       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10541       ShiftCst);
10542 }
10543 
10544 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10545                                                  DAGCombinerInfo &DCI) const {
10546   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10547          "Should be called with a BUILD_VECTOR node");
10548 
10549   SelectionDAG &DAG = DCI.DAG;
10550   SDLoc dl(N);
10551   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10552     return SDValue();
10553 
10554   // Looking for:
10555   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10556   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10557       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10558     return SDValue();
10559   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10560       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10561     return SDValue();
10562   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10563     return SDValue();
10564 
10565   SDValue Ext1 = N->getOperand(0).getOperand(0);
10566   SDValue Ext2 = N->getOperand(1).getOperand(0);
10567   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10568      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10569     return SDValue();
10570 
10571   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10572   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10573   if (!Ext1Op || !Ext2Op)
10574     return SDValue();
10575   if (Ext1.getValueType() != MVT::i32 ||
10576       Ext2.getValueType() != MVT::i32)
10577   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10578     return SDValue();
10579 
10580   int FirstElem = Ext1Op->getZExtValue();
10581   int SecondElem = Ext2Op->getZExtValue();
10582   int SubvecIdx;
10583   if (FirstElem == 0 && SecondElem == 1)
10584     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10585   else if (FirstElem == 2 && SecondElem == 3)
10586     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10587   else
10588     return SDValue();
10589 
10590   SDValue SrcVec = Ext1.getOperand(0);
10591   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10592     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10593   return DAG.getNode(NodeType, dl, MVT::v2f64,
10594                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10595 }
10596 
10597 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10598                                               DAGCombinerInfo &DCI) const {
10599   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10600           N->getOpcode() == ISD::UINT_TO_FP) &&
10601          "Need an int -> FP conversion node here");
10602 
10603   if (useSoftFloat() || !Subtarget.has64BitSupport())
10604     return SDValue();
10605 
10606   SelectionDAG &DAG = DCI.DAG;
10607   SDLoc dl(N);
10608   SDValue Op(N, 0);
10609 
10610   SDValue FirstOperand(Op.getOperand(0));
10611   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
10612     (FirstOperand.getValueType() == MVT::i8 ||
10613      FirstOperand.getValueType() == MVT::i16);
10614   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
10615     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
10616     bool DstDouble = Op.getValueType() == MVT::f64;
10617     unsigned ConvOp = Signed ?
10618       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
10619       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
10620     SDValue WidthConst =
10621       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
10622                             dl, false);
10623     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
10624     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
10625     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
10626                                          DAG.getVTList(MVT::f64, MVT::Other),
10627                                          Ops, MVT::i8, LDN->getMemOperand());
10628 
10629     // For signed conversion, we need to sign-extend the value in the VSR
10630     if (Signed) {
10631       SDValue ExtOps[] = { Ld, WidthConst };
10632       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
10633       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
10634     } else
10635       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
10636   }
10637 
10638   // Don't handle ppc_fp128 here or i1 conversions.
10639   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10640     return SDValue();
10641   if (Op.getOperand(0).getValueType() == MVT::i1)
10642     return SDValue();
10643 
10644   // For i32 intermediate values, unfortunately, the conversion functions
10645   // leave the upper 32 bits of the value are undefined. Within the set of
10646   // scalar instructions, we have no method for zero- or sign-extending the
10647   // value. Thus, we cannot handle i32 intermediate values here.
10648   if (Op.getOperand(0).getValueType() == MVT::i32)
10649     return SDValue();
10650 
10651   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10652          "UINT_TO_FP is supported only with FPCVT");
10653 
10654   // If we have FCFIDS, then use it when converting to single-precision.
10655   // Otherwise, convert to double-precision and then round.
10656   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10657                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10658                                                             : PPCISD::FCFIDS)
10659                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10660                                                             : PPCISD::FCFID);
10661   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10662                   ? MVT::f32
10663                   : MVT::f64;
10664 
10665   // If we're converting from a float, to an int, and back to a float again,
10666   // then we don't need the store/load pair at all.
10667   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10668        Subtarget.hasFPCVT()) ||
10669       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10670     SDValue Src = Op.getOperand(0).getOperand(0);
10671     if (Src.getValueType() == MVT::f32) {
10672       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10673       DCI.AddToWorklist(Src.getNode());
10674     } else if (Src.getValueType() != MVT::f64) {
10675       // Make sure that we don't pick up a ppc_fp128 source value.
10676       return SDValue();
10677     }
10678 
10679     unsigned FCTOp =
10680       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10681                                                         PPCISD::FCTIDUZ;
10682 
10683     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10684     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10685 
10686     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10687       FP = DAG.getNode(ISD::FP_ROUND, dl,
10688                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10689       DCI.AddToWorklist(FP.getNode());
10690     }
10691 
10692     return FP;
10693   }
10694 
10695   return SDValue();
10696 }
10697 
10698 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10699 // builtins) into loads with swaps.
10700 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10701                                               DAGCombinerInfo &DCI) const {
10702   SelectionDAG &DAG = DCI.DAG;
10703   SDLoc dl(N);
10704   SDValue Chain;
10705   SDValue Base;
10706   MachineMemOperand *MMO;
10707 
10708   switch (N->getOpcode()) {
10709   default:
10710     llvm_unreachable("Unexpected opcode for little endian VSX load");
10711   case ISD::LOAD: {
10712     LoadSDNode *LD = cast<LoadSDNode>(N);
10713     Chain = LD->getChain();
10714     Base = LD->getBasePtr();
10715     MMO = LD->getMemOperand();
10716     // If the MMO suggests this isn't a load of a full vector, leave
10717     // things alone.  For a built-in, we have to make the change for
10718     // correctness, so if there is a size problem that will be a bug.
10719     if (MMO->getSize() < 16)
10720       return SDValue();
10721     break;
10722   }
10723   case ISD::INTRINSIC_W_CHAIN: {
10724     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10725     Chain = Intrin->getChain();
10726     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10727     // us what we want. Get operand 2 instead.
10728     Base = Intrin->getOperand(2);
10729     MMO = Intrin->getMemOperand();
10730     break;
10731   }
10732   }
10733 
10734   MVT VecTy = N->getValueType(0).getSimpleVT();
10735   SDValue LoadOps[] = { Chain, Base };
10736   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10737                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10738                                          LoadOps, MVT::v2f64, MMO);
10739 
10740   DCI.AddToWorklist(Load.getNode());
10741   Chain = Load.getValue(1);
10742   SDValue Swap = DAG.getNode(
10743       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10744   DCI.AddToWorklist(Swap.getNode());
10745 
10746   // Add a bitcast if the resulting load type doesn't match v2f64.
10747   if (VecTy != MVT::v2f64) {
10748     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10749     DCI.AddToWorklist(N.getNode());
10750     // Package {bitcast value, swap's chain} to match Load's shape.
10751     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10752                        N, Swap.getValue(1));
10753   }
10754 
10755   return Swap;
10756 }
10757 
10758 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10759 // builtins) into stores with swaps.
10760 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10761                                                DAGCombinerInfo &DCI) const {
10762   SelectionDAG &DAG = DCI.DAG;
10763   SDLoc dl(N);
10764   SDValue Chain;
10765   SDValue Base;
10766   unsigned SrcOpnd;
10767   MachineMemOperand *MMO;
10768 
10769   switch (N->getOpcode()) {
10770   default:
10771     llvm_unreachable("Unexpected opcode for little endian VSX store");
10772   case ISD::STORE: {
10773     StoreSDNode *ST = cast<StoreSDNode>(N);
10774     Chain = ST->getChain();
10775     Base = ST->getBasePtr();
10776     MMO = ST->getMemOperand();
10777     SrcOpnd = 1;
10778     // If the MMO suggests this isn't a store of a full vector, leave
10779     // things alone.  For a built-in, we have to make the change for
10780     // correctness, so if there is a size problem that will be a bug.
10781     if (MMO->getSize() < 16)
10782       return SDValue();
10783     break;
10784   }
10785   case ISD::INTRINSIC_VOID: {
10786     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10787     Chain = Intrin->getChain();
10788     // Intrin->getBasePtr() oddly does not get what we want.
10789     Base = Intrin->getOperand(3);
10790     MMO = Intrin->getMemOperand();
10791     SrcOpnd = 2;
10792     break;
10793   }
10794   }
10795 
10796   SDValue Src = N->getOperand(SrcOpnd);
10797   MVT VecTy = Src.getValueType().getSimpleVT();
10798 
10799   // All stores are done as v2f64 and possible bit cast.
10800   if (VecTy != MVT::v2f64) {
10801     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10802     DCI.AddToWorklist(Src.getNode());
10803   }
10804 
10805   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10806                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10807   DCI.AddToWorklist(Swap.getNode());
10808   Chain = Swap.getValue(1);
10809   SDValue StoreOps[] = { Chain, Swap, Base };
10810   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10811                                           DAG.getVTList(MVT::Other),
10812                                           StoreOps, VecTy, MMO);
10813   DCI.AddToWorklist(Store.getNode());
10814   return Store;
10815 }
10816 
10817 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10818                                              DAGCombinerInfo &DCI) const {
10819   SelectionDAG &DAG = DCI.DAG;
10820   SDLoc dl(N);
10821   switch (N->getOpcode()) {
10822   default: break;
10823   case PPCISD::SHL:
10824     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10825         return N->getOperand(0);
10826     break;
10827   case PPCISD::SRL:
10828     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10829         return N->getOperand(0);
10830     break;
10831   case PPCISD::SRA:
10832     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10833       if (C->isNullValue() ||   //  0 >>s V -> 0.
10834           C->isAllOnesValue())    // -1 >>s V -> -1.
10835         return N->getOperand(0);
10836     }
10837     break;
10838   case ISD::SIGN_EXTEND:
10839   case ISD::ZERO_EXTEND:
10840   case ISD::ANY_EXTEND:
10841     return DAGCombineExtBoolTrunc(N, DCI);
10842   case ISD::TRUNCATE:
10843   case ISD::SETCC:
10844   case ISD::SELECT_CC:
10845     return DAGCombineTruncBoolExt(N, DCI);
10846   case ISD::SINT_TO_FP:
10847   case ISD::UINT_TO_FP:
10848     return combineFPToIntToFP(N, DCI);
10849   case ISD::STORE: {
10850     EVT Op1VT = N->getOperand(1).getValueType();
10851     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
10852       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
10853 
10854     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10855     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10856         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10857         ValidTypeForStoreFltAsInt &&
10858         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10859       SDValue Val = N->getOperand(1).getOperand(0);
10860       if (Val.getValueType() == MVT::f32) {
10861         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10862         DCI.AddToWorklist(Val.getNode());
10863       }
10864       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10865       DCI.AddToWorklist(Val.getNode());
10866 
10867       if (Op1VT == MVT::i32) {
10868         SDValue Ops[] = {
10869           N->getOperand(0), Val, N->getOperand(2),
10870           DAG.getValueType(N->getOperand(1).getValueType())
10871         };
10872 
10873         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10874                 DAG.getVTList(MVT::Other), Ops,
10875                 cast<StoreSDNode>(N)->getMemoryVT(),
10876                 cast<StoreSDNode>(N)->getMemOperand());
10877       } else {
10878         unsigned WidthInBytes =
10879           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
10880         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
10881 
10882         SDValue Ops[] = {
10883           N->getOperand(0), Val, N->getOperand(2), WidthConst,
10884           DAG.getValueType(N->getOperand(1).getValueType())
10885         };
10886         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
10887                                       DAG.getVTList(MVT::Other), Ops,
10888                                       cast<StoreSDNode>(N)->getMemoryVT(),
10889                                       cast<StoreSDNode>(N)->getMemOperand());
10890       }
10891 
10892       DCI.AddToWorklist(Val.getNode());
10893       return Val;
10894     }
10895 
10896     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10897     if (cast<StoreSDNode>(N)->isUnindexed() &&
10898         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10899         N->getOperand(1).getNode()->hasOneUse() &&
10900         (N->getOperand(1).getValueType() == MVT::i32 ||
10901          N->getOperand(1).getValueType() == MVT::i16 ||
10902          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10903           N->getOperand(1).getValueType() == MVT::i64))) {
10904       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10905       // Do an any-extend to 32-bits if this is a half-word input.
10906       if (BSwapOp.getValueType() == MVT::i16)
10907         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10908 
10909       SDValue Ops[] = {
10910         N->getOperand(0), BSwapOp, N->getOperand(2),
10911         DAG.getValueType(N->getOperand(1).getValueType())
10912       };
10913       return
10914         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10915                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10916                                 cast<StoreSDNode>(N)->getMemOperand());
10917     }
10918 
10919     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10920     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
10921     EVT VT = N->getOperand(1).getValueType();
10922     if (VT.isSimple()) {
10923       MVT StoreVT = VT.getSimpleVT();
10924       if (Subtarget.needsSwapsForVSXMemOps() &&
10925           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10926            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10927         return expandVSXStoreForLE(N, DCI);
10928     }
10929     break;
10930   }
10931   case ISD::LOAD: {
10932     LoadSDNode *LD = cast<LoadSDNode>(N);
10933     EVT VT = LD->getValueType(0);
10934 
10935     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10936     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
10937     if (VT.isSimple()) {
10938       MVT LoadVT = VT.getSimpleVT();
10939       if (Subtarget.needsSwapsForVSXMemOps() &&
10940           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10941            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10942         return expandVSXLoadForLE(N, DCI);
10943     }
10944 
10945     // We sometimes end up with a 64-bit integer load, from which we extract
10946     // two single-precision floating-point numbers. This happens with
10947     // std::complex<float>, and other similar structures, because of the way we
10948     // canonicalize structure copies. However, if we lack direct moves,
10949     // then the final bitcasts from the extracted integer values to the
10950     // floating-point numbers turn into store/load pairs. Even with direct moves,
10951     // just loading the two floating-point numbers is likely better.
10952     auto ReplaceTwoFloatLoad = [&]() {
10953       if (VT != MVT::i64)
10954         return false;
10955 
10956       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10957           LD->isVolatile())
10958         return false;
10959 
10960       //  We're looking for a sequence like this:
10961       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10962       //      t16: i64 = srl t13, Constant:i32<32>
10963       //    t17: i32 = truncate t16
10964       //  t18: f32 = bitcast t17
10965       //    t19: i32 = truncate t13
10966       //  t20: f32 = bitcast t19
10967 
10968       if (!LD->hasNUsesOfValue(2, 0))
10969         return false;
10970 
10971       auto UI = LD->use_begin();
10972       while (UI.getUse().getResNo() != 0) ++UI;
10973       SDNode *Trunc = *UI++;
10974       while (UI.getUse().getResNo() != 0) ++UI;
10975       SDNode *RightShift = *UI;
10976       if (Trunc->getOpcode() != ISD::TRUNCATE)
10977         std::swap(Trunc, RightShift);
10978 
10979       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10980           Trunc->getValueType(0) != MVT::i32 ||
10981           !Trunc->hasOneUse())
10982         return false;
10983       if (RightShift->getOpcode() != ISD::SRL ||
10984           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10985           RightShift->getConstantOperandVal(1) != 32 ||
10986           !RightShift->hasOneUse())
10987         return false;
10988 
10989       SDNode *Trunc2 = *RightShift->use_begin();
10990       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10991           Trunc2->getValueType(0) != MVT::i32 ||
10992           !Trunc2->hasOneUse())
10993         return false;
10994 
10995       SDNode *Bitcast = *Trunc->use_begin();
10996       SDNode *Bitcast2 = *Trunc2->use_begin();
10997 
10998       if (Bitcast->getOpcode() != ISD::BITCAST ||
10999           Bitcast->getValueType(0) != MVT::f32)
11000         return false;
11001       if (Bitcast2->getOpcode() != ISD::BITCAST ||
11002           Bitcast2->getValueType(0) != MVT::f32)
11003         return false;
11004 
11005       if (Subtarget.isLittleEndian())
11006         std::swap(Bitcast, Bitcast2);
11007 
11008       // Bitcast has the second float (in memory-layout order) and Bitcast2
11009       // has the first one.
11010 
11011       SDValue BasePtr = LD->getBasePtr();
11012       if (LD->isIndexed()) {
11013         assert(LD->getAddressingMode() == ISD::PRE_INC &&
11014                "Non-pre-inc AM on PPC?");
11015         BasePtr =
11016           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11017                       LD->getOffset());
11018       }
11019 
11020       auto MMOFlags =
11021           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11022       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11023                                       LD->getPointerInfo(), LD->getAlignment(),
11024                                       MMOFlags, LD->getAAInfo());
11025       SDValue AddPtr =
11026         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11027                     BasePtr, DAG.getIntPtrConstant(4, dl));
11028       SDValue FloatLoad2 = DAG.getLoad(
11029           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11030           LD->getPointerInfo().getWithOffset(4),
11031           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11032 
11033       if (LD->isIndexed()) {
11034         // Note that DAGCombine should re-form any pre-increment load(s) from
11035         // what is produced here if that makes sense.
11036         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11037       }
11038 
11039       DCI.CombineTo(Bitcast2, FloatLoad);
11040       DCI.CombineTo(Bitcast, FloatLoad2);
11041 
11042       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11043                                     SDValue(FloatLoad2.getNode(), 1));
11044       return true;
11045     };
11046 
11047     if (ReplaceTwoFloatLoad())
11048       return SDValue(N, 0);
11049 
11050     EVT MemVT = LD->getMemoryVT();
11051     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11052     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11053     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11054     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11055     if (LD->isUnindexed() && VT.isVector() &&
11056         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11057           // P8 and later hardware should just use LOAD.
11058           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11059                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11060          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11061           LD->getAlignment() >= ScalarABIAlignment)) &&
11062         LD->getAlignment() < ABIAlignment) {
11063       // This is a type-legal unaligned Altivec or QPX load.
11064       SDValue Chain = LD->getChain();
11065       SDValue Ptr = LD->getBasePtr();
11066       bool isLittleEndian = Subtarget.isLittleEndian();
11067 
11068       // This implements the loading of unaligned vectors as described in
11069       // the venerable Apple Velocity Engine overview. Specifically:
11070       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11071       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11072       //
11073       // The general idea is to expand a sequence of one or more unaligned
11074       // loads into an alignment-based permutation-control instruction (lvsl
11075       // or lvsr), a series of regular vector loads (which always truncate
11076       // their input address to an aligned address), and a series of
11077       // permutations.  The results of these permutations are the requested
11078       // loaded values.  The trick is that the last "extra" load is not taken
11079       // from the address you might suspect (sizeof(vector) bytes after the
11080       // last requested load), but rather sizeof(vector) - 1 bytes after the
11081       // last requested vector. The point of this is to avoid a page fault if
11082       // the base address happened to be aligned. This works because if the
11083       // base address is aligned, then adding less than a full vector length
11084       // will cause the last vector in the sequence to be (re)loaded.
11085       // Otherwise, the next vector will be fetched as you might suspect was
11086       // necessary.
11087 
11088       // We might be able to reuse the permutation generation from
11089       // a different base address offset from this one by an aligned amount.
11090       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11091       // optimization later.
11092       Intrinsic::ID Intr, IntrLD, IntrPerm;
11093       MVT PermCntlTy, PermTy, LDTy;
11094       if (Subtarget.hasAltivec()) {
11095         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
11096                                  Intrinsic::ppc_altivec_lvsl;
11097         IntrLD = Intrinsic::ppc_altivec_lvx;
11098         IntrPerm = Intrinsic::ppc_altivec_vperm;
11099         PermCntlTy = MVT::v16i8;
11100         PermTy = MVT::v4i32;
11101         LDTy = MVT::v4i32;
11102       } else {
11103         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11104                                        Intrinsic::ppc_qpx_qvlpcls;
11105         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11106                                        Intrinsic::ppc_qpx_qvlfs;
11107         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11108         PermCntlTy = MVT::v4f64;
11109         PermTy = MVT::v4f64;
11110         LDTy = MemVT.getSimpleVT();
11111       }
11112 
11113       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11114 
11115       // Create the new MMO for the new base load. It is like the original MMO,
11116       // but represents an area in memory almost twice the vector size centered
11117       // on the original address. If the address is unaligned, we might start
11118       // reading up to (sizeof(vector)-1) bytes below the address of the
11119       // original unaligned load.
11120       MachineFunction &MF = DAG.getMachineFunction();
11121       MachineMemOperand *BaseMMO =
11122         MF.getMachineMemOperand(LD->getMemOperand(),
11123                                 -(long)MemVT.getStoreSize()+1,
11124                                 2*MemVT.getStoreSize()-1);
11125 
11126       // Create the new base load.
11127       SDValue LDXIntID =
11128           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11129       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11130       SDValue BaseLoad =
11131         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11132                                 DAG.getVTList(PermTy, MVT::Other),
11133                                 BaseLoadOps, LDTy, BaseMMO);
11134 
11135       // Note that the value of IncOffset (which is provided to the next
11136       // load's pointer info offset value, and thus used to calculate the
11137       // alignment), and the value of IncValue (which is actually used to
11138       // increment the pointer value) are different! This is because we
11139       // require the next load to appear to be aligned, even though it
11140       // is actually offset from the base pointer by a lesser amount.
11141       int IncOffset = VT.getSizeInBits() / 8;
11142       int IncValue = IncOffset;
11143 
11144       // Walk (both up and down) the chain looking for another load at the real
11145       // (aligned) offset (the alignment of the other load does not matter in
11146       // this case). If found, then do not use the offset reduction trick, as
11147       // that will prevent the loads from being later combined (as they would
11148       // otherwise be duplicates).
11149       if (!findConsecutiveLoad(LD, DAG))
11150         --IncValue;
11151 
11152       SDValue Increment =
11153           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11154       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11155 
11156       MachineMemOperand *ExtraMMO =
11157         MF.getMachineMemOperand(LD->getMemOperand(),
11158                                 1, 2*MemVT.getStoreSize()-1);
11159       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11160       SDValue ExtraLoad =
11161         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11162                                 DAG.getVTList(PermTy, MVT::Other),
11163                                 ExtraLoadOps, LDTy, ExtraMMO);
11164 
11165       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11166         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11167 
11168       // Because vperm has a big-endian bias, we must reverse the order
11169       // of the input vectors and complement the permute control vector
11170       // when generating little endian code.  We have already handled the
11171       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11172       // and ExtraLoad here.
11173       SDValue Perm;
11174       if (isLittleEndian)
11175         Perm = BuildIntrinsicOp(IntrPerm,
11176                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11177       else
11178         Perm = BuildIntrinsicOp(IntrPerm,
11179                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11180 
11181       if (VT != PermTy)
11182         Perm = Subtarget.hasAltivec() ?
11183                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11184                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11185                                DAG.getTargetConstant(1, dl, MVT::i64));
11186                                // second argument is 1 because this rounding
11187                                // is always exact.
11188 
11189       // The output of the permutation is our loaded result, the TokenFactor is
11190       // our new chain.
11191       DCI.CombineTo(N, Perm, TF);
11192       return SDValue(N, 0);
11193     }
11194     }
11195     break;
11196     case ISD::INTRINSIC_WO_CHAIN: {
11197       bool isLittleEndian = Subtarget.isLittleEndian();
11198       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11199       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11200                                            : Intrinsic::ppc_altivec_lvsl);
11201       if ((IID == Intr ||
11202            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11203            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11204         N->getOperand(1)->getOpcode() == ISD::ADD) {
11205         SDValue Add = N->getOperand(1);
11206 
11207         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11208                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11209 
11210         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11211                                   APInt::getAllOnesValue(Bits /* alignment */)
11212                                       .zext(Add.getScalarValueSizeInBits()))) {
11213           SDNode *BasePtr = Add->getOperand(0).getNode();
11214           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11215                                     UE = BasePtr->use_end();
11216                UI != UE; ++UI) {
11217             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11218                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11219               // We've found another LVSL/LVSR, and this address is an aligned
11220               // multiple of that one. The results will be the same, so use the
11221               // one we've just found instead.
11222 
11223               return SDValue(*UI, 0);
11224             }
11225           }
11226         }
11227 
11228         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11229           SDNode *BasePtr = Add->getOperand(0).getNode();
11230           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11231                UE = BasePtr->use_end(); UI != UE; ++UI) {
11232             if (UI->getOpcode() == ISD::ADD &&
11233                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11234                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11235                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11236                 (1ULL << Bits) == 0) {
11237               SDNode *OtherAdd = *UI;
11238               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11239                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11240                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11241                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11242                   return SDValue(*VI, 0);
11243                 }
11244               }
11245             }
11246           }
11247         }
11248       }
11249     }
11250 
11251     break;
11252   case ISD::INTRINSIC_W_CHAIN: {
11253     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11254     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11255     if (Subtarget.needsSwapsForVSXMemOps()) {
11256       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11257       default:
11258         break;
11259       case Intrinsic::ppc_vsx_lxvw4x:
11260       case Intrinsic::ppc_vsx_lxvd2x:
11261         return expandVSXLoadForLE(N, DCI);
11262       }
11263     }
11264     break;
11265   }
11266   case ISD::INTRINSIC_VOID: {
11267     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11268     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11269     if (Subtarget.needsSwapsForVSXMemOps()) {
11270       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11271       default:
11272         break;
11273       case Intrinsic::ppc_vsx_stxvw4x:
11274       case Intrinsic::ppc_vsx_stxvd2x:
11275         return expandVSXStoreForLE(N, DCI);
11276       }
11277     }
11278     break;
11279   }
11280   case ISD::BSWAP:
11281     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11282     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11283         N->getOperand(0).hasOneUse() &&
11284         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11285          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11286           N->getValueType(0) == MVT::i64))) {
11287       SDValue Load = N->getOperand(0);
11288       LoadSDNode *LD = cast<LoadSDNode>(Load);
11289       // Create the byte-swapping load.
11290       SDValue Ops[] = {
11291         LD->getChain(),    // Chain
11292         LD->getBasePtr(),  // Ptr
11293         DAG.getValueType(N->getValueType(0)) // VT
11294       };
11295       SDValue BSLoad =
11296         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11297                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11298                                               MVT::i64 : MVT::i32, MVT::Other),
11299                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11300 
11301       // If this is an i16 load, insert the truncate.
11302       SDValue ResVal = BSLoad;
11303       if (N->getValueType(0) == MVT::i16)
11304         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11305 
11306       // First, combine the bswap away.  This makes the value produced by the
11307       // load dead.
11308       DCI.CombineTo(N, ResVal);
11309 
11310       // Next, combine the load away, we give it a bogus result value but a real
11311       // chain result.  The result value is dead because the bswap is dead.
11312       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11313 
11314       // Return N so it doesn't get rechecked!
11315       return SDValue(N, 0);
11316     }
11317 
11318     break;
11319   case PPCISD::VCMP: {
11320     // If a VCMPo node already exists with exactly the same operands as this
11321     // node, use its result instead of this node (VCMPo computes both a CR6 and
11322     // a normal output).
11323     //
11324     if (!N->getOperand(0).hasOneUse() &&
11325         !N->getOperand(1).hasOneUse() &&
11326         !N->getOperand(2).hasOneUse()) {
11327 
11328       // Scan all of the users of the LHS, looking for VCMPo's that match.
11329       SDNode *VCMPoNode = nullptr;
11330 
11331       SDNode *LHSN = N->getOperand(0).getNode();
11332       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11333            UI != E; ++UI)
11334         if (UI->getOpcode() == PPCISD::VCMPo &&
11335             UI->getOperand(1) == N->getOperand(1) &&
11336             UI->getOperand(2) == N->getOperand(2) &&
11337             UI->getOperand(0) == N->getOperand(0)) {
11338           VCMPoNode = *UI;
11339           break;
11340         }
11341 
11342       // If there is no VCMPo node, or if the flag value has a single use, don't
11343       // transform this.
11344       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11345         break;
11346 
11347       // Look at the (necessarily single) use of the flag value.  If it has a
11348       // chain, this transformation is more complex.  Note that multiple things
11349       // could use the value result, which we should ignore.
11350       SDNode *FlagUser = nullptr;
11351       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11352            FlagUser == nullptr; ++UI) {
11353         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11354         SDNode *User = *UI;
11355         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11356           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11357             FlagUser = User;
11358             break;
11359           }
11360         }
11361       }
11362 
11363       // If the user is a MFOCRF instruction, we know this is safe.
11364       // Otherwise we give up for right now.
11365       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11366         return SDValue(VCMPoNode, 0);
11367     }
11368     break;
11369   }
11370   case ISD::BRCOND: {
11371     SDValue Cond = N->getOperand(1);
11372     SDValue Target = N->getOperand(2);
11373 
11374     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11375         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11376           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11377 
11378       // We now need to make the intrinsic dead (it cannot be instruction
11379       // selected).
11380       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11381       assert(Cond.getNode()->hasOneUse() &&
11382              "Counter decrement has more than one use");
11383 
11384       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11385                          N->getOperand(0), Target);
11386     }
11387   }
11388   break;
11389   case ISD::BR_CC: {
11390     // If this is a branch on an altivec predicate comparison, lower this so
11391     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11392     // lowering is done pre-legalize, because the legalizer lowers the predicate
11393     // compare down to code that is difficult to reassemble.
11394     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11395     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11396 
11397     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11398     // value. If so, pass-through the AND to get to the intrinsic.
11399     if (LHS.getOpcode() == ISD::AND &&
11400         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11401         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11402           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11403         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11404         !isNullConstant(LHS.getOperand(1)))
11405       LHS = LHS.getOperand(0);
11406 
11407     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11408         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11409           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11410         isa<ConstantSDNode>(RHS)) {
11411       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11412              "Counter decrement comparison is not EQ or NE");
11413 
11414       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11415       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11416                     (CC == ISD::SETNE && !Val);
11417 
11418       // We now need to make the intrinsic dead (it cannot be instruction
11419       // selected).
11420       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11421       assert(LHS.getNode()->hasOneUse() &&
11422              "Counter decrement has more than one use");
11423 
11424       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11425                          N->getOperand(0), N->getOperand(4));
11426     }
11427 
11428     int CompareOpc;
11429     bool isDot;
11430 
11431     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11432         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11433         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11434       assert(isDot && "Can't compare against a vector result!");
11435 
11436       // If this is a comparison against something other than 0/1, then we know
11437       // that the condition is never/always true.
11438       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11439       if (Val != 0 && Val != 1) {
11440         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11441           return N->getOperand(0);
11442         // Always !=, turn it into an unconditional branch.
11443         return DAG.getNode(ISD::BR, dl, MVT::Other,
11444                            N->getOperand(0), N->getOperand(4));
11445       }
11446 
11447       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11448 
11449       // Create the PPCISD altivec 'dot' comparison node.
11450       SDValue Ops[] = {
11451         LHS.getOperand(2),  // LHS of compare
11452         LHS.getOperand(3),  // RHS of compare
11453         DAG.getConstant(CompareOpc, dl, MVT::i32)
11454       };
11455       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11456       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11457 
11458       // Unpack the result based on how the target uses it.
11459       PPC::Predicate CompOpc;
11460       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11461       default:  // Can't happen, don't crash on invalid number though.
11462       case 0:   // Branch on the value of the EQ bit of CR6.
11463         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11464         break;
11465       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11466         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11467         break;
11468       case 2:   // Branch on the value of the LT bit of CR6.
11469         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11470         break;
11471       case 3:   // Branch on the inverted value of the LT bit of CR6.
11472         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11473         break;
11474       }
11475 
11476       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11477                          DAG.getConstant(CompOpc, dl, MVT::i32),
11478                          DAG.getRegister(PPC::CR6, MVT::i32),
11479                          N->getOperand(4), CompNode.getValue(1));
11480     }
11481     break;
11482   }
11483   case ISD::BUILD_VECTOR:
11484     return DAGCombineBuildVector(N, DCI);
11485   }
11486 
11487   return SDValue();
11488 }
11489 
11490 SDValue
11491 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11492                                   SelectionDAG &DAG,
11493                                   std::vector<SDNode *> *Created) const {
11494   // fold (sdiv X, pow2)
11495   EVT VT = N->getValueType(0);
11496   if (VT == MVT::i64 && !Subtarget.isPPC64())
11497     return SDValue();
11498   if ((VT != MVT::i32 && VT != MVT::i64) ||
11499       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11500     return SDValue();
11501 
11502   SDLoc DL(N);
11503   SDValue N0 = N->getOperand(0);
11504 
11505   bool IsNegPow2 = (-Divisor).isPowerOf2();
11506   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11507   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11508 
11509   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11510   if (Created)
11511     Created->push_back(Op.getNode());
11512 
11513   if (IsNegPow2) {
11514     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11515     if (Created)
11516       Created->push_back(Op.getNode());
11517   }
11518 
11519   return Op;
11520 }
11521 
11522 //===----------------------------------------------------------------------===//
11523 // Inline Assembly Support
11524 //===----------------------------------------------------------------------===//
11525 
11526 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11527                                                       APInt &KnownZero,
11528                                                       APInt &KnownOne,
11529                                                       const SelectionDAG &DAG,
11530                                                       unsigned Depth) const {
11531   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11532   switch (Op.getOpcode()) {
11533   default: break;
11534   case PPCISD::LBRX: {
11535     // lhbrx is known to have the top bits cleared out.
11536     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11537       KnownZero = 0xFFFF0000;
11538     break;
11539   }
11540   case ISD::INTRINSIC_WO_CHAIN: {
11541     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11542     default: break;
11543     case Intrinsic::ppc_altivec_vcmpbfp_p:
11544     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11545     case Intrinsic::ppc_altivec_vcmpequb_p:
11546     case Intrinsic::ppc_altivec_vcmpequh_p:
11547     case Intrinsic::ppc_altivec_vcmpequw_p:
11548     case Intrinsic::ppc_altivec_vcmpequd_p:
11549     case Intrinsic::ppc_altivec_vcmpgefp_p:
11550     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11551     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11552     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11553     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11554     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11555     case Intrinsic::ppc_altivec_vcmpgtub_p:
11556     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11557     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11558     case Intrinsic::ppc_altivec_vcmpgtud_p:
11559       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11560       break;
11561     }
11562   }
11563   }
11564 }
11565 
11566 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11567   switch (Subtarget.getDarwinDirective()) {
11568   default: break;
11569   case PPC::DIR_970:
11570   case PPC::DIR_PWR4:
11571   case PPC::DIR_PWR5:
11572   case PPC::DIR_PWR5X:
11573   case PPC::DIR_PWR6:
11574   case PPC::DIR_PWR6X:
11575   case PPC::DIR_PWR7:
11576   case PPC::DIR_PWR8:
11577   case PPC::DIR_PWR9: {
11578     if (!ML)
11579       break;
11580 
11581     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11582 
11583     // For small loops (between 5 and 8 instructions), align to a 32-byte
11584     // boundary so that the entire loop fits in one instruction-cache line.
11585     uint64_t LoopSize = 0;
11586     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11587       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11588         LoopSize += TII->getInstSizeInBytes(*J);
11589         if (LoopSize > 32)
11590           break;
11591       }
11592 
11593     if (LoopSize > 16 && LoopSize <= 32)
11594       return 5;
11595 
11596     break;
11597   }
11598   }
11599 
11600   return TargetLowering::getPrefLoopAlignment(ML);
11601 }
11602 
11603 /// getConstraintType - Given a constraint, return the type of
11604 /// constraint it is for this target.
11605 PPCTargetLowering::ConstraintType
11606 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11607   if (Constraint.size() == 1) {
11608     switch (Constraint[0]) {
11609     default: break;
11610     case 'b':
11611     case 'r':
11612     case 'f':
11613     case 'd':
11614     case 'v':
11615     case 'y':
11616       return C_RegisterClass;
11617     case 'Z':
11618       // FIXME: While Z does indicate a memory constraint, it specifically
11619       // indicates an r+r address (used in conjunction with the 'y' modifier
11620       // in the replacement string). Currently, we're forcing the base
11621       // register to be r0 in the asm printer (which is interpreted as zero)
11622       // and forming the complete address in the second register. This is
11623       // suboptimal.
11624       return C_Memory;
11625     }
11626   } else if (Constraint == "wc") { // individual CR bits.
11627     return C_RegisterClass;
11628   } else if (Constraint == "wa" || Constraint == "wd" ||
11629              Constraint == "wf" || Constraint == "ws") {
11630     return C_RegisterClass; // VSX registers.
11631   }
11632   return TargetLowering::getConstraintType(Constraint);
11633 }
11634 
11635 /// Examine constraint type and operand type and determine a weight value.
11636 /// This object must already have been set up with the operand type
11637 /// and the current alternative constraint selected.
11638 TargetLowering::ConstraintWeight
11639 PPCTargetLowering::getSingleConstraintMatchWeight(
11640     AsmOperandInfo &info, const char *constraint) const {
11641   ConstraintWeight weight = CW_Invalid;
11642   Value *CallOperandVal = info.CallOperandVal;
11643     // If we don't have a value, we can't do a match,
11644     // but allow it at the lowest weight.
11645   if (!CallOperandVal)
11646     return CW_Default;
11647   Type *type = CallOperandVal->getType();
11648 
11649   // Look at the constraint type.
11650   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11651     return CW_Register; // an individual CR bit.
11652   else if ((StringRef(constraint) == "wa" ||
11653             StringRef(constraint) == "wd" ||
11654             StringRef(constraint) == "wf") &&
11655            type->isVectorTy())
11656     return CW_Register;
11657   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11658     return CW_Register;
11659 
11660   switch (*constraint) {
11661   default:
11662     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11663     break;
11664   case 'b':
11665     if (type->isIntegerTy())
11666       weight = CW_Register;
11667     break;
11668   case 'f':
11669     if (type->isFloatTy())
11670       weight = CW_Register;
11671     break;
11672   case 'd':
11673     if (type->isDoubleTy())
11674       weight = CW_Register;
11675     break;
11676   case 'v':
11677     if (type->isVectorTy())
11678       weight = CW_Register;
11679     break;
11680   case 'y':
11681     weight = CW_Register;
11682     break;
11683   case 'Z':
11684     weight = CW_Memory;
11685     break;
11686   }
11687   return weight;
11688 }
11689 
11690 std::pair<unsigned, const TargetRegisterClass *>
11691 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11692                                                 StringRef Constraint,
11693                                                 MVT VT) const {
11694   if (Constraint.size() == 1) {
11695     // GCC RS6000 Constraint Letters
11696     switch (Constraint[0]) {
11697     case 'b':   // R1-R31
11698       if (VT == MVT::i64 && Subtarget.isPPC64())
11699         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11700       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11701     case 'r':   // R0-R31
11702       if (VT == MVT::i64 && Subtarget.isPPC64())
11703         return std::make_pair(0U, &PPC::G8RCRegClass);
11704       return std::make_pair(0U, &PPC::GPRCRegClass);
11705     // 'd' and 'f' constraints are both defined to be "the floating point
11706     // registers", where one is for 32-bit and the other for 64-bit. We don't
11707     // really care overly much here so just give them all the same reg classes.
11708     case 'd':
11709     case 'f':
11710       if (VT == MVT::f32 || VT == MVT::i32)
11711         return std::make_pair(0U, &PPC::F4RCRegClass);
11712       if (VT == MVT::f64 || VT == MVT::i64)
11713         return std::make_pair(0U, &PPC::F8RCRegClass);
11714       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11715         return std::make_pair(0U, &PPC::QFRCRegClass);
11716       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11717         return std::make_pair(0U, &PPC::QSRCRegClass);
11718       break;
11719     case 'v':
11720       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11721         return std::make_pair(0U, &PPC::QFRCRegClass);
11722       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11723         return std::make_pair(0U, &PPC::QSRCRegClass);
11724       if (Subtarget.hasAltivec())
11725         return std::make_pair(0U, &PPC::VRRCRegClass);
11726     case 'y':   // crrc
11727       return std::make_pair(0U, &PPC::CRRCRegClass);
11728     }
11729   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11730     // An individual CR bit.
11731     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11732   } else if ((Constraint == "wa" || Constraint == "wd" ||
11733              Constraint == "wf") && Subtarget.hasVSX()) {
11734     return std::make_pair(0U, &PPC::VSRCRegClass);
11735   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11736     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11737       return std::make_pair(0U, &PPC::VSSRCRegClass);
11738     else
11739       return std::make_pair(0U, &PPC::VSFRCRegClass);
11740   }
11741 
11742   std::pair<unsigned, const TargetRegisterClass *> R =
11743       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11744 
11745   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11746   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11747   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11748   // register.
11749   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11750   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11751   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11752       PPC::GPRCRegClass.contains(R.first))
11753     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11754                             PPC::sub_32, &PPC::G8RCRegClass),
11755                           &PPC::G8RCRegClass);
11756 
11757   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11758   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11759     R.first = PPC::CR0;
11760     R.second = &PPC::CRRCRegClass;
11761   }
11762 
11763   return R;
11764 }
11765 
11766 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11767 /// vector.  If it is invalid, don't add anything to Ops.
11768 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11769                                                      std::string &Constraint,
11770                                                      std::vector<SDValue>&Ops,
11771                                                      SelectionDAG &DAG) const {
11772   SDValue Result;
11773 
11774   // Only support length 1 constraints.
11775   if (Constraint.length() > 1) return;
11776 
11777   char Letter = Constraint[0];
11778   switch (Letter) {
11779   default: break;
11780   case 'I':
11781   case 'J':
11782   case 'K':
11783   case 'L':
11784   case 'M':
11785   case 'N':
11786   case 'O':
11787   case 'P': {
11788     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11789     if (!CST) return; // Must be an immediate to match.
11790     SDLoc dl(Op);
11791     int64_t Value = CST->getSExtValue();
11792     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11793                          // numbers are printed as such.
11794     switch (Letter) {
11795     default: llvm_unreachable("Unknown constraint letter!");
11796     case 'I':  // "I" is a signed 16-bit constant.
11797       if (isInt<16>(Value))
11798         Result = DAG.getTargetConstant(Value, dl, TCVT);
11799       break;
11800     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11801       if (isShiftedUInt<16, 16>(Value))
11802         Result = DAG.getTargetConstant(Value, dl, TCVT);
11803       break;
11804     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11805       if (isShiftedInt<16, 16>(Value))
11806         Result = DAG.getTargetConstant(Value, dl, TCVT);
11807       break;
11808     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11809       if (isUInt<16>(Value))
11810         Result = DAG.getTargetConstant(Value, dl, TCVT);
11811       break;
11812     case 'M':  // "M" is a constant that is greater than 31.
11813       if (Value > 31)
11814         Result = DAG.getTargetConstant(Value, dl, TCVT);
11815       break;
11816     case 'N':  // "N" is a positive constant that is an exact power of two.
11817       if (Value > 0 && isPowerOf2_64(Value))
11818         Result = DAG.getTargetConstant(Value, dl, TCVT);
11819       break;
11820     case 'O':  // "O" is the constant zero.
11821       if (Value == 0)
11822         Result = DAG.getTargetConstant(Value, dl, TCVT);
11823       break;
11824     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11825       if (isInt<16>(-Value))
11826         Result = DAG.getTargetConstant(Value, dl, TCVT);
11827       break;
11828     }
11829     break;
11830   }
11831   }
11832 
11833   if (Result.getNode()) {
11834     Ops.push_back(Result);
11835     return;
11836   }
11837 
11838   // Handle standard constraint letters.
11839   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11840 }
11841 
11842 // isLegalAddressingMode - Return true if the addressing mode represented
11843 // by AM is legal for this target, for a load/store of the specified type.
11844 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11845                                               const AddrMode &AM, Type *Ty,
11846                                               unsigned AS) const {
11847   // PPC does not allow r+i addressing modes for vectors!
11848   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11849     return false;
11850 
11851   // PPC allows a sign-extended 16-bit immediate field.
11852   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11853     return false;
11854 
11855   // No global is ever allowed as a base.
11856   if (AM.BaseGV)
11857     return false;
11858 
11859   // PPC only support r+r,
11860   switch (AM.Scale) {
11861   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11862     break;
11863   case 1:
11864     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11865       return false;
11866     // Otherwise we have r+r or r+i.
11867     break;
11868   case 2:
11869     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11870       return false;
11871     // Allow 2*r as r+r.
11872     break;
11873   default:
11874     // No other scales are supported.
11875     return false;
11876   }
11877 
11878   return true;
11879 }
11880 
11881 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11882                                            SelectionDAG &DAG) const {
11883   MachineFunction &MF = DAG.getMachineFunction();
11884   MachineFrameInfo &MFI = MF.getFrameInfo();
11885   MFI.setReturnAddressIsTaken(true);
11886 
11887   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11888     return SDValue();
11889 
11890   SDLoc dl(Op);
11891   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11892 
11893   // Make sure the function does not optimize away the store of the RA to
11894   // the stack.
11895   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11896   FuncInfo->setLRStoreRequired();
11897   bool isPPC64 = Subtarget.isPPC64();
11898   auto PtrVT = getPointerTy(MF.getDataLayout());
11899 
11900   if (Depth > 0) {
11901     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11902     SDValue Offset =
11903         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11904                         isPPC64 ? MVT::i64 : MVT::i32);
11905     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11906                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11907                        MachinePointerInfo());
11908   }
11909 
11910   // Just load the return address off the stack.
11911   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11912   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11913                      MachinePointerInfo());
11914 }
11915 
11916 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11917                                           SelectionDAG &DAG) const {
11918   SDLoc dl(Op);
11919   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11920 
11921   MachineFunction &MF = DAG.getMachineFunction();
11922   MachineFrameInfo &MFI = MF.getFrameInfo();
11923   MFI.setFrameAddressIsTaken(true);
11924 
11925   EVT PtrVT = getPointerTy(MF.getDataLayout());
11926   bool isPPC64 = PtrVT == MVT::i64;
11927 
11928   // Naked functions never have a frame pointer, and so we use r1. For all
11929   // other functions, this decision must be delayed until during PEI.
11930   unsigned FrameReg;
11931   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11932     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11933   else
11934     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11935 
11936   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11937                                          PtrVT);
11938   while (Depth--)
11939     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11940                             FrameAddr, MachinePointerInfo());
11941   return FrameAddr;
11942 }
11943 
11944 // FIXME? Maybe this could be a TableGen attribute on some registers and
11945 // this table could be generated automatically from RegInfo.
11946 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11947                                               SelectionDAG &DAG) const {
11948   bool isPPC64 = Subtarget.isPPC64();
11949   bool isDarwinABI = Subtarget.isDarwinABI();
11950 
11951   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11952       (!isPPC64 && VT != MVT::i32))
11953     report_fatal_error("Invalid register global variable type");
11954 
11955   bool is64Bit = isPPC64 && VT == MVT::i64;
11956   unsigned Reg = StringSwitch<unsigned>(RegName)
11957                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11958                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11959                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11960                                   (is64Bit ? PPC::X13 : PPC::R13))
11961                    .Default(0);
11962 
11963   if (Reg)
11964     return Reg;
11965   report_fatal_error("Invalid register name global variable");
11966 }
11967 
11968 bool
11969 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11970   // The PowerPC target isn't yet aware of offsets.
11971   return false;
11972 }
11973 
11974 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11975                                            const CallInst &I,
11976                                            unsigned Intrinsic) const {
11977 
11978   switch (Intrinsic) {
11979   case Intrinsic::ppc_qpx_qvlfd:
11980   case Intrinsic::ppc_qpx_qvlfs:
11981   case Intrinsic::ppc_qpx_qvlfcd:
11982   case Intrinsic::ppc_qpx_qvlfcs:
11983   case Intrinsic::ppc_qpx_qvlfiwa:
11984   case Intrinsic::ppc_qpx_qvlfiwz:
11985   case Intrinsic::ppc_altivec_lvx:
11986   case Intrinsic::ppc_altivec_lvxl:
11987   case Intrinsic::ppc_altivec_lvebx:
11988   case Intrinsic::ppc_altivec_lvehx:
11989   case Intrinsic::ppc_altivec_lvewx:
11990   case Intrinsic::ppc_vsx_lxvd2x:
11991   case Intrinsic::ppc_vsx_lxvw4x: {
11992     EVT VT;
11993     switch (Intrinsic) {
11994     case Intrinsic::ppc_altivec_lvebx:
11995       VT = MVT::i8;
11996       break;
11997     case Intrinsic::ppc_altivec_lvehx:
11998       VT = MVT::i16;
11999       break;
12000     case Intrinsic::ppc_altivec_lvewx:
12001       VT = MVT::i32;
12002       break;
12003     case Intrinsic::ppc_vsx_lxvd2x:
12004       VT = MVT::v2f64;
12005       break;
12006     case Intrinsic::ppc_qpx_qvlfd:
12007       VT = MVT::v4f64;
12008       break;
12009     case Intrinsic::ppc_qpx_qvlfs:
12010       VT = MVT::v4f32;
12011       break;
12012     case Intrinsic::ppc_qpx_qvlfcd:
12013       VT = MVT::v2f64;
12014       break;
12015     case Intrinsic::ppc_qpx_qvlfcs:
12016       VT = MVT::v2f32;
12017       break;
12018     default:
12019       VT = MVT::v4i32;
12020       break;
12021     }
12022 
12023     Info.opc = ISD::INTRINSIC_W_CHAIN;
12024     Info.memVT = VT;
12025     Info.ptrVal = I.getArgOperand(0);
12026     Info.offset = -VT.getStoreSize()+1;
12027     Info.size = 2*VT.getStoreSize()-1;
12028     Info.align = 1;
12029     Info.vol = false;
12030     Info.readMem = true;
12031     Info.writeMem = false;
12032     return true;
12033   }
12034   case Intrinsic::ppc_qpx_qvlfda:
12035   case Intrinsic::ppc_qpx_qvlfsa:
12036   case Intrinsic::ppc_qpx_qvlfcda:
12037   case Intrinsic::ppc_qpx_qvlfcsa:
12038   case Intrinsic::ppc_qpx_qvlfiwaa:
12039   case Intrinsic::ppc_qpx_qvlfiwza: {
12040     EVT VT;
12041     switch (Intrinsic) {
12042     case Intrinsic::ppc_qpx_qvlfda:
12043       VT = MVT::v4f64;
12044       break;
12045     case Intrinsic::ppc_qpx_qvlfsa:
12046       VT = MVT::v4f32;
12047       break;
12048     case Intrinsic::ppc_qpx_qvlfcda:
12049       VT = MVT::v2f64;
12050       break;
12051     case Intrinsic::ppc_qpx_qvlfcsa:
12052       VT = MVT::v2f32;
12053       break;
12054     default:
12055       VT = MVT::v4i32;
12056       break;
12057     }
12058 
12059     Info.opc = ISD::INTRINSIC_W_CHAIN;
12060     Info.memVT = VT;
12061     Info.ptrVal = I.getArgOperand(0);
12062     Info.offset = 0;
12063     Info.size = VT.getStoreSize();
12064     Info.align = 1;
12065     Info.vol = false;
12066     Info.readMem = true;
12067     Info.writeMem = false;
12068     return true;
12069   }
12070   case Intrinsic::ppc_qpx_qvstfd:
12071   case Intrinsic::ppc_qpx_qvstfs:
12072   case Intrinsic::ppc_qpx_qvstfcd:
12073   case Intrinsic::ppc_qpx_qvstfcs:
12074   case Intrinsic::ppc_qpx_qvstfiw:
12075   case Intrinsic::ppc_altivec_stvx:
12076   case Intrinsic::ppc_altivec_stvxl:
12077   case Intrinsic::ppc_altivec_stvebx:
12078   case Intrinsic::ppc_altivec_stvehx:
12079   case Intrinsic::ppc_altivec_stvewx:
12080   case Intrinsic::ppc_vsx_stxvd2x:
12081   case Intrinsic::ppc_vsx_stxvw4x: {
12082     EVT VT;
12083     switch (Intrinsic) {
12084     case Intrinsic::ppc_altivec_stvebx:
12085       VT = MVT::i8;
12086       break;
12087     case Intrinsic::ppc_altivec_stvehx:
12088       VT = MVT::i16;
12089       break;
12090     case Intrinsic::ppc_altivec_stvewx:
12091       VT = MVT::i32;
12092       break;
12093     case Intrinsic::ppc_vsx_stxvd2x:
12094       VT = MVT::v2f64;
12095       break;
12096     case Intrinsic::ppc_qpx_qvstfd:
12097       VT = MVT::v4f64;
12098       break;
12099     case Intrinsic::ppc_qpx_qvstfs:
12100       VT = MVT::v4f32;
12101       break;
12102     case Intrinsic::ppc_qpx_qvstfcd:
12103       VT = MVT::v2f64;
12104       break;
12105     case Intrinsic::ppc_qpx_qvstfcs:
12106       VT = MVT::v2f32;
12107       break;
12108     default:
12109       VT = MVT::v4i32;
12110       break;
12111     }
12112 
12113     Info.opc = ISD::INTRINSIC_VOID;
12114     Info.memVT = VT;
12115     Info.ptrVal = I.getArgOperand(1);
12116     Info.offset = -VT.getStoreSize()+1;
12117     Info.size = 2*VT.getStoreSize()-1;
12118     Info.align = 1;
12119     Info.vol = false;
12120     Info.readMem = false;
12121     Info.writeMem = true;
12122     return true;
12123   }
12124   case Intrinsic::ppc_qpx_qvstfda:
12125   case Intrinsic::ppc_qpx_qvstfsa:
12126   case Intrinsic::ppc_qpx_qvstfcda:
12127   case Intrinsic::ppc_qpx_qvstfcsa:
12128   case Intrinsic::ppc_qpx_qvstfiwa: {
12129     EVT VT;
12130     switch (Intrinsic) {
12131     case Intrinsic::ppc_qpx_qvstfda:
12132       VT = MVT::v4f64;
12133       break;
12134     case Intrinsic::ppc_qpx_qvstfsa:
12135       VT = MVT::v4f32;
12136       break;
12137     case Intrinsic::ppc_qpx_qvstfcda:
12138       VT = MVT::v2f64;
12139       break;
12140     case Intrinsic::ppc_qpx_qvstfcsa:
12141       VT = MVT::v2f32;
12142       break;
12143     default:
12144       VT = MVT::v4i32;
12145       break;
12146     }
12147 
12148     Info.opc = ISD::INTRINSIC_VOID;
12149     Info.memVT = VT;
12150     Info.ptrVal = I.getArgOperand(1);
12151     Info.offset = 0;
12152     Info.size = VT.getStoreSize();
12153     Info.align = 1;
12154     Info.vol = false;
12155     Info.readMem = false;
12156     Info.writeMem = true;
12157     return true;
12158   }
12159   default:
12160     break;
12161   }
12162 
12163   return false;
12164 }
12165 
12166 /// getOptimalMemOpType - Returns the target specific optimal type for load
12167 /// and store operations as a result of memset, memcpy, and memmove
12168 /// lowering. If DstAlign is zero that means it's safe to destination
12169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12170 /// means there isn't a need to check it against alignment requirement,
12171 /// probably because the source does not need to be loaded. If 'IsMemset' is
12172 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12173 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12174 /// source is constant so it does not need to be loaded.
12175 /// It returns EVT::Other if the type should be determined using generic
12176 /// target-independent logic.
12177 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12178                                            unsigned DstAlign, unsigned SrcAlign,
12179                                            bool IsMemset, bool ZeroMemset,
12180                                            bool MemcpyStrSrc,
12181                                            MachineFunction &MF) const {
12182   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12183     const Function *F = MF.getFunction();
12184     // When expanding a memset, require at least two QPX instructions to cover
12185     // the cost of loading the value to be stored from the constant pool.
12186     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12187        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12188         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12189       return MVT::v4f64;
12190     }
12191 
12192     // We should use Altivec/VSX loads and stores when available. For unaligned
12193     // addresses, unaligned VSX loads are only fast starting with the P8.
12194     if (Subtarget.hasAltivec() && Size >= 16 &&
12195         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12196          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12197       return MVT::v4i32;
12198   }
12199 
12200   if (Subtarget.isPPC64()) {
12201     return MVT::i64;
12202   }
12203 
12204   return MVT::i32;
12205 }
12206 
12207 /// \brief Returns true if it is beneficial to convert a load of a constant
12208 /// to just the constant itself.
12209 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12210                                                           Type *Ty) const {
12211   assert(Ty->isIntegerTy());
12212 
12213   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12214   return !(BitSize == 0 || BitSize > 64);
12215 }
12216 
12217 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12218   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12219     return false;
12220   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12221   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12222   return NumBits1 == 64 && NumBits2 == 32;
12223 }
12224 
12225 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12226   if (!VT1.isInteger() || !VT2.isInteger())
12227     return false;
12228   unsigned NumBits1 = VT1.getSizeInBits();
12229   unsigned NumBits2 = VT2.getSizeInBits();
12230   return NumBits1 == 64 && NumBits2 == 32;
12231 }
12232 
12233 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12234   // Generally speaking, zexts are not free, but they are free when they can be
12235   // folded with other operations.
12236   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12237     EVT MemVT = LD->getMemoryVT();
12238     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12239          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12240         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12241          LD->getExtensionType() == ISD::ZEXTLOAD))
12242       return true;
12243   }
12244 
12245   // FIXME: Add other cases...
12246   //  - 32-bit shifts with a zext to i64
12247   //  - zext after ctlz, bswap, etc.
12248   //  - zext after and by a constant mask
12249 
12250   return TargetLowering::isZExtFree(Val, VT2);
12251 }
12252 
12253 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12254   assert(VT.isFloatingPoint());
12255   return true;
12256 }
12257 
12258 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12259   return isInt<16>(Imm) || isUInt<16>(Imm);
12260 }
12261 
12262 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12263   return isInt<16>(Imm) || isUInt<16>(Imm);
12264 }
12265 
12266 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12267                                                        unsigned,
12268                                                        unsigned,
12269                                                        bool *Fast) const {
12270   if (DisablePPCUnaligned)
12271     return false;
12272 
12273   // PowerPC supports unaligned memory access for simple non-vector types.
12274   // Although accessing unaligned addresses is not as efficient as accessing
12275   // aligned addresses, it is generally more efficient than manual expansion,
12276   // and generally only traps for software emulation when crossing page
12277   // boundaries.
12278 
12279   if (!VT.isSimple())
12280     return false;
12281 
12282   if (VT.getSimpleVT().isVector()) {
12283     if (Subtarget.hasVSX()) {
12284       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12285           VT != MVT::v4f32 && VT != MVT::v4i32)
12286         return false;
12287     } else {
12288       return false;
12289     }
12290   }
12291 
12292   if (VT == MVT::ppcf128)
12293     return false;
12294 
12295   if (Fast)
12296     *Fast = true;
12297 
12298   return true;
12299 }
12300 
12301 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12302   VT = VT.getScalarType();
12303 
12304   if (!VT.isSimple())
12305     return false;
12306 
12307   switch (VT.getSimpleVT().SimpleTy) {
12308   case MVT::f32:
12309   case MVT::f64:
12310     return true;
12311   default:
12312     break;
12313   }
12314 
12315   return false;
12316 }
12317 
12318 const MCPhysReg *
12319 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12320   // LR is a callee-save register, but we must treat it as clobbered by any call
12321   // site. Hence we include LR in the scratch registers, which are in turn added
12322   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12323   // to CTR, which is used by any indirect call.
12324   static const MCPhysReg ScratchRegs[] = {
12325     PPC::X12, PPC::LR8, PPC::CTR8, 0
12326   };
12327 
12328   return ScratchRegs;
12329 }
12330 
12331 unsigned PPCTargetLowering::getExceptionPointerRegister(
12332     const Constant *PersonalityFn) const {
12333   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12334 }
12335 
12336 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12337     const Constant *PersonalityFn) const {
12338   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12339 }
12340 
12341 bool
12342 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12343                      EVT VT , unsigned DefinedValues) const {
12344   if (VT == MVT::v2i64)
12345     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12346 
12347   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12348     return true;
12349 
12350   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12351 }
12352 
12353 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12354   if (DisableILPPref || Subtarget.enableMachineScheduler())
12355     return TargetLowering::getSchedulingPreference(N);
12356 
12357   return Sched::ILP;
12358 }
12359 
12360 // Create a fast isel object.
12361 FastISel *
12362 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12363                                   const TargetLibraryInfo *LibInfo) const {
12364   return PPC::createFastISel(FuncInfo, LibInfo);
12365 }
12366 
12367 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12368   if (Subtarget.isDarwinABI()) return;
12369   if (!Subtarget.isPPC64()) return;
12370 
12371   // Update IsSplitCSR in PPCFunctionInfo
12372   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12373   PFI->setIsSplitCSR(true);
12374 }
12375 
12376 void PPCTargetLowering::insertCopiesSplitCSR(
12377   MachineBasicBlock *Entry,
12378   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12379   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12380   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12381   if (!IStart)
12382     return;
12383 
12384   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12385   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12386   MachineBasicBlock::iterator MBBI = Entry->begin();
12387   for (const MCPhysReg *I = IStart; *I; ++I) {
12388     const TargetRegisterClass *RC = nullptr;
12389     if (PPC::G8RCRegClass.contains(*I))
12390       RC = &PPC::G8RCRegClass;
12391     else if (PPC::F8RCRegClass.contains(*I))
12392       RC = &PPC::F8RCRegClass;
12393     else if (PPC::CRRCRegClass.contains(*I))
12394       RC = &PPC::CRRCRegClass;
12395     else if (PPC::VRRCRegClass.contains(*I))
12396       RC = &PPC::VRRCRegClass;
12397     else
12398       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12399 
12400     unsigned NewVR = MRI->createVirtualRegister(RC);
12401     // Create copy from CSR to a virtual register.
12402     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12403     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12404     // nounwind. If we want to generalize this later, we may need to emit
12405     // CFI pseudo-instructions.
12406     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12407              Attribute::NoUnwind) &&
12408            "Function should be nounwind in insertCopiesSplitCSR!");
12409     Entry->addLiveIn(*I);
12410     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12411       .addReg(*I);
12412 
12413     // Insert the copy-back instructions right before the terminator
12414     for (auto *Exit : Exits)
12415       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12416               TII->get(TargetOpcode::COPY), *I)
12417         .addReg(NewVR);
12418   }
12419 }
12420 
12421 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12422 bool PPCTargetLowering::useLoadStackGuardNode() const {
12423   if (!Subtarget.isTargetLinux())
12424     return TargetLowering::useLoadStackGuardNode();
12425   return true;
12426 }
12427 
12428 // Override to disable global variable loading on Linux.
12429 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12430   if (!Subtarget.isTargetLinux())
12431     return TargetLowering::insertSSPDeclarations(M);
12432 }
12433 
12434 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12435 
12436   if (!VT.isSimple() || !Subtarget.hasVSX())
12437     return false;
12438 
12439   switch(VT.getSimpleVT().SimpleTy) {
12440   default:
12441     // For FP types that are currently not supported by PPC backend, return
12442     // false. Examples: f16, f80.
12443     return false;
12444   case MVT::f32:
12445   case MVT::f64:
12446   case MVT::ppcf128:
12447     return Imm.isPosZero();
12448   }
12449 }
12450