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 "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCExpr.h"
74 #include "llvm/MC/MCRegisterInfo.h"
75 #include "llvm/Support/AtomicOrdering.h"
76 #include "llvm/Support/BranchProbability.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CodeGen.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/Format.h"
84 #include "llvm/Support/KnownBits.h"
85 #include "llvm/Support/MachineValueType.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetMachine.h"
89 #include "llvm/Target/TargetOptions.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
115 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
116 
117 STATISTIC(NumTailCalls, "Number of tail calls");
118 STATISTIC(NumSiblingCalls, "Number of sibling calls");
119 
120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
121 
122 // FIXME: Remove this once the bug has been fixed!
123 extern cl::opt<bool> ANDIGlueBug;
124 
125 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
126                                      const PPCSubtarget &STI)
127     : TargetLowering(TM), Subtarget(STI) {
128   // Use _setjmp/_longjmp instead of setjmp/longjmp.
129   setUseUnderscoreSetJmp(true);
130   setUseUnderscoreLongJmp(true);
131 
132   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
133   // arguments are at least 4/8 bytes aligned.
134   bool isPPC64 = Subtarget.isPPC64();
135   setMinStackArgumentAlignment(isPPC64 ? 8:4);
136 
137   // Set up the register classes.
138   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
139   if (!useSoftFloat()) {
140     if (hasSPE()) {
141       addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
142       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
143     } else {
144       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
145       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
146     }
147   }
148 
149   // Match BITREVERSE to customized fast code sequence in the td file.
150   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
151   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
152 
153   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
154   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
155 
156   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
157   for (MVT VT : MVT::integer_valuetypes()) {
158     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
160   }
161 
162   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
163 
164   // PowerPC has pre-inc load and store's.
165   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
166   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
167   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
168   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
169   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
170   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
171   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
172   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
173   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
174   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
175   if (!Subtarget.hasSPE()) {
176     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
177     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
178     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
179     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
180   }
181 
182   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
183   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
184   for (MVT VT : ScalarIntVTs) {
185     setOperationAction(ISD::ADDC, VT, Legal);
186     setOperationAction(ISD::ADDE, VT, Legal);
187     setOperationAction(ISD::SUBC, VT, Legal);
188     setOperationAction(ISD::SUBE, VT, Legal);
189   }
190 
191   if (Subtarget.useCRBits()) {
192     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193 
194     if (isPPC64 || Subtarget.hasFPCVT()) {
195       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
196       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
197                          isPPC64 ? MVT::i64 : MVT::i32);
198       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
199       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
200                         isPPC64 ? MVT::i64 : MVT::i32);
201     } else {
202       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
203       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
204     }
205 
206     // PowerPC does not support direct load/store of condition registers.
207     setOperationAction(ISD::LOAD, MVT::i1, Custom);
208     setOperationAction(ISD::STORE, MVT::i1, Custom);
209 
210     // FIXME: Remove this once the ANDI glue bug is fixed:
211     if (ANDIGlueBug)
212       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
213 
214     for (MVT VT : MVT::integer_valuetypes()) {
215       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
216       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
217       setTruncStoreAction(VT, MVT::i1, Expand);
218     }
219 
220     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
221   }
222 
223   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
224   // PPC (the libcall is not available).
225   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
226   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
227 
228   // We do not currently implement these libm ops for PowerPC.
229   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
230   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
231   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
232   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
233   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
234   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
235 
236   // PowerPC has no SREM/UREM instructions unless we are on P9
237   // On P9 we may use a hardware instruction to compute the remainder.
238   // The instructions are not legalized directly because in the cases where the
239   // result of both the remainder and the division is required it is more
240   // efficient to compute the remainder from the result of the division rather
241   // than use the remainder instruction.
242   if (Subtarget.isISA3_0()) {
243     setOperationAction(ISD::SREM, MVT::i32, Custom);
244     setOperationAction(ISD::UREM, MVT::i32, Custom);
245     setOperationAction(ISD::SREM, MVT::i64, Custom);
246     setOperationAction(ISD::UREM, MVT::i64, Custom);
247   } else {
248     setOperationAction(ISD::SREM, MVT::i32, Expand);
249     setOperationAction(ISD::UREM, MVT::i32, Expand);
250     setOperationAction(ISD::SREM, MVT::i64, Expand);
251     setOperationAction(ISD::UREM, MVT::i64, Expand);
252   }
253 
254   if (Subtarget.hasP9Vector()) {
255     setOperationAction(ISD::ABS, MVT::v4i32, Legal);
256     setOperationAction(ISD::ABS, MVT::v8i16, Legal);
257     setOperationAction(ISD::ABS, MVT::v16i8, Legal);
258   }
259 
260   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
261   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
262   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
263   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
264   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
265   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
266   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
267   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
268   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
269 
270   // We don't support sin/cos/sqrt/fmod/pow
271   setOperationAction(ISD::FSIN , MVT::f64, Expand);
272   setOperationAction(ISD::FCOS , MVT::f64, Expand);
273   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
274   setOperationAction(ISD::FREM , MVT::f64, Expand);
275   setOperationAction(ISD::FPOW , MVT::f64, Expand);
276   setOperationAction(ISD::FSIN , MVT::f32, Expand);
277   setOperationAction(ISD::FCOS , MVT::f32, Expand);
278   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
279   setOperationAction(ISD::FREM , MVT::f32, Expand);
280   setOperationAction(ISD::FPOW , MVT::f32, Expand);
281   if (Subtarget.hasSPE()) {
282     setOperationAction(ISD::FMA  , MVT::f64, Expand);
283     setOperationAction(ISD::FMA  , MVT::f32, Expand);
284   } else {
285     setOperationAction(ISD::FMA  , MVT::f64, Legal);
286     setOperationAction(ISD::FMA  , MVT::f32, Legal);
287   }
288 
289   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
290 
291   // If we're enabling GP optimizations, use hardware square root
292   if (!Subtarget.hasFSQRT() &&
293       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
294         Subtarget.hasFRE()))
295     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
296 
297   if (!Subtarget.hasFSQRT() &&
298       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
299         Subtarget.hasFRES()))
300     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
301 
302   if (Subtarget.hasFCPSGN()) {
303     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
304     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
305   } else {
306     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
307     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
308   }
309 
310   if (Subtarget.hasFPRND()) {
311     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
312     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
313     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
314     setOperationAction(ISD::FROUND, MVT::f64, Legal);
315 
316     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
317     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
318     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
319     setOperationAction(ISD::FROUND, MVT::f32, Legal);
320   }
321 
322   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
323   // to speed up scalar BSWAP64.
324   // CTPOP or CTTZ were introduced in P8/P9 respectively
325   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
326   if (Subtarget.isISA3_0()) {
327     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
328     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
329     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
330   } else {
331     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
332     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
333     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
334   }
335 
336   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
337     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
338     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
339   } else {
340     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
341     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
342   }
343 
344   // PowerPC does not have ROTR
345   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
346   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
347 
348   if (!Subtarget.useCRBits()) {
349     // PowerPC does not have Select
350     setOperationAction(ISD::SELECT, MVT::i32, Expand);
351     setOperationAction(ISD::SELECT, MVT::i64, Expand);
352     setOperationAction(ISD::SELECT, MVT::f32, Expand);
353     setOperationAction(ISD::SELECT, MVT::f64, Expand);
354   }
355 
356   // PowerPC wants to turn select_cc of FP into fsel when possible.
357   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
358   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
359 
360   // PowerPC wants to optimize integer setcc a bit
361   if (!Subtarget.useCRBits())
362     setOperationAction(ISD::SETCC, MVT::i32, Custom);
363 
364   // PowerPC does not have BRCOND which requires SetCC
365   if (!Subtarget.useCRBits())
366     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
367 
368   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
369 
370   if (Subtarget.hasSPE()) {
371     // SPE has built-in conversions
372     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
373     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
374     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
375   } else {
376     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
377     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
378 
379     // PowerPC does not have [U|S]INT_TO_FP
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
382   }
383 
384   if (Subtarget.hasDirectMove() && isPPC64) {
385     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
386     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
387     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
388     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
389   } else {
390     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
391     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
392     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
393     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
394   }
395 
396   // We cannot sextinreg(i1).  Expand to shifts.
397   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
398 
399   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
400   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
401   // support continuation, user-level threading, and etc.. As a result, no
402   // other SjLj exception interfaces are implemented and please don't build
403   // your own exception handling based on them.
404   // LLVM/Clang supports zero-cost DWARF exception handling.
405   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
406   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
407 
408   // We want to legalize GlobalAddress and ConstantPool nodes into the
409   // appropriate instructions to materialize the address.
410   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
411   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
412   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
413   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
414   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
415   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
416   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
417   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
418   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
419   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
420 
421   // TRAP is legal.
422   setOperationAction(ISD::TRAP, MVT::Other, Legal);
423 
424   // TRAMPOLINE is custom lowered.
425   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
426   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
427 
428   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
429   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
430 
431   if (Subtarget.isSVR4ABI()) {
432     if (isPPC64) {
433       // VAARG always uses double-word chunks, so promote anything smaller.
434       setOperationAction(ISD::VAARG, MVT::i1, Promote);
435       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
436       setOperationAction(ISD::VAARG, MVT::i8, Promote);
437       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
438       setOperationAction(ISD::VAARG, MVT::i16, Promote);
439       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
440       setOperationAction(ISD::VAARG, MVT::i32, Promote);
441       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
442       setOperationAction(ISD::VAARG, MVT::Other, Expand);
443     } else {
444       // VAARG is custom lowered with the 32-bit SVR4 ABI.
445       setOperationAction(ISD::VAARG, MVT::Other, Custom);
446       setOperationAction(ISD::VAARG, MVT::i64, Custom);
447     }
448   } else
449     setOperationAction(ISD::VAARG, MVT::Other, Expand);
450 
451   if (Subtarget.isSVR4ABI() && !isPPC64)
452     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
453     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
454   else
455     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
456 
457   // Use the default implementation.
458   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
459   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
460   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
461   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
462   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
463   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
464   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
465   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
466   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
467 
468   // We want to custom lower some of our intrinsics.
469   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
470 
471   // To handle counter-based loop conditions.
472   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
473 
474   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
475   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
476   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
477   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
478 
479   // Comparisons that require checking two conditions.
480   if (Subtarget.hasSPE()) {
481     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
482     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
483     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
484     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
485   }
486   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
487   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
488   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
489   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
490   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
491   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
492   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
493   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
494   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
495   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
496   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
497   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
498 
499   if (Subtarget.has64BitSupport()) {
500     // They also have instructions for converting between i64 and fp.
501     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
502     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
503     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
504     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
505     // This is just the low 32 bits of a (signed) fp->i64 conversion.
506     // We cannot do this with Promote because i64 is not a legal type.
507     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
508 
509     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
510       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
511   } else {
512     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
513     if (Subtarget.hasSPE())
514       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
515     else
516       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
517   }
518 
519   // With the instructions enabled under FPCVT, we can do everything.
520   if (Subtarget.hasFPCVT()) {
521     if (Subtarget.has64BitSupport()) {
522       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
523       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
524       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
525       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
526     }
527 
528     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
530     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
531     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
532   }
533 
534   if (Subtarget.use64BitRegs()) {
535     // 64-bit PowerPC implementations can support i64 types directly
536     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
537     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
538     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
539     // 64-bit PowerPC wants to expand i128 shifts itself.
540     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
541     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
542     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
543   } else {
544     // 32-bit PowerPC wants to expand i64 shifts itself.
545     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
546     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
547     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
548   }
549 
550   if (Subtarget.hasAltivec()) {
551     // First set operation action for all vector types to expand. Then we
552     // will selectively turn on ones that can be effectively codegen'd.
553     for (MVT VT : MVT::vector_valuetypes()) {
554       // add/sub are legal for all supported vector VT's.
555       setOperationAction(ISD::ADD, VT, Legal);
556       setOperationAction(ISD::SUB, VT, Legal);
557 
558       // Vector instructions introduced in P8
559       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
560         setOperationAction(ISD::CTPOP, VT, Legal);
561         setOperationAction(ISD::CTLZ, VT, Legal);
562       }
563       else {
564         setOperationAction(ISD::CTPOP, VT, Expand);
565         setOperationAction(ISD::CTLZ, VT, Expand);
566       }
567 
568       // Vector instructions introduced in P9
569       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
570         setOperationAction(ISD::CTTZ, VT, Legal);
571       else
572         setOperationAction(ISD::CTTZ, VT, Expand);
573 
574       // We promote all shuffles to v16i8.
575       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
576       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
577 
578       // We promote all non-typed operations to v4i32.
579       setOperationAction(ISD::AND   , VT, Promote);
580       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
581       setOperationAction(ISD::OR    , VT, Promote);
582       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
583       setOperationAction(ISD::XOR   , VT, Promote);
584       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
585       setOperationAction(ISD::LOAD  , VT, Promote);
586       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
587       setOperationAction(ISD::SELECT, VT, Promote);
588       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
589       setOperationAction(ISD::SELECT_CC, VT, Promote);
590       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
591       setOperationAction(ISD::STORE, VT, Promote);
592       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
593 
594       // No other operations are legal.
595       setOperationAction(ISD::MUL , VT, Expand);
596       setOperationAction(ISD::SDIV, VT, Expand);
597       setOperationAction(ISD::SREM, VT, Expand);
598       setOperationAction(ISD::UDIV, VT, Expand);
599       setOperationAction(ISD::UREM, VT, Expand);
600       setOperationAction(ISD::FDIV, VT, Expand);
601       setOperationAction(ISD::FREM, VT, Expand);
602       setOperationAction(ISD::FNEG, VT, Expand);
603       setOperationAction(ISD::FSQRT, VT, Expand);
604       setOperationAction(ISD::FLOG, VT, Expand);
605       setOperationAction(ISD::FLOG10, VT, Expand);
606       setOperationAction(ISD::FLOG2, VT, Expand);
607       setOperationAction(ISD::FEXP, VT, Expand);
608       setOperationAction(ISD::FEXP2, VT, Expand);
609       setOperationAction(ISD::FSIN, VT, Expand);
610       setOperationAction(ISD::FCOS, VT, Expand);
611       setOperationAction(ISD::FABS, VT, Expand);
612       setOperationAction(ISD::FFLOOR, VT, Expand);
613       setOperationAction(ISD::FCEIL,  VT, Expand);
614       setOperationAction(ISD::FTRUNC, VT, Expand);
615       setOperationAction(ISD::FRINT,  VT, Expand);
616       setOperationAction(ISD::FNEARBYINT, VT, Expand);
617       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
618       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
619       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
620       setOperationAction(ISD::MULHU, VT, Expand);
621       setOperationAction(ISD::MULHS, VT, Expand);
622       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
623       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
624       setOperationAction(ISD::UDIVREM, VT, Expand);
625       setOperationAction(ISD::SDIVREM, VT, Expand);
626       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
627       setOperationAction(ISD::FPOW, VT, Expand);
628       setOperationAction(ISD::BSWAP, VT, Expand);
629       setOperationAction(ISD::VSELECT, VT, Expand);
630       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
631       setOperationAction(ISD::ROTL, VT, Expand);
632       setOperationAction(ISD::ROTR, VT, Expand);
633 
634       for (MVT InnerVT : MVT::vector_valuetypes()) {
635         setTruncStoreAction(VT, InnerVT, Expand);
636         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
637         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
638         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
639       }
640     }
641 
642     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
643     // with merges, splats, etc.
644     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
645 
646     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
647     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
648     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
649     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
650     setOperationAction(ISD::SELECT, MVT::v4i32,
651                        Subtarget.useCRBits() ? Legal : Expand);
652     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
653     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
654     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
655     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
656     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
657     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
658     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
659     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
660     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
661 
662     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
663     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
664     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
665     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
666 
667     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
668     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
669 
670     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
671       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
672       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
673     }
674 
675     if (Subtarget.hasP8Altivec())
676       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
677     else
678       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
679 
680     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
681     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
682 
683     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
684     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
685 
686     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
687     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
688     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
689     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
690 
691     // Altivec does not contain unordered floating-point compare instructions
692     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
693     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
694     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
695     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
696 
697     if (Subtarget.hasVSX()) {
698       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
699       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
700       if (Subtarget.hasP8Vector()) {
701         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
702         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
703       }
704       if (Subtarget.hasDirectMove() && isPPC64) {
705         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
706         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
707         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
708         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
709         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
710         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
711         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
712         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
713       }
714       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
715 
716       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
717       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
718       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
719       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
720       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
721 
722       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
723 
724       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
725       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
726 
727       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
728       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
729 
730       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
731       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
732       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
733       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
734       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
735 
736       // Share the Altivec comparison restrictions.
737       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
738       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
739       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
740       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
741 
742       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
743       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
744 
745       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
746 
747       if (Subtarget.hasP8Vector())
748         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
749 
750       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
751 
752       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
753       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
754       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
755 
756       if (Subtarget.hasP8Altivec()) {
757         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
758         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
759         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
760 
761         // 128 bit shifts can be accomplished via 3 instructions for SHL and
762         // SRL, but not for SRA because of the instructions available:
763         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
764         // doing
765         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
766         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
767         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
768 
769         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
770       }
771       else {
772         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
773         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
774         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
775 
776         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
777 
778         // VSX v2i64 only supports non-arithmetic operations.
779         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
780         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
781       }
782 
783       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
784       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
785       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
786       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
787 
788       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
789 
790       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
791       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
792       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
793       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
794 
795       // Vector operation legalization checks the result type of
796       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
797       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
798       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
799       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
800       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
801 
802       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
803       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
804       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
805       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
806 
807       if (Subtarget.hasDirectMove())
808         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
809       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
810 
811       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
812     }
813 
814     if (Subtarget.hasP8Altivec()) {
815       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
816       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
817     }
818 
819     if (Subtarget.hasP9Vector()) {
820       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
821       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
822 
823       // 128 bit shifts can be accomplished via 3 instructions for SHL and
824       // SRL, but not for SRA because of the instructions available:
825       // VS{RL} and VS{RL}O.
826       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
827       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
828       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
829 
830       if (EnableQuadPrecision) {
831         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
832         setOperationAction(ISD::FADD, MVT::f128, Legal);
833         setOperationAction(ISD::FSUB, MVT::f128, Legal);
834         setOperationAction(ISD::FDIV, MVT::f128, Legal);
835         setOperationAction(ISD::FMUL, MVT::f128, Legal);
836         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
837         // No extending loads to f128 on PPC.
838         for (MVT FPT : MVT::fp_valuetypes())
839           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
840         setOperationAction(ISD::FMA, MVT::f128, Legal);
841         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
842         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
843         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
844         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
845         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
846         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
847 
848         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
849         setOperationAction(ISD::FRINT, MVT::f128, Legal);
850         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
851         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
852         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
853         setOperationAction(ISD::FROUND, MVT::f128, Legal);
854 
855         setOperationAction(ISD::SELECT, MVT::f128, Expand);
856         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
857         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
858         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
859         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
860         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
861         // No implementation for these ops for PowerPC.
862         setOperationAction(ISD::FSIN , MVT::f128, Expand);
863         setOperationAction(ISD::FCOS , MVT::f128, Expand);
864         setOperationAction(ISD::FPOW, MVT::f128, Expand);
865         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
866         setOperationAction(ISD::FREM, MVT::f128, Expand);
867       }
868 
869     }
870 
871     if (Subtarget.hasP9Altivec()) {
872       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
873       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
874     }
875   }
876 
877   if (Subtarget.hasQPX()) {
878     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
879     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
880     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
881     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
882 
883     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
884     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
885 
886     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
887     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
888 
889     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
890     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
891 
892     if (!Subtarget.useCRBits())
893       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
894     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
895 
896     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
897     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
898     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
899     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
900     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
901     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
902     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
903 
904     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
905     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
906 
907     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
908     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
909     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
910 
911     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
912     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
913     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
914     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
915     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
916     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
917     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
918     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
919     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
920     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
921 
922     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
923     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
924 
925     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
926     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
927 
928     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
929 
930     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
931     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
932     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
933     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
934 
935     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
936     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
937 
938     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
939     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
940 
941     if (!Subtarget.useCRBits())
942       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
943     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
944 
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
946     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
947     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
948     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
949     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
950     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
951     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
952 
953     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
954     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
955 
956     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
957     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
958     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
959     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
960     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
961     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
962     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
963     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
964     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
965     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
966 
967     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
968     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
969 
970     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
971     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
972 
973     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
974 
975     setOperationAction(ISD::AND , MVT::v4i1, Legal);
976     setOperationAction(ISD::OR , MVT::v4i1, Legal);
977     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
978 
979     if (!Subtarget.useCRBits())
980       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
981     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
982 
983     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
984     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
985 
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
988     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
989     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
990     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
991     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
992     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
993 
994     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
995     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
996 
997     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
998 
999     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1000     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1001     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1002     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1003 
1004     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1005     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1006     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1007     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1008 
1009     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1010     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1011 
1012     // These need to set FE_INEXACT, and so cannot be vectorized here.
1013     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1014     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1015 
1016     if (TM.Options.UnsafeFPMath) {
1017       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1018       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1019 
1020       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1021       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1022     } else {
1023       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1024       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1025 
1026       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1027       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1028     }
1029   }
1030 
1031   if (Subtarget.has64BitSupport())
1032     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1033 
1034   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1035 
1036   if (!isPPC64) {
1037     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1038     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1039   }
1040 
1041   setBooleanContents(ZeroOrOneBooleanContent);
1042 
1043   if (Subtarget.hasAltivec()) {
1044     // Altivec instructions set fields to all zeros or all ones.
1045     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1046   }
1047 
1048   if (!isPPC64) {
1049     // These libcalls are not available in 32-bit.
1050     setLibcallName(RTLIB::SHL_I128, nullptr);
1051     setLibcallName(RTLIB::SRL_I128, nullptr);
1052     setLibcallName(RTLIB::SRA_I128, nullptr);
1053   }
1054 
1055   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1056 
1057   // We have target-specific dag combine patterns for the following nodes:
1058   setTargetDAGCombine(ISD::SHL);
1059   setTargetDAGCombine(ISD::SRA);
1060   setTargetDAGCombine(ISD::SRL);
1061   setTargetDAGCombine(ISD::SINT_TO_FP);
1062   setTargetDAGCombine(ISD::BUILD_VECTOR);
1063   if (Subtarget.hasFPCVT())
1064     setTargetDAGCombine(ISD::UINT_TO_FP);
1065   setTargetDAGCombine(ISD::LOAD);
1066   setTargetDAGCombine(ISD::STORE);
1067   setTargetDAGCombine(ISD::BR_CC);
1068   if (Subtarget.useCRBits())
1069     setTargetDAGCombine(ISD::BRCOND);
1070   setTargetDAGCombine(ISD::BSWAP);
1071   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1072   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1073   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1074 
1075   setTargetDAGCombine(ISD::SIGN_EXTEND);
1076   setTargetDAGCombine(ISD::ZERO_EXTEND);
1077   setTargetDAGCombine(ISD::ANY_EXTEND);
1078 
1079   if (Subtarget.useCRBits()) {
1080     setTargetDAGCombine(ISD::TRUNCATE);
1081     setTargetDAGCombine(ISD::SETCC);
1082     setTargetDAGCombine(ISD::SELECT_CC);
1083   }
1084 
1085   // Use reciprocal estimates.
1086   if (TM.Options.UnsafeFPMath) {
1087     setTargetDAGCombine(ISD::FDIV);
1088     setTargetDAGCombine(ISD::FSQRT);
1089   }
1090 
1091   // Darwin long double math library functions have $LDBL128 appended.
1092   if (Subtarget.isDarwin()) {
1093     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1094     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1095     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1096     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1097     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1098     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1099     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1100     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1101     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1102     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1103   }
1104 
1105   if (EnableQuadPrecision) {
1106     setLibcallName(RTLIB::LOG_F128, "logf128");
1107     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1108     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1109     setLibcallName(RTLIB::EXP_F128, "expf128");
1110     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1111     setLibcallName(RTLIB::SIN_F128, "sinf128");
1112     setLibcallName(RTLIB::COS_F128, "cosf128");
1113     setLibcallName(RTLIB::POW_F128, "powf128");
1114     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1115     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1116     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1117     setLibcallName(RTLIB::REM_F128, "fmodf128");
1118   }
1119 
1120   // With 32 condition bits, we don't need to sink (and duplicate) compares
1121   // aggressively in CodeGenPrep.
1122   if (Subtarget.useCRBits()) {
1123     setHasMultipleConditionRegisters();
1124     setJumpIsExpensive();
1125   }
1126 
1127   setMinFunctionAlignment(2);
1128   if (Subtarget.isDarwin())
1129     setPrefFunctionAlignment(4);
1130 
1131   switch (Subtarget.getDarwinDirective()) {
1132   default: break;
1133   case PPC::DIR_970:
1134   case PPC::DIR_A2:
1135   case PPC::DIR_E500:
1136   case PPC::DIR_E500mc:
1137   case PPC::DIR_E5500:
1138   case PPC::DIR_PWR4:
1139   case PPC::DIR_PWR5:
1140   case PPC::DIR_PWR5X:
1141   case PPC::DIR_PWR6:
1142   case PPC::DIR_PWR6X:
1143   case PPC::DIR_PWR7:
1144   case PPC::DIR_PWR8:
1145   case PPC::DIR_PWR9:
1146     setPrefFunctionAlignment(4);
1147     setPrefLoopAlignment(4);
1148     break;
1149   }
1150 
1151   if (Subtarget.enableMachineScheduler())
1152     setSchedulingPreference(Sched::Source);
1153   else
1154     setSchedulingPreference(Sched::Hybrid);
1155 
1156   computeRegisterProperties(STI.getRegisterInfo());
1157 
1158   // The Freescale cores do better with aggressive inlining of memcpy and
1159   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1160   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1161       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1162     MaxStoresPerMemset = 32;
1163     MaxStoresPerMemsetOptSize = 16;
1164     MaxStoresPerMemcpy = 32;
1165     MaxStoresPerMemcpyOptSize = 8;
1166     MaxStoresPerMemmove = 32;
1167     MaxStoresPerMemmoveOptSize = 8;
1168   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1169     // The A2 also benefits from (very) aggressive inlining of memcpy and
1170     // friends. The overhead of a the function call, even when warm, can be
1171     // over one hundred cycles.
1172     MaxStoresPerMemset = 128;
1173     MaxStoresPerMemcpy = 128;
1174     MaxStoresPerMemmove = 128;
1175     MaxLoadsPerMemcmp = 128;
1176   } else {
1177     MaxLoadsPerMemcmp = 8;
1178     MaxLoadsPerMemcmpOptSize = 4;
1179   }
1180 }
1181 
1182 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1183 /// the desired ByVal argument alignment.
1184 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1185                              unsigned MaxMaxAlign) {
1186   if (MaxAlign == MaxMaxAlign)
1187     return;
1188   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1189     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1190       MaxAlign = 32;
1191     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1192       MaxAlign = 16;
1193   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1194     unsigned EltAlign = 0;
1195     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1196     if (EltAlign > MaxAlign)
1197       MaxAlign = EltAlign;
1198   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1199     for (auto *EltTy : STy->elements()) {
1200       unsigned EltAlign = 0;
1201       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1202       if (EltAlign > MaxAlign)
1203         MaxAlign = EltAlign;
1204       if (MaxAlign == MaxMaxAlign)
1205         break;
1206     }
1207   }
1208 }
1209 
1210 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1211 /// function arguments in the caller parameter area.
1212 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1213                                                   const DataLayout &DL) const {
1214   // Darwin passes everything on 4 byte boundary.
1215   if (Subtarget.isDarwin())
1216     return 4;
1217 
1218   // 16byte and wider vectors are passed on 16byte boundary.
1219   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1220   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1221   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1222     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1223   return Align;
1224 }
1225 
1226 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1227                                                           EVT VT) const {
1228   if (Subtarget.hasSPE() && VT == MVT::f64)
1229     return 2;
1230   return PPCTargetLowering::getNumRegisters(Context, VT);
1231 }
1232 
1233 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1234                                                      EVT VT) const {
1235   if (Subtarget.hasSPE() && VT == MVT::f64)
1236     return MVT::i32;
1237   return PPCTargetLowering::getRegisterType(Context, VT);
1238 }
1239 
1240 bool PPCTargetLowering::useSoftFloat() const {
1241   return Subtarget.useSoftFloat();
1242 }
1243 
1244 bool PPCTargetLowering::hasSPE() const {
1245   return Subtarget.hasSPE();
1246 }
1247 
1248 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1249   switch ((PPCISD::NodeType)Opcode) {
1250   case PPCISD::FIRST_NUMBER:    break;
1251   case PPCISD::FSEL:            return "PPCISD::FSEL";
1252   case PPCISD::FCFID:           return "PPCISD::FCFID";
1253   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1254   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1255   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1256   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1257   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1258   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1259   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1260   case PPCISD::FP_TO_UINT_IN_VSR:
1261                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1262   case PPCISD::FP_TO_SINT_IN_VSR:
1263                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1264   case PPCISD::FRE:             return "PPCISD::FRE";
1265   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1266   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1267   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1268   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1269   case PPCISD::VPERM:           return "PPCISD::VPERM";
1270   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1271   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1272   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1273   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1274   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1275   case PPCISD::CMPB:            return "PPCISD::CMPB";
1276   case PPCISD::Hi:              return "PPCISD::Hi";
1277   case PPCISD::Lo:              return "PPCISD::Lo";
1278   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1279   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1280   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1281   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1282   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1283   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1284   case PPCISD::SRL:             return "PPCISD::SRL";
1285   case PPCISD::SRA:             return "PPCISD::SRA";
1286   case PPCISD::SHL:             return "PPCISD::SHL";
1287   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1288   case PPCISD::CALL:            return "PPCISD::CALL";
1289   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1290   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1291   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1292   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1293   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1294   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1295   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1296   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1297   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1298   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1299   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1300   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1301   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1302   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1303   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1304   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1305   case PPCISD::VCMP:            return "PPCISD::VCMP";
1306   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1307   case PPCISD::LBRX:            return "PPCISD::LBRX";
1308   case PPCISD::STBRX:           return "PPCISD::STBRX";
1309   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1310   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1311   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1312   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1313   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1314   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1315   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1316   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1317   case PPCISD::ST_VSR_SCAL_INT:
1318                                 return "PPCISD::ST_VSR_SCAL_INT";
1319   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1320   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1321   case PPCISD::BDZ:             return "PPCISD::BDZ";
1322   case PPCISD::MFFS:            return "PPCISD::MFFS";
1323   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1324   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1325   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1326   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1327   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1328   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1329   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1330   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1331   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1332   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1333   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1334   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1335   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1336   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1337   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1338   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1339   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1340   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1341   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1342   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1343   case PPCISD::SC:              return "PPCISD::SC";
1344   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1345   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1346   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1347   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1348   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1349   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1350   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1351   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1352   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1353   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1354   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1355   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1356   }
1357   return nullptr;
1358 }
1359 
1360 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1361                                           EVT VT) const {
1362   if (!VT.isVector())
1363     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1364 
1365   if (Subtarget.hasQPX())
1366     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1367 
1368   return VT.changeVectorElementTypeToInteger();
1369 }
1370 
1371 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1372   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1373   return true;
1374 }
1375 
1376 //===----------------------------------------------------------------------===//
1377 // Node matching predicates, for use by the tblgen matching code.
1378 //===----------------------------------------------------------------------===//
1379 
1380 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1381 static bool isFloatingPointZero(SDValue Op) {
1382   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1383     return CFP->getValueAPF().isZero();
1384   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1385     // Maybe this has already been legalized into the constant pool?
1386     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1387       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1388         return CFP->getValueAPF().isZero();
1389   }
1390   return false;
1391 }
1392 
1393 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1394 /// true if Op is undef or if it matches the specified value.
1395 static bool isConstantOrUndef(int Op, int Val) {
1396   return Op < 0 || Op == Val;
1397 }
1398 
1399 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1400 /// VPKUHUM instruction.
1401 /// The ShuffleKind distinguishes between big-endian operations with
1402 /// two different inputs (0), either-endian operations with two identical
1403 /// inputs (1), and little-endian operations with two different inputs (2).
1404 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1405 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1406                                SelectionDAG &DAG) {
1407   bool IsLE = DAG.getDataLayout().isLittleEndian();
1408   if (ShuffleKind == 0) {
1409     if (IsLE)
1410       return false;
1411     for (unsigned i = 0; i != 16; ++i)
1412       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1413         return false;
1414   } else if (ShuffleKind == 2) {
1415     if (!IsLE)
1416       return false;
1417     for (unsigned i = 0; i != 16; ++i)
1418       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1419         return false;
1420   } else if (ShuffleKind == 1) {
1421     unsigned j = IsLE ? 0 : 1;
1422     for (unsigned i = 0; i != 8; ++i)
1423       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1424           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1425         return false;
1426   }
1427   return true;
1428 }
1429 
1430 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1431 /// VPKUWUM instruction.
1432 /// The ShuffleKind distinguishes between big-endian operations with
1433 /// two different inputs (0), either-endian operations with two identical
1434 /// inputs (1), and little-endian operations with two different inputs (2).
1435 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1436 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1437                                SelectionDAG &DAG) {
1438   bool IsLE = DAG.getDataLayout().isLittleEndian();
1439   if (ShuffleKind == 0) {
1440     if (IsLE)
1441       return false;
1442     for (unsigned i = 0; i != 16; i += 2)
1443       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1444           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1445         return false;
1446   } else if (ShuffleKind == 2) {
1447     if (!IsLE)
1448       return false;
1449     for (unsigned i = 0; i != 16; i += 2)
1450       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1451           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1452         return false;
1453   } else if (ShuffleKind == 1) {
1454     unsigned j = IsLE ? 0 : 2;
1455     for (unsigned i = 0; i != 8; i += 2)
1456       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1457           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1458           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1459           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1460         return false;
1461   }
1462   return true;
1463 }
1464 
1465 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1466 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1467 /// current subtarget.
1468 ///
1469 /// The ShuffleKind distinguishes between big-endian operations with
1470 /// two different inputs (0), either-endian operations with two identical
1471 /// inputs (1), and little-endian operations with two different inputs (2).
1472 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1473 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1474                                SelectionDAG &DAG) {
1475   const PPCSubtarget& Subtarget =
1476     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1477   if (!Subtarget.hasP8Vector())
1478     return false;
1479 
1480   bool IsLE = DAG.getDataLayout().isLittleEndian();
1481   if (ShuffleKind == 0) {
1482     if (IsLE)
1483       return false;
1484     for (unsigned i = 0; i != 16; i += 4)
1485       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1486           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1487           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1488           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1489         return false;
1490   } else if (ShuffleKind == 2) {
1491     if (!IsLE)
1492       return false;
1493     for (unsigned i = 0; i != 16; i += 4)
1494       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1495           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1496           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1497           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1498         return false;
1499   } else if (ShuffleKind == 1) {
1500     unsigned j = IsLE ? 0 : 4;
1501     for (unsigned i = 0; i != 8; i += 4)
1502       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1503           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1504           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1505           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1506           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1507           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1508           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1509           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1510         return false;
1511   }
1512   return true;
1513 }
1514 
1515 /// isVMerge - Common function, used to match vmrg* shuffles.
1516 ///
1517 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1518                      unsigned LHSStart, unsigned RHSStart) {
1519   if (N->getValueType(0) != MVT::v16i8)
1520     return false;
1521   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1522          "Unsupported merge size!");
1523 
1524   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1525     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1526       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1527                              LHSStart+j+i*UnitSize) ||
1528           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1529                              RHSStart+j+i*UnitSize))
1530         return false;
1531     }
1532   return true;
1533 }
1534 
1535 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1536 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1537 /// The ShuffleKind distinguishes between big-endian merges with two
1538 /// different inputs (0), either-endian merges with two identical inputs (1),
1539 /// and little-endian merges with two different inputs (2).  For the latter,
1540 /// the input operands are swapped (see PPCInstrAltivec.td).
1541 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1542                              unsigned ShuffleKind, SelectionDAG &DAG) {
1543   if (DAG.getDataLayout().isLittleEndian()) {
1544     if (ShuffleKind == 1) // unary
1545       return isVMerge(N, UnitSize, 0, 0);
1546     else if (ShuffleKind == 2) // swapped
1547       return isVMerge(N, UnitSize, 0, 16);
1548     else
1549       return false;
1550   } else {
1551     if (ShuffleKind == 1) // unary
1552       return isVMerge(N, UnitSize, 8, 8);
1553     else if (ShuffleKind == 0) // normal
1554       return isVMerge(N, UnitSize, 8, 24);
1555     else
1556       return false;
1557   }
1558 }
1559 
1560 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1561 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1562 /// The ShuffleKind distinguishes between big-endian merges with two
1563 /// different inputs (0), either-endian merges with two identical inputs (1),
1564 /// and little-endian merges with two different inputs (2).  For the latter,
1565 /// the input operands are swapped (see PPCInstrAltivec.td).
1566 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1567                              unsigned ShuffleKind, SelectionDAG &DAG) {
1568   if (DAG.getDataLayout().isLittleEndian()) {
1569     if (ShuffleKind == 1) // unary
1570       return isVMerge(N, UnitSize, 8, 8);
1571     else if (ShuffleKind == 2) // swapped
1572       return isVMerge(N, UnitSize, 8, 24);
1573     else
1574       return false;
1575   } else {
1576     if (ShuffleKind == 1) // unary
1577       return isVMerge(N, UnitSize, 0, 0);
1578     else if (ShuffleKind == 0) // normal
1579       return isVMerge(N, UnitSize, 0, 16);
1580     else
1581       return false;
1582   }
1583 }
1584 
1585 /**
1586  * Common function used to match vmrgew and vmrgow shuffles
1587  *
1588  * The indexOffset determines whether to look for even or odd words in
1589  * the shuffle mask. This is based on the of the endianness of the target
1590  * machine.
1591  *   - Little Endian:
1592  *     - Use offset of 0 to check for odd elements
1593  *     - Use offset of 4 to check for even elements
1594  *   - Big Endian:
1595  *     - Use offset of 0 to check for even elements
1596  *     - Use offset of 4 to check for odd elements
1597  * A detailed description of the vector element ordering for little endian and
1598  * big endian can be found at
1599  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1600  * Targeting your applications - what little endian and big endian IBM XL C/C++
1601  * compiler differences mean to you
1602  *
1603  * The mask to the shuffle vector instruction specifies the indices of the
1604  * elements from the two input vectors to place in the result. The elements are
1605  * numbered in array-access order, starting with the first vector. These vectors
1606  * are always of type v16i8, thus each vector will contain 16 elements of size
1607  * 8. More info on the shuffle vector can be found in the
1608  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1609  * Language Reference.
1610  *
1611  * The RHSStartValue indicates whether the same input vectors are used (unary)
1612  * or two different input vectors are used, based on the following:
1613  *   - If the instruction uses the same vector for both inputs, the range of the
1614  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1615  *     be 0.
1616  *   - If the instruction has two different vectors then the range of the
1617  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1618  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1619  *     to 31 specify elements in the second vector).
1620  *
1621  * \param[in] N The shuffle vector SD Node to analyze
1622  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1623  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1624  * vector to the shuffle_vector instruction
1625  * \return true iff this shuffle vector represents an even or odd word merge
1626  */
1627 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1628                      unsigned RHSStartValue) {
1629   if (N->getValueType(0) != MVT::v16i8)
1630     return false;
1631 
1632   for (unsigned i = 0; i < 2; ++i)
1633     for (unsigned j = 0; j < 4; ++j)
1634       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1635                              i*RHSStartValue+j+IndexOffset) ||
1636           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1637                              i*RHSStartValue+j+IndexOffset+8))
1638         return false;
1639   return true;
1640 }
1641 
1642 /**
1643  * Determine if the specified shuffle mask is suitable for the vmrgew or
1644  * vmrgow instructions.
1645  *
1646  * \param[in] N The shuffle vector SD Node to analyze
1647  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1648  * \param[in] ShuffleKind Identify the type of merge:
1649  *   - 0 = big-endian merge with two different inputs;
1650  *   - 1 = either-endian merge with two identical inputs;
1651  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1652  *     little-endian merges).
1653  * \param[in] DAG The current SelectionDAG
1654  * \return true iff this shuffle mask
1655  */
1656 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1657                               unsigned ShuffleKind, SelectionDAG &DAG) {
1658   if (DAG.getDataLayout().isLittleEndian()) {
1659     unsigned indexOffset = CheckEven ? 4 : 0;
1660     if (ShuffleKind == 1) // Unary
1661       return isVMerge(N, indexOffset, 0);
1662     else if (ShuffleKind == 2) // swapped
1663       return isVMerge(N, indexOffset, 16);
1664     else
1665       return false;
1666   }
1667   else {
1668     unsigned indexOffset = CheckEven ? 0 : 4;
1669     if (ShuffleKind == 1) // Unary
1670       return isVMerge(N, indexOffset, 0);
1671     else if (ShuffleKind == 0) // Normal
1672       return isVMerge(N, indexOffset, 16);
1673     else
1674       return false;
1675   }
1676   return false;
1677 }
1678 
1679 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1680 /// amount, otherwise return -1.
1681 /// The ShuffleKind distinguishes between big-endian operations with two
1682 /// different inputs (0), either-endian operations with two identical inputs
1683 /// (1), and little-endian operations with two different inputs (2).  For the
1684 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1685 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1686                              SelectionDAG &DAG) {
1687   if (N->getValueType(0) != MVT::v16i8)
1688     return -1;
1689 
1690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1691 
1692   // Find the first non-undef value in the shuffle mask.
1693   unsigned i;
1694   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1695     /*search*/;
1696 
1697   if (i == 16) return -1;  // all undef.
1698 
1699   // Otherwise, check to see if the rest of the elements are consecutively
1700   // numbered from this value.
1701   unsigned ShiftAmt = SVOp->getMaskElt(i);
1702   if (ShiftAmt < i) return -1;
1703 
1704   ShiftAmt -= i;
1705   bool isLE = DAG.getDataLayout().isLittleEndian();
1706 
1707   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1708     // Check the rest of the elements to see if they are consecutive.
1709     for (++i; i != 16; ++i)
1710       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1711         return -1;
1712   } else if (ShuffleKind == 1) {
1713     // Check the rest of the elements to see if they are consecutive.
1714     for (++i; i != 16; ++i)
1715       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1716         return -1;
1717   } else
1718     return -1;
1719 
1720   if (isLE)
1721     ShiftAmt = 16 - ShiftAmt;
1722 
1723   return ShiftAmt;
1724 }
1725 
1726 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1727 /// specifies a splat of a single element that is suitable for input to
1728 /// VSPLTB/VSPLTH/VSPLTW.
1729 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1730   assert(N->getValueType(0) == MVT::v16i8 &&
1731          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1732 
1733   // The consecutive indices need to specify an element, not part of two
1734   // different elements.  So abandon ship early if this isn't the case.
1735   if (N->getMaskElt(0) % EltSize != 0)
1736     return false;
1737 
1738   // This is a splat operation if each element of the permute is the same, and
1739   // if the value doesn't reference the second vector.
1740   unsigned ElementBase = N->getMaskElt(0);
1741 
1742   // FIXME: Handle UNDEF elements too!
1743   if (ElementBase >= 16)
1744     return false;
1745 
1746   // Check that the indices are consecutive, in the case of a multi-byte element
1747   // splatted with a v16i8 mask.
1748   for (unsigned i = 1; i != EltSize; ++i)
1749     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1750       return false;
1751 
1752   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1753     if (N->getMaskElt(i) < 0) continue;
1754     for (unsigned j = 0; j != EltSize; ++j)
1755       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1756         return false;
1757   }
1758   return true;
1759 }
1760 
1761 /// Check that the mask is shuffling N byte elements. Within each N byte
1762 /// element of the mask, the indices could be either in increasing or
1763 /// decreasing order as long as they are consecutive.
1764 /// \param[in] N the shuffle vector SD Node to analyze
1765 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1766 /// Word/DoubleWord/QuadWord).
1767 /// \param[in] StepLen the delta indices number among the N byte element, if
1768 /// the mask is in increasing/decreasing order then it is 1/-1.
1769 /// \return true iff the mask is shuffling N byte elements.
1770 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1771                                    int StepLen) {
1772   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1773          "Unexpected element width.");
1774   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1775 
1776   unsigned NumOfElem = 16 / Width;
1777   unsigned MaskVal[16]; //  Width is never greater than 16
1778   for (unsigned i = 0; i < NumOfElem; ++i) {
1779     MaskVal[0] = N->getMaskElt(i * Width);
1780     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1781       return false;
1782     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1783       return false;
1784     }
1785 
1786     for (unsigned int j = 1; j < Width; ++j) {
1787       MaskVal[j] = N->getMaskElt(i * Width + j);
1788       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1789         return false;
1790       }
1791     }
1792   }
1793 
1794   return true;
1795 }
1796 
1797 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1798                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1799   if (!isNByteElemShuffleMask(N, 4, 1))
1800     return false;
1801 
1802   // Now we look at mask elements 0,4,8,12
1803   unsigned M0 = N->getMaskElt(0) / 4;
1804   unsigned M1 = N->getMaskElt(4) / 4;
1805   unsigned M2 = N->getMaskElt(8) / 4;
1806   unsigned M3 = N->getMaskElt(12) / 4;
1807   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1808   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1809 
1810   // Below, let H and L be arbitrary elements of the shuffle mask
1811   // where H is in the range [4,7] and L is in the range [0,3].
1812   // H, 1, 2, 3 or L, 5, 6, 7
1813   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1814       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1815     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1816     InsertAtByte = IsLE ? 12 : 0;
1817     Swap = M0 < 4;
1818     return true;
1819   }
1820   // 0, H, 2, 3 or 4, L, 6, 7
1821   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1822       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1823     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1824     InsertAtByte = IsLE ? 8 : 4;
1825     Swap = M1 < 4;
1826     return true;
1827   }
1828   // 0, 1, H, 3 or 4, 5, L, 7
1829   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1830       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1831     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1832     InsertAtByte = IsLE ? 4 : 8;
1833     Swap = M2 < 4;
1834     return true;
1835   }
1836   // 0, 1, 2, H or 4, 5, 6, L
1837   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1838       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1839     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1840     InsertAtByte = IsLE ? 0 : 12;
1841     Swap = M3 < 4;
1842     return true;
1843   }
1844 
1845   // If both vector operands for the shuffle are the same vector, the mask will
1846   // contain only elements from the first one and the second one will be undef.
1847   if (N->getOperand(1).isUndef()) {
1848     ShiftElts = 0;
1849     Swap = true;
1850     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1851     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1852       InsertAtByte = IsLE ? 12 : 0;
1853       return true;
1854     }
1855     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1856       InsertAtByte = IsLE ? 8 : 4;
1857       return true;
1858     }
1859     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1860       InsertAtByte = IsLE ? 4 : 8;
1861       return true;
1862     }
1863     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1864       InsertAtByte = IsLE ? 0 : 12;
1865       return true;
1866     }
1867   }
1868 
1869   return false;
1870 }
1871 
1872 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1873                                bool &Swap, bool IsLE) {
1874   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1875   // Ensure each byte index of the word is consecutive.
1876   if (!isNByteElemShuffleMask(N, 4, 1))
1877     return false;
1878 
1879   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1880   unsigned M0 = N->getMaskElt(0) / 4;
1881   unsigned M1 = N->getMaskElt(4) / 4;
1882   unsigned M2 = N->getMaskElt(8) / 4;
1883   unsigned M3 = N->getMaskElt(12) / 4;
1884 
1885   // If both vector operands for the shuffle are the same vector, the mask will
1886   // contain only elements from the first one and the second one will be undef.
1887   if (N->getOperand(1).isUndef()) {
1888     assert(M0 < 4 && "Indexing into an undef vector?");
1889     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1890       return false;
1891 
1892     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1893     Swap = false;
1894     return true;
1895   }
1896 
1897   // Ensure each word index of the ShuffleVector Mask is consecutive.
1898   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1899     return false;
1900 
1901   if (IsLE) {
1902     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1903       // Input vectors don't need to be swapped if the leading element
1904       // of the result is one of the 3 left elements of the second vector
1905       // (or if there is no shift to be done at all).
1906       Swap = false;
1907       ShiftElts = (8 - M0) % 8;
1908     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1909       // Input vectors need to be swapped if the leading element
1910       // of the result is one of the 3 left elements of the first vector
1911       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1912       Swap = true;
1913       ShiftElts = (4 - M0) % 4;
1914     }
1915 
1916     return true;
1917   } else {                                          // BE
1918     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1919       // Input vectors don't need to be swapped if the leading element
1920       // of the result is one of the 4 elements of the first vector.
1921       Swap = false;
1922       ShiftElts = M0;
1923     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1924       // Input vectors need to be swapped if the leading element
1925       // of the result is one of the 4 elements of the right vector.
1926       Swap = true;
1927       ShiftElts = M0 - 4;
1928     }
1929 
1930     return true;
1931   }
1932 }
1933 
1934 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1935   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1936 
1937   if (!isNByteElemShuffleMask(N, Width, -1))
1938     return false;
1939 
1940   for (int i = 0; i < 16; i += Width)
1941     if (N->getMaskElt(i) != i + Width - 1)
1942       return false;
1943 
1944   return true;
1945 }
1946 
1947 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1948   return isXXBRShuffleMaskHelper(N, 2);
1949 }
1950 
1951 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1952   return isXXBRShuffleMaskHelper(N, 4);
1953 }
1954 
1955 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1956   return isXXBRShuffleMaskHelper(N, 8);
1957 }
1958 
1959 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1960   return isXXBRShuffleMaskHelper(N, 16);
1961 }
1962 
1963 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1964 /// if the inputs to the instruction should be swapped and set \p DM to the
1965 /// value for the immediate.
1966 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1967 /// AND element 0 of the result comes from the first input (LE) or second input
1968 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1969 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1970 /// mask.
1971 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1972                                bool &Swap, bool IsLE) {
1973   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1974 
1975   // Ensure each byte index of the double word is consecutive.
1976   if (!isNByteElemShuffleMask(N, 8, 1))
1977     return false;
1978 
1979   unsigned M0 = N->getMaskElt(0) / 8;
1980   unsigned M1 = N->getMaskElt(8) / 8;
1981   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1982 
1983   // If both vector operands for the shuffle are the same vector, the mask will
1984   // contain only elements from the first one and the second one will be undef.
1985   if (N->getOperand(1).isUndef()) {
1986     if ((M0 | M1) < 2) {
1987       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1988       Swap = false;
1989       return true;
1990     } else
1991       return false;
1992   }
1993 
1994   if (IsLE) {
1995     if (M0 > 1 && M1 < 2) {
1996       Swap = false;
1997     } else if (M0 < 2 && M1 > 1) {
1998       M0 = (M0 + 2) % 4;
1999       M1 = (M1 + 2) % 4;
2000       Swap = true;
2001     } else
2002       return false;
2003 
2004     // Note: if control flow comes here that means Swap is already set above
2005     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2006     return true;
2007   } else { // BE
2008     if (M0 < 2 && M1 > 1) {
2009       Swap = false;
2010     } else if (M0 > 1 && M1 < 2) {
2011       M0 = (M0 + 2) % 4;
2012       M1 = (M1 + 2) % 4;
2013       Swap = true;
2014     } else
2015       return false;
2016 
2017     // Note: if control flow comes here that means Swap is already set above
2018     DM = (M0 << 1) + (M1 & 1);
2019     return true;
2020   }
2021 }
2022 
2023 
2024 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2025 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2026 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2027                                 SelectionDAG &DAG) {
2028   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2029   assert(isSplatShuffleMask(SVOp, EltSize));
2030   if (DAG.getDataLayout().isLittleEndian())
2031     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2032   else
2033     return SVOp->getMaskElt(0) / EltSize;
2034 }
2035 
2036 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2037 /// by using a vspltis[bhw] instruction of the specified element size, return
2038 /// the constant being splatted.  The ByteSize field indicates the number of
2039 /// bytes of each element [124] -> [bhw].
2040 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2041   SDValue OpVal(nullptr, 0);
2042 
2043   // If ByteSize of the splat is bigger than the element size of the
2044   // build_vector, then we have a case where we are checking for a splat where
2045   // multiple elements of the buildvector are folded together into a single
2046   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2047   unsigned EltSize = 16/N->getNumOperands();
2048   if (EltSize < ByteSize) {
2049     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2050     SDValue UniquedVals[4];
2051     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2052 
2053     // See if all of the elements in the buildvector agree across.
2054     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2055       if (N->getOperand(i).isUndef()) continue;
2056       // If the element isn't a constant, bail fully out.
2057       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2058 
2059       if (!UniquedVals[i&(Multiple-1)].getNode())
2060         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2061       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2062         return SDValue();  // no match.
2063     }
2064 
2065     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2066     // either constant or undef values that are identical for each chunk.  See
2067     // if these chunks can form into a larger vspltis*.
2068 
2069     // Check to see if all of the leading entries are either 0 or -1.  If
2070     // neither, then this won't fit into the immediate field.
2071     bool LeadingZero = true;
2072     bool LeadingOnes = true;
2073     for (unsigned i = 0; i != Multiple-1; ++i) {
2074       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2075 
2076       LeadingZero &= isNullConstant(UniquedVals[i]);
2077       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2078     }
2079     // Finally, check the least significant entry.
2080     if (LeadingZero) {
2081       if (!UniquedVals[Multiple-1].getNode())
2082         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2083       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2084       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2085         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2086     }
2087     if (LeadingOnes) {
2088       if (!UniquedVals[Multiple-1].getNode())
2089         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2090       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2091       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2092         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2093     }
2094 
2095     return SDValue();
2096   }
2097 
2098   // Check to see if this buildvec has a single non-undef value in its elements.
2099   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2100     if (N->getOperand(i).isUndef()) continue;
2101     if (!OpVal.getNode())
2102       OpVal = N->getOperand(i);
2103     else if (OpVal != N->getOperand(i))
2104       return SDValue();
2105   }
2106 
2107   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2108 
2109   unsigned ValSizeInBytes = EltSize;
2110   uint64_t Value = 0;
2111   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2112     Value = CN->getZExtValue();
2113   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2114     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2115     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2116   }
2117 
2118   // If the splat value is larger than the element value, then we can never do
2119   // this splat.  The only case that we could fit the replicated bits into our
2120   // immediate field for would be zero, and we prefer to use vxor for it.
2121   if (ValSizeInBytes < ByteSize) return SDValue();
2122 
2123   // If the element value is larger than the splat value, check if it consists
2124   // of a repeated bit pattern of size ByteSize.
2125   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2126     return SDValue();
2127 
2128   // Properly sign extend the value.
2129   int MaskVal = SignExtend32(Value, ByteSize * 8);
2130 
2131   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2132   if (MaskVal == 0) return SDValue();
2133 
2134   // Finally, if this value fits in a 5 bit sext field, return it
2135   if (SignExtend32<5>(MaskVal) == MaskVal)
2136     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2137   return SDValue();
2138 }
2139 
2140 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2141 /// amount, otherwise return -1.
2142 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2143   EVT VT = N->getValueType(0);
2144   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2145     return -1;
2146 
2147   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2148 
2149   // Find the first non-undef value in the shuffle mask.
2150   unsigned i;
2151   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2152     /*search*/;
2153 
2154   if (i == 4) return -1;  // all undef.
2155 
2156   // Otherwise, check to see if the rest of the elements are consecutively
2157   // numbered from this value.
2158   unsigned ShiftAmt = SVOp->getMaskElt(i);
2159   if (ShiftAmt < i) return -1;
2160   ShiftAmt -= i;
2161 
2162   // Check the rest of the elements to see if they are consecutive.
2163   for (++i; i != 4; ++i)
2164     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2165       return -1;
2166 
2167   return ShiftAmt;
2168 }
2169 
2170 //===----------------------------------------------------------------------===//
2171 //  Addressing Mode Selection
2172 //===----------------------------------------------------------------------===//
2173 
2174 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2175 /// or 64-bit immediate, and if the value can be accurately represented as a
2176 /// sign extension from a 16-bit value.  If so, this returns true and the
2177 /// immediate.
2178 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2179   if (!isa<ConstantSDNode>(N))
2180     return false;
2181 
2182   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2183   if (N->getValueType(0) == MVT::i32)
2184     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2185   else
2186     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2187 }
2188 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2189   return isIntS16Immediate(Op.getNode(), Imm);
2190 }
2191 
2192 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2193 /// can be represented as an indexed [r+r] operation.  Returns false if it
2194 /// can be more efficiently represented with [r+imm].
2195 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2196                                             SDValue &Index,
2197                                             SelectionDAG &DAG) const {
2198   int16_t imm = 0;
2199   if (N.getOpcode() == ISD::ADD) {
2200     if (isIntS16Immediate(N.getOperand(1), imm))
2201       return false;    // r+i
2202     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2203       return false;    // r+i
2204 
2205     Base = N.getOperand(0);
2206     Index = N.getOperand(1);
2207     return true;
2208   } else if (N.getOpcode() == ISD::OR) {
2209     if (isIntS16Immediate(N.getOperand(1), imm))
2210       return false;    // r+i can fold it if we can.
2211 
2212     // If this is an or of disjoint bitfields, we can codegen this as an add
2213     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2214     // disjoint.
2215     KnownBits LHSKnown, RHSKnown;
2216     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2217 
2218     if (LHSKnown.Zero.getBoolValue()) {
2219       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2220       // If all of the bits are known zero on the LHS or RHS, the add won't
2221       // carry.
2222       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2223         Base = N.getOperand(0);
2224         Index = N.getOperand(1);
2225         return true;
2226       }
2227     }
2228   }
2229 
2230   return false;
2231 }
2232 
2233 // If we happen to be doing an i64 load or store into a stack slot that has
2234 // less than a 4-byte alignment, then the frame-index elimination may need to
2235 // use an indexed load or store instruction (because the offset may not be a
2236 // multiple of 4). The extra register needed to hold the offset comes from the
2237 // register scavenger, and it is possible that the scavenger will need to use
2238 // an emergency spill slot. As a result, we need to make sure that a spill slot
2239 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2240 // stack slot.
2241 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2242   // FIXME: This does not handle the LWA case.
2243   if (VT != MVT::i64)
2244     return;
2245 
2246   // NOTE: We'll exclude negative FIs here, which come from argument
2247   // lowering, because there are no known test cases triggering this problem
2248   // using packed structures (or similar). We can remove this exclusion if
2249   // we find such a test case. The reason why this is so test-case driven is
2250   // because this entire 'fixup' is only to prevent crashes (from the
2251   // register scavenger) on not-really-valid inputs. For example, if we have:
2252   //   %a = alloca i1
2253   //   %b = bitcast i1* %a to i64*
2254   //   store i64* a, i64 b
2255   // then the store should really be marked as 'align 1', but is not. If it
2256   // were marked as 'align 1' then the indexed form would have been
2257   // instruction-selected initially, and the problem this 'fixup' is preventing
2258   // won't happen regardless.
2259   if (FrameIdx < 0)
2260     return;
2261 
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   MachineFrameInfo &MFI = MF.getFrameInfo();
2264 
2265   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2266   if (Align >= 4)
2267     return;
2268 
2269   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2270   FuncInfo->setHasNonRISpills();
2271 }
2272 
2273 /// Returns true if the address N can be represented by a base register plus
2274 /// a signed 16-bit displacement [r+imm], and if it is not better
2275 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2276 /// displacements that are multiples of that value.
2277 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2278                                             SDValue &Base,
2279                                             SelectionDAG &DAG,
2280                                             unsigned Alignment) const {
2281   // FIXME dl should come from parent load or store, not from address
2282   SDLoc dl(N);
2283   // If this can be more profitably realized as r+r, fail.
2284   if (SelectAddressRegReg(N, Disp, Base, DAG))
2285     return false;
2286 
2287   if (N.getOpcode() == ISD::ADD) {
2288     int16_t imm = 0;
2289     if (isIntS16Immediate(N.getOperand(1), imm) &&
2290         (!Alignment || (imm % Alignment) == 0)) {
2291       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2292       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2293         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2294         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2295       } else {
2296         Base = N.getOperand(0);
2297       }
2298       return true; // [r+i]
2299     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2300       // Match LOAD (ADD (X, Lo(G))).
2301       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2302              && "Cannot handle constant offsets yet!");
2303       Disp = N.getOperand(1).getOperand(0);  // The global address.
2304       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2305              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2306              Disp.getOpcode() == ISD::TargetConstantPool ||
2307              Disp.getOpcode() == ISD::TargetJumpTable);
2308       Base = N.getOperand(0);
2309       return true;  // [&g+r]
2310     }
2311   } else if (N.getOpcode() == ISD::OR) {
2312     int16_t imm = 0;
2313     if (isIntS16Immediate(N.getOperand(1), imm) &&
2314         (!Alignment || (imm % Alignment) == 0)) {
2315       // If this is an or of disjoint bitfields, we can codegen this as an add
2316       // (for better address arithmetic) if the LHS and RHS of the OR are
2317       // provably disjoint.
2318       KnownBits LHSKnown;
2319       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2320 
2321       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2322         // If all of the bits are known zero on the LHS or RHS, the add won't
2323         // carry.
2324         if (FrameIndexSDNode *FI =
2325               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2326           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2327           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2328         } else {
2329           Base = N.getOperand(0);
2330         }
2331         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2332         return true;
2333       }
2334     }
2335   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2336     // Loading from a constant address.
2337 
2338     // If this address fits entirely in a 16-bit sext immediate field, codegen
2339     // this as "d, 0"
2340     int16_t Imm;
2341     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2342       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2343       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2344                              CN->getValueType(0));
2345       return true;
2346     }
2347 
2348     // Handle 32-bit sext immediates with LIS + addr mode.
2349     if ((CN->getValueType(0) == MVT::i32 ||
2350          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2351         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2352       int Addr = (int)CN->getZExtValue();
2353 
2354       // Otherwise, break this down into an LIS + disp.
2355       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2356 
2357       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2358                                    MVT::i32);
2359       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2360       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2361       return true;
2362     }
2363   }
2364 
2365   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2366   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2367     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2368     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2369   } else
2370     Base = N;
2371   return true;      // [r+0]
2372 }
2373 
2374 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2375 /// represented as an indexed [r+r] operation.
2376 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2377                                                 SDValue &Index,
2378                                                 SelectionDAG &DAG) const {
2379   // Check to see if we can easily represent this as an [r+r] address.  This
2380   // will fail if it thinks that the address is more profitably represented as
2381   // reg+imm, e.g. where imm = 0.
2382   if (SelectAddressRegReg(N, Base, Index, DAG))
2383     return true;
2384 
2385   // If the address is the result of an add, we will utilize the fact that the
2386   // address calculation includes an implicit add.  However, we can reduce
2387   // register pressure if we do not materialize a constant just for use as the
2388   // index register.  We only get rid of the add if it is not an add of a
2389   // value and a 16-bit signed constant and both have a single use.
2390   int16_t imm = 0;
2391   if (N.getOpcode() == ISD::ADD &&
2392       (!isIntS16Immediate(N.getOperand(1), imm) ||
2393        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2394     Base = N.getOperand(0);
2395     Index = N.getOperand(1);
2396     return true;
2397   }
2398 
2399   // Otherwise, do it the hard way, using R0 as the base register.
2400   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2401                          N.getValueType());
2402   Index = N;
2403   return true;
2404 }
2405 
2406 /// getPreIndexedAddressParts - returns true by value, base pointer and
2407 /// offset pointer and addressing mode by reference if the node's address
2408 /// can be legally represented as pre-indexed load / store address.
2409 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2410                                                   SDValue &Offset,
2411                                                   ISD::MemIndexedMode &AM,
2412                                                   SelectionDAG &DAG) const {
2413   if (DisablePPCPreinc) return false;
2414 
2415   bool isLoad = true;
2416   SDValue Ptr;
2417   EVT VT;
2418   unsigned Alignment;
2419   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2420     Ptr = LD->getBasePtr();
2421     VT = LD->getMemoryVT();
2422     Alignment = LD->getAlignment();
2423   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2424     Ptr = ST->getBasePtr();
2425     VT  = ST->getMemoryVT();
2426     Alignment = ST->getAlignment();
2427     isLoad = false;
2428   } else
2429     return false;
2430 
2431   // PowerPC doesn't have preinc load/store instructions for vectors (except
2432   // for QPX, which does have preinc r+r forms).
2433   if (VT.isVector()) {
2434     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2435       return false;
2436     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2437       AM = ISD::PRE_INC;
2438       return true;
2439     }
2440   }
2441 
2442   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2443     // Common code will reject creating a pre-inc form if the base pointer
2444     // is a frame index, or if N is a store and the base pointer is either
2445     // the same as or a predecessor of the value being stored.  Check for
2446     // those situations here, and try with swapped Base/Offset instead.
2447     bool Swap = false;
2448 
2449     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2450       Swap = true;
2451     else if (!isLoad) {
2452       SDValue Val = cast<StoreSDNode>(N)->getValue();
2453       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2454         Swap = true;
2455     }
2456 
2457     if (Swap)
2458       std::swap(Base, Offset);
2459 
2460     AM = ISD::PRE_INC;
2461     return true;
2462   }
2463 
2464   // LDU/STU can only handle immediates that are a multiple of 4.
2465   if (VT != MVT::i64) {
2466     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2467       return false;
2468   } else {
2469     // LDU/STU need an address with at least 4-byte alignment.
2470     if (Alignment < 4)
2471       return false;
2472 
2473     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2474       return false;
2475   }
2476 
2477   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2478     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2479     // sext i32 to i64 when addr mode is r+i.
2480     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2481         LD->getExtensionType() == ISD::SEXTLOAD &&
2482         isa<ConstantSDNode>(Offset))
2483       return false;
2484   }
2485 
2486   AM = ISD::PRE_INC;
2487   return true;
2488 }
2489 
2490 //===----------------------------------------------------------------------===//
2491 //  LowerOperation implementation
2492 //===----------------------------------------------------------------------===//
2493 
2494 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2495 /// and LoOpFlags to the target MO flags.
2496 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2497                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2498                                const GlobalValue *GV = nullptr) {
2499   HiOpFlags = PPCII::MO_HA;
2500   LoOpFlags = PPCII::MO_LO;
2501 
2502   // Don't use the pic base if not in PIC relocation model.
2503   if (IsPIC) {
2504     HiOpFlags |= PPCII::MO_PIC_FLAG;
2505     LoOpFlags |= PPCII::MO_PIC_FLAG;
2506   }
2507 
2508   // If this is a reference to a global value that requires a non-lazy-ptr, make
2509   // sure that instruction lowering adds it.
2510   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2511     HiOpFlags |= PPCII::MO_NLP_FLAG;
2512     LoOpFlags |= PPCII::MO_NLP_FLAG;
2513 
2514     if (GV->hasHiddenVisibility()) {
2515       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2516       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2517     }
2518   }
2519 }
2520 
2521 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2522                              SelectionDAG &DAG) {
2523   SDLoc DL(HiPart);
2524   EVT PtrVT = HiPart.getValueType();
2525   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2526 
2527   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2528   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2529 
2530   // With PIC, the first instruction is actually "GR+hi(&G)".
2531   if (isPIC)
2532     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2533                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2534 
2535   // Generate non-pic code that has direct accesses to the constant pool.
2536   // The address of the global is just (hi(&g)+lo(&g)).
2537   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2538 }
2539 
2540 static void setUsesTOCBasePtr(MachineFunction &MF) {
2541   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2542   FuncInfo->setUsesTOCBasePtr();
2543 }
2544 
2545 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2546   setUsesTOCBasePtr(DAG.getMachineFunction());
2547 }
2548 
2549 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2550                            SDValue GA) {
2551   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2552   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2553                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2554 
2555   SDValue Ops[] = { GA, Reg };
2556   return DAG.getMemIntrinsicNode(
2557       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2558       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2559       MachineMemOperand::MOLoad);
2560 }
2561 
2562 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2563                                              SelectionDAG &DAG) const {
2564   EVT PtrVT = Op.getValueType();
2565   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2566   const Constant *C = CP->getConstVal();
2567 
2568   // 64-bit SVR4 ABI code is always position-independent.
2569   // The actual address of the GlobalValue is stored in the TOC.
2570   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2571     setUsesTOCBasePtr(DAG);
2572     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2573     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2574   }
2575 
2576   unsigned MOHiFlag, MOLoFlag;
2577   bool IsPIC = isPositionIndependent();
2578   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2579 
2580   if (IsPIC && Subtarget.isSVR4ABI()) {
2581     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2582                                            PPCII::MO_PIC_FLAG);
2583     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2584   }
2585 
2586   SDValue CPIHi =
2587     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2588   SDValue CPILo =
2589     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2590   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2591 }
2592 
2593 // For 64-bit PowerPC, prefer the more compact relative encodings.
2594 // This trades 32 bits per jump table entry for one or two instructions
2595 // on the jump site.
2596 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2597   if (isJumpTableRelative())
2598     return MachineJumpTableInfo::EK_LabelDifference32;
2599 
2600   return TargetLowering::getJumpTableEncoding();
2601 }
2602 
2603 bool PPCTargetLowering::isJumpTableRelative() const {
2604   if (Subtarget.isPPC64())
2605     return true;
2606   return TargetLowering::isJumpTableRelative();
2607 }
2608 
2609 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2610                                                     SelectionDAG &DAG) const {
2611   if (!Subtarget.isPPC64())
2612     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2613 
2614   switch (getTargetMachine().getCodeModel()) {
2615   case CodeModel::Small:
2616   case CodeModel::Medium:
2617     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2618   default:
2619     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2620                        getPointerTy(DAG.getDataLayout()));
2621   }
2622 }
2623 
2624 const MCExpr *
2625 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2626                                                 unsigned JTI,
2627                                                 MCContext &Ctx) const {
2628   if (!Subtarget.isPPC64())
2629     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2630 
2631   switch (getTargetMachine().getCodeModel()) {
2632   case CodeModel::Small:
2633   case CodeModel::Medium:
2634     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2635   default:
2636     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2637   }
2638 }
2639 
2640 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2641   EVT PtrVT = Op.getValueType();
2642   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2643 
2644   // 64-bit SVR4 ABI code is always position-independent.
2645   // The actual address of the GlobalValue is stored in the TOC.
2646   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2647     setUsesTOCBasePtr(DAG);
2648     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2649     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2650   }
2651 
2652   unsigned MOHiFlag, MOLoFlag;
2653   bool IsPIC = isPositionIndependent();
2654   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2655 
2656   if (IsPIC && Subtarget.isSVR4ABI()) {
2657     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2658                                         PPCII::MO_PIC_FLAG);
2659     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2660   }
2661 
2662   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2663   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2664   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2665 }
2666 
2667 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2668                                              SelectionDAG &DAG) const {
2669   EVT PtrVT = Op.getValueType();
2670   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2671   const BlockAddress *BA = BASDN->getBlockAddress();
2672 
2673   // 64-bit SVR4 ABI code is always position-independent.
2674   // The actual BlockAddress is stored in the TOC.
2675   if (Subtarget.isSVR4ABI() && isPositionIndependent()) {
2676     if (Subtarget.isPPC64())
2677       setUsesTOCBasePtr(DAG);
2678     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2679     return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2680   }
2681 
2682   unsigned MOHiFlag, MOLoFlag;
2683   bool IsPIC = isPositionIndependent();
2684   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2685   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2686   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2687   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2688 }
2689 
2690 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2691                                               SelectionDAG &DAG) const {
2692   // FIXME: TLS addresses currently use medium model code sequences,
2693   // which is the most useful form.  Eventually support for small and
2694   // large models could be added if users need it, at the cost of
2695   // additional complexity.
2696   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2697   if (DAG.getTarget().useEmulatedTLS())
2698     return LowerToTLSEmulatedModel(GA, DAG);
2699 
2700   SDLoc dl(GA);
2701   const GlobalValue *GV = GA->getGlobal();
2702   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2703   bool is64bit = Subtarget.isPPC64();
2704   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2705   PICLevel::Level picLevel = M->getPICLevel();
2706 
2707   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2708 
2709   if (Model == TLSModel::LocalExec) {
2710     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2711                                                PPCII::MO_TPREL_HA);
2712     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2713                                                PPCII::MO_TPREL_LO);
2714     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2715                              : DAG.getRegister(PPC::R2, MVT::i32);
2716 
2717     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2718     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2719   }
2720 
2721   if (Model == TLSModel::InitialExec) {
2722     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2723     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2724                                                 PPCII::MO_TLS);
2725     SDValue GOTPtr;
2726     if (is64bit) {
2727       setUsesTOCBasePtr(DAG);
2728       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2729       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2730                            PtrVT, GOTReg, TGA);
2731     } else
2732       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2733     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2734                                    PtrVT, TGA, GOTPtr);
2735     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2736   }
2737 
2738   if (Model == TLSModel::GeneralDynamic) {
2739     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2740     SDValue GOTPtr;
2741     if (is64bit) {
2742       setUsesTOCBasePtr(DAG);
2743       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2744       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2745                                    GOTReg, TGA);
2746     } else {
2747       if (picLevel == PICLevel::SmallPIC)
2748         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2749       else
2750         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2751     }
2752     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2753                        GOTPtr, TGA, TGA);
2754   }
2755 
2756   if (Model == TLSModel::LocalDynamic) {
2757     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2758     SDValue GOTPtr;
2759     if (is64bit) {
2760       setUsesTOCBasePtr(DAG);
2761       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2762       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2763                            GOTReg, TGA);
2764     } else {
2765       if (picLevel == PICLevel::SmallPIC)
2766         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2767       else
2768         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2769     }
2770     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2771                                   PtrVT, GOTPtr, TGA, TGA);
2772     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2773                                       PtrVT, TLSAddr, TGA);
2774     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2775   }
2776 
2777   llvm_unreachable("Unknown TLS model!");
2778 }
2779 
2780 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2781                                               SelectionDAG &DAG) const {
2782   EVT PtrVT = Op.getValueType();
2783   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2784   SDLoc DL(GSDN);
2785   const GlobalValue *GV = GSDN->getGlobal();
2786 
2787   // 64-bit SVR4 ABI code is always position-independent.
2788   // The actual address of the GlobalValue is stored in the TOC.
2789   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2790     setUsesTOCBasePtr(DAG);
2791     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2792     return getTOCEntry(DAG, DL, true, GA);
2793   }
2794 
2795   unsigned MOHiFlag, MOLoFlag;
2796   bool IsPIC = isPositionIndependent();
2797   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2798 
2799   if (IsPIC && Subtarget.isSVR4ABI()) {
2800     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2801                                             GSDN->getOffset(),
2802                                             PPCII::MO_PIC_FLAG);
2803     return getTOCEntry(DAG, DL, false, GA);
2804   }
2805 
2806   SDValue GAHi =
2807     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2808   SDValue GALo =
2809     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2810 
2811   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2812 
2813   // If the global reference is actually to a non-lazy-pointer, we have to do an
2814   // extra load to get the address of the global.
2815   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2816     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2817   return Ptr;
2818 }
2819 
2820 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2821   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2822   SDLoc dl(Op);
2823 
2824   if (Op.getValueType() == MVT::v2i64) {
2825     // When the operands themselves are v2i64 values, we need to do something
2826     // special because VSX has no underlying comparison operations for these.
2827     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2828       // Equality can be handled by casting to the legal type for Altivec
2829       // comparisons, everything else needs to be expanded.
2830       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2831         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2832                  DAG.getSetCC(dl, MVT::v4i32,
2833                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2834                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2835                    CC));
2836       }
2837 
2838       return SDValue();
2839     }
2840 
2841     // We handle most of these in the usual way.
2842     return Op;
2843   }
2844 
2845   // If we're comparing for equality to zero, expose the fact that this is
2846   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2847   // fold the new nodes.
2848   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2849     return V;
2850 
2851   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2852     // Leave comparisons against 0 and -1 alone for now, since they're usually
2853     // optimized.  FIXME: revisit this when we can custom lower all setcc
2854     // optimizations.
2855     if (C->isAllOnesValue() || C->isNullValue())
2856       return SDValue();
2857   }
2858 
2859   // If we have an integer seteq/setne, turn it into a compare against zero
2860   // by xor'ing the rhs with the lhs, which is faster than setting a
2861   // condition register, reading it back out, and masking the correct bit.  The
2862   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2863   // the result to other bit-twiddling opportunities.
2864   EVT LHSVT = Op.getOperand(0).getValueType();
2865   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2866     EVT VT = Op.getValueType();
2867     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2868                                 Op.getOperand(1));
2869     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2870   }
2871   return SDValue();
2872 }
2873 
2874 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2875   SDNode *Node = Op.getNode();
2876   EVT VT = Node->getValueType(0);
2877   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2878   SDValue InChain = Node->getOperand(0);
2879   SDValue VAListPtr = Node->getOperand(1);
2880   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2881   SDLoc dl(Node);
2882 
2883   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2884 
2885   // gpr_index
2886   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2887                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2888   InChain = GprIndex.getValue(1);
2889 
2890   if (VT == MVT::i64) {
2891     // Check if GprIndex is even
2892     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2893                                  DAG.getConstant(1, dl, MVT::i32));
2894     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2895                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2896     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2897                                           DAG.getConstant(1, dl, MVT::i32));
2898     // Align GprIndex to be even if it isn't
2899     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2900                            GprIndex);
2901   }
2902 
2903   // fpr index is 1 byte after gpr
2904   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2905                                DAG.getConstant(1, dl, MVT::i32));
2906 
2907   // fpr
2908   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2909                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2910   InChain = FprIndex.getValue(1);
2911 
2912   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2913                                        DAG.getConstant(8, dl, MVT::i32));
2914 
2915   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2916                                         DAG.getConstant(4, dl, MVT::i32));
2917 
2918   // areas
2919   SDValue OverflowArea =
2920       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2921   InChain = OverflowArea.getValue(1);
2922 
2923   SDValue RegSaveArea =
2924       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2925   InChain = RegSaveArea.getValue(1);
2926 
2927   // select overflow_area if index > 8
2928   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2929                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2930 
2931   // adjustment constant gpr_index * 4/8
2932   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2933                                     VT.isInteger() ? GprIndex : FprIndex,
2934                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2935                                                     MVT::i32));
2936 
2937   // OurReg = RegSaveArea + RegConstant
2938   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2939                                RegConstant);
2940 
2941   // Floating types are 32 bytes into RegSaveArea
2942   if (VT.isFloatingPoint())
2943     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2944                          DAG.getConstant(32, dl, MVT::i32));
2945 
2946   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2947   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2948                                    VT.isInteger() ? GprIndex : FprIndex,
2949                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2950                                                    MVT::i32));
2951 
2952   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2953                               VT.isInteger() ? VAListPtr : FprPtr,
2954                               MachinePointerInfo(SV), MVT::i8);
2955 
2956   // determine if we should load from reg_save_area or overflow_area
2957   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2958 
2959   // increase overflow_area by 4/8 if gpr/fpr > 8
2960   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2961                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2962                                           dl, MVT::i32));
2963 
2964   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2965                              OverflowAreaPlusN);
2966 
2967   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2968                               MachinePointerInfo(), MVT::i32);
2969 
2970   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2971 }
2972 
2973 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2974   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2975 
2976   // We have to copy the entire va_list struct:
2977   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2978   return DAG.getMemcpy(Op.getOperand(0), Op,
2979                        Op.getOperand(1), Op.getOperand(2),
2980                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2981                        false, MachinePointerInfo(), MachinePointerInfo());
2982 }
2983 
2984 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2985                                                   SelectionDAG &DAG) const {
2986   return Op.getOperand(0);
2987 }
2988 
2989 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2990                                                 SelectionDAG &DAG) const {
2991   SDValue Chain = Op.getOperand(0);
2992   SDValue Trmp = Op.getOperand(1); // trampoline
2993   SDValue FPtr = Op.getOperand(2); // nested function
2994   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2995   SDLoc dl(Op);
2996 
2997   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2998   bool isPPC64 = (PtrVT == MVT::i64);
2999   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3000 
3001   TargetLowering::ArgListTy Args;
3002   TargetLowering::ArgListEntry Entry;
3003 
3004   Entry.Ty = IntPtrTy;
3005   Entry.Node = Trmp; Args.push_back(Entry);
3006 
3007   // TrampSize == (isPPC64 ? 48 : 40);
3008   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3009                                isPPC64 ? MVT::i64 : MVT::i32);
3010   Args.push_back(Entry);
3011 
3012   Entry.Node = FPtr; Args.push_back(Entry);
3013   Entry.Node = Nest; Args.push_back(Entry);
3014 
3015   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3016   TargetLowering::CallLoweringInfo CLI(DAG);
3017   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3018       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3019       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3020 
3021   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3022   return CallResult.second;
3023 }
3024 
3025 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3026   MachineFunction &MF = DAG.getMachineFunction();
3027   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3028   EVT PtrVT = getPointerTy(MF.getDataLayout());
3029 
3030   SDLoc dl(Op);
3031 
3032   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3033     // vastart just stores the address of the VarArgsFrameIndex slot into the
3034     // memory location argument.
3035     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3036     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3037     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3038                         MachinePointerInfo(SV));
3039   }
3040 
3041   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3042   // We suppose the given va_list is already allocated.
3043   //
3044   // typedef struct {
3045   //  char gpr;     /* index into the array of 8 GPRs
3046   //                 * stored in the register save area
3047   //                 * gpr=0 corresponds to r3,
3048   //                 * gpr=1 to r4, etc.
3049   //                 */
3050   //  char fpr;     /* index into the array of 8 FPRs
3051   //                 * stored in the register save area
3052   //                 * fpr=0 corresponds to f1,
3053   //                 * fpr=1 to f2, etc.
3054   //                 */
3055   //  char *overflow_arg_area;
3056   //                /* location on stack that holds
3057   //                 * the next overflow argument
3058   //                 */
3059   //  char *reg_save_area;
3060   //               /* where r3:r10 and f1:f8 (if saved)
3061   //                * are stored
3062   //                */
3063   // } va_list[1];
3064 
3065   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3066   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3067   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3068                                             PtrVT);
3069   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3070                                  PtrVT);
3071 
3072   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3073   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3074 
3075   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3076   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3077 
3078   uint64_t FPROffset = 1;
3079   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3080 
3081   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3082 
3083   // Store first byte : number of int regs
3084   SDValue firstStore =
3085       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3086                         MachinePointerInfo(SV), MVT::i8);
3087   uint64_t nextOffset = FPROffset;
3088   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3089                                   ConstFPROffset);
3090 
3091   // Store second byte : number of float regs
3092   SDValue secondStore =
3093       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3094                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3095   nextOffset += StackOffset;
3096   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3097 
3098   // Store second word : arguments given on stack
3099   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3100                                     MachinePointerInfo(SV, nextOffset));
3101   nextOffset += FrameOffset;
3102   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3103 
3104   // Store third word : arguments given in registers
3105   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3106                       MachinePointerInfo(SV, nextOffset));
3107 }
3108 
3109 #include "PPCGenCallingConv.inc"
3110 
3111 // Function whose sole purpose is to kill compiler warnings
3112 // stemming from unused functions included from PPCGenCallingConv.inc.
3113 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
3114   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
3115 }
3116 
3117 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
3118                                       CCValAssign::LocInfo &LocInfo,
3119                                       ISD::ArgFlagsTy &ArgFlags,
3120                                       CCState &State) {
3121   return true;
3122 }
3123 
3124 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
3125                                              MVT &LocVT,
3126                                              CCValAssign::LocInfo &LocInfo,
3127                                              ISD::ArgFlagsTy &ArgFlags,
3128                                              CCState &State) {
3129   static const MCPhysReg ArgRegs[] = {
3130     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3131     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3132   };
3133   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3134 
3135   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3136 
3137   // Skip one register if the first unallocated register has an even register
3138   // number and there are still argument registers available which have not been
3139   // allocated yet. RegNum is actually an index into ArgRegs, which means we
3140   // need to skip a register if RegNum is odd.
3141   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3142     State.AllocateReg(ArgRegs[RegNum]);
3143   }
3144 
3145   // Always return false here, as this function only makes sure that the first
3146   // unallocated register has an odd register number and does not actually
3147   // allocate a register for the current argument.
3148   return false;
3149 }
3150 
3151 bool
3152 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3153                                                   MVT &LocVT,
3154                                                   CCValAssign::LocInfo &LocInfo,
3155                                                   ISD::ArgFlagsTy &ArgFlags,
3156                                                   CCState &State) {
3157   static const MCPhysReg ArgRegs[] = {
3158     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3159     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3160   };
3161   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3162 
3163   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3164   int RegsLeft = NumArgRegs - RegNum;
3165 
3166   // Skip if there is not enough registers left for long double type (4 gpr regs
3167   // in soft float mode) and put long double argument on the stack.
3168   if (RegNum != NumArgRegs && RegsLeft < 4) {
3169     for (int i = 0; i < RegsLeft; i++) {
3170       State.AllocateReg(ArgRegs[RegNum + i]);
3171     }
3172   }
3173 
3174   return false;
3175 }
3176 
3177 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3178                                                MVT &LocVT,
3179                                                CCValAssign::LocInfo &LocInfo,
3180                                                ISD::ArgFlagsTy &ArgFlags,
3181                                                CCState &State) {
3182   static const MCPhysReg ArgRegs[] = {
3183     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3184     PPC::F8
3185   };
3186 
3187   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3188 
3189   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3190 
3191   // If there is only one Floating-point register left we need to put both f64
3192   // values of a split ppc_fp128 value on the stack.
3193   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3194     State.AllocateReg(ArgRegs[RegNum]);
3195   }
3196 
3197   // Always return false here, as this function only makes sure that the two f64
3198   // values a ppc_fp128 value is split into are both passed in registers or both
3199   // passed on the stack and does not actually allocate a register for the
3200   // current argument.
3201   return false;
3202 }
3203 
3204 /// FPR - The set of FP registers that should be allocated for arguments,
3205 /// on Darwin.
3206 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3207                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3208                                 PPC::F11, PPC::F12, PPC::F13};
3209 
3210 /// QFPR - The set of QPX registers that should be allocated for arguments.
3211 static const MCPhysReg QFPR[] = {
3212     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3213     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3214 
3215 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3216 /// the stack.
3217 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3218                                        unsigned PtrByteSize) {
3219   unsigned ArgSize = ArgVT.getStoreSize();
3220   if (Flags.isByVal())
3221     ArgSize = Flags.getByValSize();
3222 
3223   // Round up to multiples of the pointer size, except for array members,
3224   // which are always packed.
3225   if (!Flags.isInConsecutiveRegs())
3226     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3227 
3228   return ArgSize;
3229 }
3230 
3231 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3232 /// on the stack.
3233 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3234                                             ISD::ArgFlagsTy Flags,
3235                                             unsigned PtrByteSize) {
3236   unsigned Align = PtrByteSize;
3237 
3238   // Altivec parameters are padded to a 16 byte boundary.
3239   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3240       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3241       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3242       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3243     Align = 16;
3244   // QPX vector types stored in double-precision are padded to a 32 byte
3245   // boundary.
3246   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3247     Align = 32;
3248 
3249   // ByVal parameters are aligned as requested.
3250   if (Flags.isByVal()) {
3251     unsigned BVAlign = Flags.getByValAlign();
3252     if (BVAlign > PtrByteSize) {
3253       if (BVAlign % PtrByteSize != 0)
3254           llvm_unreachable(
3255             "ByVal alignment is not a multiple of the pointer size");
3256 
3257       Align = BVAlign;
3258     }
3259   }
3260 
3261   // Array members are always packed to their original alignment.
3262   if (Flags.isInConsecutiveRegs()) {
3263     // If the array member was split into multiple registers, the first
3264     // needs to be aligned to the size of the full type.  (Except for
3265     // ppcf128, which is only aligned as its f64 components.)
3266     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3267       Align = OrigVT.getStoreSize();
3268     else
3269       Align = ArgVT.getStoreSize();
3270   }
3271 
3272   return Align;
3273 }
3274 
3275 /// CalculateStackSlotUsed - Return whether this argument will use its
3276 /// stack slot (instead of being passed in registers).  ArgOffset,
3277 /// AvailableFPRs, and AvailableVRs must hold the current argument
3278 /// position, and will be updated to account for this argument.
3279 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3280                                    ISD::ArgFlagsTy Flags,
3281                                    unsigned PtrByteSize,
3282                                    unsigned LinkageSize,
3283                                    unsigned ParamAreaSize,
3284                                    unsigned &ArgOffset,
3285                                    unsigned &AvailableFPRs,
3286                                    unsigned &AvailableVRs, bool HasQPX) {
3287   bool UseMemory = false;
3288 
3289   // Respect alignment of argument on the stack.
3290   unsigned Align =
3291     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3292   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3293   // If there's no space left in the argument save area, we must
3294   // use memory (this check also catches zero-sized arguments).
3295   if (ArgOffset >= LinkageSize + ParamAreaSize)
3296     UseMemory = true;
3297 
3298   // Allocate argument on the stack.
3299   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3300   if (Flags.isInConsecutiveRegsLast())
3301     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3302   // If we overran the argument save area, we must use memory
3303   // (this check catches arguments passed partially in memory)
3304   if (ArgOffset > LinkageSize + ParamAreaSize)
3305     UseMemory = true;
3306 
3307   // However, if the argument is actually passed in an FPR or a VR,
3308   // we don't use memory after all.
3309   if (!Flags.isByVal()) {
3310     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3311         // QPX registers overlap with the scalar FP registers.
3312         (HasQPX && (ArgVT == MVT::v4f32 ||
3313                     ArgVT == MVT::v4f64 ||
3314                     ArgVT == MVT::v4i1)))
3315       if (AvailableFPRs > 0) {
3316         --AvailableFPRs;
3317         return false;
3318       }
3319     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3320         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3321         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3322         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3323       if (AvailableVRs > 0) {
3324         --AvailableVRs;
3325         return false;
3326       }
3327   }
3328 
3329   return UseMemory;
3330 }
3331 
3332 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3333 /// ensure minimum alignment required for target.
3334 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3335                                      unsigned NumBytes) {
3336   unsigned TargetAlign = Lowering->getStackAlignment();
3337   unsigned AlignMask = TargetAlign - 1;
3338   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3339   return NumBytes;
3340 }
3341 
3342 SDValue PPCTargetLowering::LowerFormalArguments(
3343     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3344     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3345     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3346   if (Subtarget.isSVR4ABI()) {
3347     if (Subtarget.isPPC64())
3348       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3349                                          dl, DAG, InVals);
3350     else
3351       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3352                                          dl, DAG, InVals);
3353   } else {
3354     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3355                                        dl, DAG, InVals);
3356   }
3357 }
3358 
3359 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3360     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3361     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3362     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3363 
3364   // 32-bit SVR4 ABI Stack Frame Layout:
3365   //              +-----------------------------------+
3366   //        +-->  |            Back chain             |
3367   //        |     +-----------------------------------+
3368   //        |     | Floating-point register save area |
3369   //        |     +-----------------------------------+
3370   //        |     |    General register save area     |
3371   //        |     +-----------------------------------+
3372   //        |     |          CR save word             |
3373   //        |     +-----------------------------------+
3374   //        |     |         VRSAVE save word          |
3375   //        |     +-----------------------------------+
3376   //        |     |         Alignment padding         |
3377   //        |     +-----------------------------------+
3378   //        |     |     Vector register save area     |
3379   //        |     +-----------------------------------+
3380   //        |     |       Local variable space        |
3381   //        |     +-----------------------------------+
3382   //        |     |        Parameter list area        |
3383   //        |     +-----------------------------------+
3384   //        |     |           LR save word            |
3385   //        |     +-----------------------------------+
3386   // SP-->  +---  |            Back chain             |
3387   //              +-----------------------------------+
3388   //
3389   // Specifications:
3390   //   System V Application Binary Interface PowerPC Processor Supplement
3391   //   AltiVec Technology Programming Interface Manual
3392 
3393   MachineFunction &MF = DAG.getMachineFunction();
3394   MachineFrameInfo &MFI = MF.getFrameInfo();
3395   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3396 
3397   EVT PtrVT = getPointerTy(MF.getDataLayout());
3398   // Potential tail calls could cause overwriting of argument stack slots.
3399   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3400                        (CallConv == CallingConv::Fast));
3401   unsigned PtrByteSize = 4;
3402 
3403   // Assign locations to all of the incoming arguments.
3404   SmallVector<CCValAssign, 16> ArgLocs;
3405   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3406                  *DAG.getContext());
3407 
3408   // Reserve space for the linkage area on the stack.
3409   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3410   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3411   if (useSoftFloat() || hasSPE())
3412     CCInfo.PreAnalyzeFormalArguments(Ins);
3413 
3414   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3415   CCInfo.clearWasPPCF128();
3416 
3417   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3418     CCValAssign &VA = ArgLocs[i];
3419 
3420     // Arguments stored in registers.
3421     if (VA.isRegLoc()) {
3422       const TargetRegisterClass *RC;
3423       EVT ValVT = VA.getValVT();
3424 
3425       switch (ValVT.getSimpleVT().SimpleTy) {
3426         default:
3427           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3428         case MVT::i1:
3429         case MVT::i32:
3430           RC = &PPC::GPRCRegClass;
3431           break;
3432         case MVT::f32:
3433           if (Subtarget.hasP8Vector())
3434             RC = &PPC::VSSRCRegClass;
3435           else if (Subtarget.hasSPE())
3436             RC = &PPC::SPE4RCRegClass;
3437           else
3438             RC = &PPC::F4RCRegClass;
3439           break;
3440         case MVT::f64:
3441           if (Subtarget.hasVSX())
3442             RC = &PPC::VSFRCRegClass;
3443           else if (Subtarget.hasSPE())
3444             RC = &PPC::SPERCRegClass;
3445           else
3446             RC = &PPC::F8RCRegClass;
3447           break;
3448         case MVT::v16i8:
3449         case MVT::v8i16:
3450         case MVT::v4i32:
3451           RC = &PPC::VRRCRegClass;
3452           break;
3453         case MVT::v4f32:
3454           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3455           break;
3456         case MVT::v2f64:
3457         case MVT::v2i64:
3458           RC = &PPC::VRRCRegClass;
3459           break;
3460         case MVT::v4f64:
3461           RC = &PPC::QFRCRegClass;
3462           break;
3463         case MVT::v4i1:
3464           RC = &PPC::QBRCRegClass;
3465           break;
3466       }
3467 
3468       // Transform the arguments stored in physical registers into virtual ones.
3469       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3470       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3471                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3472 
3473       if (ValVT == MVT::i1)
3474         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3475 
3476       InVals.push_back(ArgValue);
3477     } else {
3478       // Argument stored in memory.
3479       assert(VA.isMemLoc());
3480 
3481       unsigned ArgSize = VA.getLocVT().getStoreSize();
3482       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3483                                      isImmutable);
3484 
3485       // Create load nodes to retrieve arguments from the stack.
3486       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3487       InVals.push_back(
3488           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3489     }
3490   }
3491 
3492   // Assign locations to all of the incoming aggregate by value arguments.
3493   // Aggregates passed by value are stored in the local variable space of the
3494   // caller's stack frame, right above the parameter list area.
3495   SmallVector<CCValAssign, 16> ByValArgLocs;
3496   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3497                       ByValArgLocs, *DAG.getContext());
3498 
3499   // Reserve stack space for the allocations in CCInfo.
3500   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3501 
3502   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3503 
3504   // Area that is at least reserved in the caller of this function.
3505   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3506   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3507 
3508   // Set the size that is at least reserved in caller of this function.  Tail
3509   // call optimized function's reserved stack space needs to be aligned so that
3510   // taking the difference between two stack areas will result in an aligned
3511   // stack.
3512   MinReservedArea =
3513       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3514   FuncInfo->setMinReservedArea(MinReservedArea);
3515 
3516   SmallVector<SDValue, 8> MemOps;
3517 
3518   // If the function takes variable number of arguments, make a frame index for
3519   // the start of the first vararg value... for expansion of llvm.va_start.
3520   if (isVarArg) {
3521     static const MCPhysReg GPArgRegs[] = {
3522       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3523       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3524     };
3525     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3526 
3527     static const MCPhysReg FPArgRegs[] = {
3528       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3529       PPC::F8
3530     };
3531     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3532 
3533     if (useSoftFloat() || hasSPE())
3534        NumFPArgRegs = 0;
3535 
3536     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3537     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3538 
3539     // Make room for NumGPArgRegs and NumFPArgRegs.
3540     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3541                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3542 
3543     FuncInfo->setVarArgsStackOffset(
3544       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3545                             CCInfo.getNextStackOffset(), true));
3546 
3547     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3548     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3549 
3550     // The fixed integer arguments of a variadic function are stored to the
3551     // VarArgsFrameIndex on the stack so that they may be loaded by
3552     // dereferencing the result of va_next.
3553     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3554       // Get an existing live-in vreg, or add a new one.
3555       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3556       if (!VReg)
3557         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3558 
3559       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3560       SDValue Store =
3561           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3562       MemOps.push_back(Store);
3563       // Increment the address by four for the next argument to store
3564       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3565       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3566     }
3567 
3568     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3569     // is set.
3570     // The double arguments are stored to the VarArgsFrameIndex
3571     // on the stack.
3572     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3573       // Get an existing live-in vreg, or add a new one.
3574       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3575       if (!VReg)
3576         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3577 
3578       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3579       SDValue Store =
3580           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3581       MemOps.push_back(Store);
3582       // Increment the address by eight for the next argument to store
3583       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3584                                          PtrVT);
3585       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3586     }
3587   }
3588 
3589   if (!MemOps.empty())
3590     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3591 
3592   return Chain;
3593 }
3594 
3595 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3596 // value to MVT::i64 and then truncate to the correct register size.
3597 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3598                                              EVT ObjectVT, SelectionDAG &DAG,
3599                                              SDValue ArgVal,
3600                                              const SDLoc &dl) const {
3601   if (Flags.isSExt())
3602     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3603                          DAG.getValueType(ObjectVT));
3604   else if (Flags.isZExt())
3605     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3606                          DAG.getValueType(ObjectVT));
3607 
3608   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3609 }
3610 
3611 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3612     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3613     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3614     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3615   // TODO: add description of PPC stack frame format, or at least some docs.
3616   //
3617   bool isELFv2ABI = Subtarget.isELFv2ABI();
3618   bool isLittleEndian = Subtarget.isLittleEndian();
3619   MachineFunction &MF = DAG.getMachineFunction();
3620   MachineFrameInfo &MFI = MF.getFrameInfo();
3621   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3622 
3623   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3624          "fastcc not supported on varargs functions");
3625 
3626   EVT PtrVT = getPointerTy(MF.getDataLayout());
3627   // Potential tail calls could cause overwriting of argument stack slots.
3628   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3629                        (CallConv == CallingConv::Fast));
3630   unsigned PtrByteSize = 8;
3631   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3632 
3633   static const MCPhysReg GPR[] = {
3634     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3635     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3636   };
3637   static const MCPhysReg VR[] = {
3638     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3639     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3640   };
3641 
3642   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3643   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3644   const unsigned Num_VR_Regs  = array_lengthof(VR);
3645   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3646 
3647   // Do a first pass over the arguments to determine whether the ABI
3648   // guarantees that our caller has allocated the parameter save area
3649   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3650   // in the ELFv2 ABI, it is true if this is a vararg function or if
3651   // any parameter is located in a stack slot.
3652 
3653   bool HasParameterArea = !isELFv2ABI || isVarArg;
3654   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3655   unsigned NumBytes = LinkageSize;
3656   unsigned AvailableFPRs = Num_FPR_Regs;
3657   unsigned AvailableVRs = Num_VR_Regs;
3658   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3659     if (Ins[i].Flags.isNest())
3660       continue;
3661 
3662     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3663                                PtrByteSize, LinkageSize, ParamAreaSize,
3664                                NumBytes, AvailableFPRs, AvailableVRs,
3665                                Subtarget.hasQPX()))
3666       HasParameterArea = true;
3667   }
3668 
3669   // Add DAG nodes to load the arguments or copy them out of registers.  On
3670   // entry to a function on PPC, the arguments start after the linkage area,
3671   // although the first ones are often in registers.
3672 
3673   unsigned ArgOffset = LinkageSize;
3674   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3675   unsigned &QFPR_idx = FPR_idx;
3676   SmallVector<SDValue, 8> MemOps;
3677   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3678   unsigned CurArgIdx = 0;
3679   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3680     SDValue ArgVal;
3681     bool needsLoad = false;
3682     EVT ObjectVT = Ins[ArgNo].VT;
3683     EVT OrigVT = Ins[ArgNo].ArgVT;
3684     unsigned ObjSize = ObjectVT.getStoreSize();
3685     unsigned ArgSize = ObjSize;
3686     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3687     if (Ins[ArgNo].isOrigArg()) {
3688       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3689       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3690     }
3691     // We re-align the argument offset for each argument, except when using the
3692     // fast calling convention, when we need to make sure we do that only when
3693     // we'll actually use a stack slot.
3694     unsigned CurArgOffset, Align;
3695     auto ComputeArgOffset = [&]() {
3696       /* Respect alignment of argument on the stack.  */
3697       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3698       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3699       CurArgOffset = ArgOffset;
3700     };
3701 
3702     if (CallConv != CallingConv::Fast) {
3703       ComputeArgOffset();
3704 
3705       /* Compute GPR index associated with argument offset.  */
3706       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3707       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3708     }
3709 
3710     // FIXME the codegen can be much improved in some cases.
3711     // We do not have to keep everything in memory.
3712     if (Flags.isByVal()) {
3713       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3714 
3715       if (CallConv == CallingConv::Fast)
3716         ComputeArgOffset();
3717 
3718       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3719       ObjSize = Flags.getByValSize();
3720       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3721       // Empty aggregate parameters do not take up registers.  Examples:
3722       //   struct { } a;
3723       //   union  { } b;
3724       //   int c[0];
3725       // etc.  However, we have to provide a place-holder in InVals, so
3726       // pretend we have an 8-byte item at the current address for that
3727       // purpose.
3728       if (!ObjSize) {
3729         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3730         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3731         InVals.push_back(FIN);
3732         continue;
3733       }
3734 
3735       // Create a stack object covering all stack doublewords occupied
3736       // by the argument.  If the argument is (fully or partially) on
3737       // the stack, or if the argument is fully in registers but the
3738       // caller has allocated the parameter save anyway, we can refer
3739       // directly to the caller's stack frame.  Otherwise, create a
3740       // local copy in our own frame.
3741       int FI;
3742       if (HasParameterArea ||
3743           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3744         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3745       else
3746         FI = MFI.CreateStackObject(ArgSize, Align, false);
3747       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3748 
3749       // Handle aggregates smaller than 8 bytes.
3750       if (ObjSize < PtrByteSize) {
3751         // The value of the object is its address, which differs from the
3752         // address of the enclosing doubleword on big-endian systems.
3753         SDValue Arg = FIN;
3754         if (!isLittleEndian) {
3755           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3756           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3757         }
3758         InVals.push_back(Arg);
3759 
3760         if (GPR_idx != Num_GPR_Regs) {
3761           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3762           FuncInfo->addLiveInAttr(VReg, Flags);
3763           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3764           SDValue Store;
3765 
3766           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3767             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3768                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3769             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3770                                       MachinePointerInfo(&*FuncArg), ObjType);
3771           } else {
3772             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3773             // store the whole register as-is to the parameter save area
3774             // slot.
3775             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3776                                  MachinePointerInfo(&*FuncArg));
3777           }
3778 
3779           MemOps.push_back(Store);
3780         }
3781         // Whether we copied from a register or not, advance the offset
3782         // into the parameter save area by a full doubleword.
3783         ArgOffset += PtrByteSize;
3784         continue;
3785       }
3786 
3787       // The value of the object is its address, which is the address of
3788       // its first stack doubleword.
3789       InVals.push_back(FIN);
3790 
3791       // Store whatever pieces of the object are in registers to memory.
3792       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3793         if (GPR_idx == Num_GPR_Regs)
3794           break;
3795 
3796         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3797         FuncInfo->addLiveInAttr(VReg, Flags);
3798         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3799         SDValue Addr = FIN;
3800         if (j) {
3801           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3802           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3803         }
3804         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3805                                      MachinePointerInfo(&*FuncArg, j));
3806         MemOps.push_back(Store);
3807         ++GPR_idx;
3808       }
3809       ArgOffset += ArgSize;
3810       continue;
3811     }
3812 
3813     switch (ObjectVT.getSimpleVT().SimpleTy) {
3814     default: llvm_unreachable("Unhandled argument type!");
3815     case MVT::i1:
3816     case MVT::i32:
3817     case MVT::i64:
3818       if (Flags.isNest()) {
3819         // The 'nest' parameter, if any, is passed in R11.
3820         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3821         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3822 
3823         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3824           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3825 
3826         break;
3827       }
3828 
3829       // These can be scalar arguments or elements of an integer array type
3830       // passed directly.  Clang may use those instead of "byval" aggregate
3831       // types to avoid forcing arguments to memory unnecessarily.
3832       if (GPR_idx != Num_GPR_Regs) {
3833         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3834         FuncInfo->addLiveInAttr(VReg, Flags);
3835         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3836 
3837         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3838           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3839           // value to MVT::i64 and then truncate to the correct register size.
3840           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3841       } else {
3842         if (CallConv == CallingConv::Fast)
3843           ComputeArgOffset();
3844 
3845         needsLoad = true;
3846         ArgSize = PtrByteSize;
3847       }
3848       if (CallConv != CallingConv::Fast || needsLoad)
3849         ArgOffset += 8;
3850       break;
3851 
3852     case MVT::f32:
3853     case MVT::f64:
3854       // These can be scalar arguments or elements of a float array type
3855       // passed directly.  The latter are used to implement ELFv2 homogenous
3856       // float aggregates.
3857       if (FPR_idx != Num_FPR_Regs) {
3858         unsigned VReg;
3859 
3860         if (ObjectVT == MVT::f32)
3861           VReg = MF.addLiveIn(FPR[FPR_idx],
3862                               Subtarget.hasP8Vector()
3863                                   ? &PPC::VSSRCRegClass
3864                                   : &PPC::F4RCRegClass);
3865         else
3866           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3867                                                 ? &PPC::VSFRCRegClass
3868                                                 : &PPC::F8RCRegClass);
3869 
3870         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3871         ++FPR_idx;
3872       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3873         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3874         // once we support fp <-> gpr moves.
3875 
3876         // This can only ever happen in the presence of f32 array types,
3877         // since otherwise we never run out of FPRs before running out
3878         // of GPRs.
3879         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3880         FuncInfo->addLiveInAttr(VReg, Flags);
3881         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3882 
3883         if (ObjectVT == MVT::f32) {
3884           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3885             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3886                                  DAG.getConstant(32, dl, MVT::i32));
3887           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3888         }
3889 
3890         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3891       } else {
3892         if (CallConv == CallingConv::Fast)
3893           ComputeArgOffset();
3894 
3895         needsLoad = true;
3896       }
3897 
3898       // When passing an array of floats, the array occupies consecutive
3899       // space in the argument area; only round up to the next doubleword
3900       // at the end of the array.  Otherwise, each float takes 8 bytes.
3901       if (CallConv != CallingConv::Fast || needsLoad) {
3902         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3903         ArgOffset += ArgSize;
3904         if (Flags.isInConsecutiveRegsLast())
3905           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3906       }
3907       break;
3908     case MVT::v4f32:
3909     case MVT::v4i32:
3910     case MVT::v8i16:
3911     case MVT::v16i8:
3912     case MVT::v2f64:
3913     case MVT::v2i64:
3914     case MVT::v1i128:
3915     case MVT::f128:
3916       if (!Subtarget.hasQPX()) {
3917         // These can be scalar arguments or elements of a vector array type
3918         // passed directly.  The latter are used to implement ELFv2 homogenous
3919         // vector aggregates.
3920         if (VR_idx != Num_VR_Regs) {
3921           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3922           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3923           ++VR_idx;
3924         } else {
3925           if (CallConv == CallingConv::Fast)
3926             ComputeArgOffset();
3927           needsLoad = true;
3928         }
3929         if (CallConv != CallingConv::Fast || needsLoad)
3930           ArgOffset += 16;
3931         break;
3932       } // not QPX
3933 
3934       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3935              "Invalid QPX parameter type");
3936       /* fall through */
3937 
3938     case MVT::v4f64:
3939     case MVT::v4i1:
3940       // QPX vectors are treated like their scalar floating-point subregisters
3941       // (except that they're larger).
3942       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3943       if (QFPR_idx != Num_QFPR_Regs) {
3944         const TargetRegisterClass *RC;
3945         switch (ObjectVT.getSimpleVT().SimpleTy) {
3946         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3947         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3948         default:         RC = &PPC::QBRCRegClass; break;
3949         }
3950 
3951         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3952         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3953         ++QFPR_idx;
3954       } else {
3955         if (CallConv == CallingConv::Fast)
3956           ComputeArgOffset();
3957         needsLoad = true;
3958       }
3959       if (CallConv != CallingConv::Fast || needsLoad)
3960         ArgOffset += Sz;
3961       break;
3962     }
3963 
3964     // We need to load the argument to a virtual register if we determined
3965     // above that we ran out of physical registers of the appropriate type.
3966     if (needsLoad) {
3967       if (ObjSize < ArgSize && !isLittleEndian)
3968         CurArgOffset += ArgSize - ObjSize;
3969       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3970       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3971       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3972     }
3973 
3974     InVals.push_back(ArgVal);
3975   }
3976 
3977   // Area that is at least reserved in the caller of this function.
3978   unsigned MinReservedArea;
3979   if (HasParameterArea)
3980     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3981   else
3982     MinReservedArea = LinkageSize;
3983 
3984   // Set the size that is at least reserved in caller of this function.  Tail
3985   // call optimized functions' reserved stack space needs to be aligned so that
3986   // taking the difference between two stack areas will result in an aligned
3987   // stack.
3988   MinReservedArea =
3989       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3990   FuncInfo->setMinReservedArea(MinReservedArea);
3991 
3992   // If the function takes variable number of arguments, make a frame index for
3993   // the start of the first vararg value... for expansion of llvm.va_start.
3994   if (isVarArg) {
3995     int Depth = ArgOffset;
3996 
3997     FuncInfo->setVarArgsFrameIndex(
3998       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3999     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4000 
4001     // If this function is vararg, store any remaining integer argument regs
4002     // to their spots on the stack so that they may be loaded by dereferencing
4003     // the result of va_next.
4004     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4005          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4006       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4007       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4008       SDValue Store =
4009           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4010       MemOps.push_back(Store);
4011       // Increment the address by four for the next argument to store
4012       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4013       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4014     }
4015   }
4016 
4017   if (!MemOps.empty())
4018     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4019 
4020   return Chain;
4021 }
4022 
4023 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4024     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4025     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4026     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4027   // TODO: add description of PPC stack frame format, or at least some docs.
4028   //
4029   MachineFunction &MF = DAG.getMachineFunction();
4030   MachineFrameInfo &MFI = MF.getFrameInfo();
4031   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4032 
4033   EVT PtrVT = getPointerTy(MF.getDataLayout());
4034   bool isPPC64 = PtrVT == MVT::i64;
4035   // Potential tail calls could cause overwriting of argument stack slots.
4036   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4037                        (CallConv == CallingConv::Fast));
4038   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4039   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4040   unsigned ArgOffset = LinkageSize;
4041   // Area that is at least reserved in caller of this function.
4042   unsigned MinReservedArea = ArgOffset;
4043 
4044   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4045     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4046     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4047   };
4048   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4049     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4050     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4051   };
4052   static const MCPhysReg VR[] = {
4053     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4054     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4055   };
4056 
4057   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4058   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4059   const unsigned Num_VR_Regs  = array_lengthof( VR);
4060 
4061   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4062 
4063   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4064 
4065   // In 32-bit non-varargs functions, the stack space for vectors is after the
4066   // stack space for non-vectors.  We do not use this space unless we have
4067   // too many vectors to fit in registers, something that only occurs in
4068   // constructed examples:), but we have to walk the arglist to figure
4069   // that out...for the pathological case, compute VecArgOffset as the
4070   // start of the vector parameter area.  Computing VecArgOffset is the
4071   // entire point of the following loop.
4072   unsigned VecArgOffset = ArgOffset;
4073   if (!isVarArg && !isPPC64) {
4074     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4075          ++ArgNo) {
4076       EVT ObjectVT = Ins[ArgNo].VT;
4077       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4078 
4079       if (Flags.isByVal()) {
4080         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4081         unsigned ObjSize = Flags.getByValSize();
4082         unsigned ArgSize =
4083                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4084         VecArgOffset += ArgSize;
4085         continue;
4086       }
4087 
4088       switch(ObjectVT.getSimpleVT().SimpleTy) {
4089       default: llvm_unreachable("Unhandled argument type!");
4090       case MVT::i1:
4091       case MVT::i32:
4092       case MVT::f32:
4093         VecArgOffset += 4;
4094         break;
4095       case MVT::i64:  // PPC64
4096       case MVT::f64:
4097         // FIXME: We are guaranteed to be !isPPC64 at this point.
4098         // Does MVT::i64 apply?
4099         VecArgOffset += 8;
4100         break;
4101       case MVT::v4f32:
4102       case MVT::v4i32:
4103       case MVT::v8i16:
4104       case MVT::v16i8:
4105         // Nothing to do, we're only looking at Nonvector args here.
4106         break;
4107       }
4108     }
4109   }
4110   // We've found where the vector parameter area in memory is.  Skip the
4111   // first 12 parameters; these don't use that memory.
4112   VecArgOffset = ((VecArgOffset+15)/16)*16;
4113   VecArgOffset += 12*16;
4114 
4115   // Add DAG nodes to load the arguments or copy them out of registers.  On
4116   // entry to a function on PPC, the arguments start after the linkage area,
4117   // although the first ones are often in registers.
4118 
4119   SmallVector<SDValue, 8> MemOps;
4120   unsigned nAltivecParamsAtEnd = 0;
4121   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4122   unsigned CurArgIdx = 0;
4123   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4124     SDValue ArgVal;
4125     bool needsLoad = false;
4126     EVT ObjectVT = Ins[ArgNo].VT;
4127     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4128     unsigned ArgSize = ObjSize;
4129     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4130     if (Ins[ArgNo].isOrigArg()) {
4131       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4132       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4133     }
4134     unsigned CurArgOffset = ArgOffset;
4135 
4136     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4137     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4138         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4139       if (isVarArg || isPPC64) {
4140         MinReservedArea = ((MinReservedArea+15)/16)*16;
4141         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4142                                                   Flags,
4143                                                   PtrByteSize);
4144       } else  nAltivecParamsAtEnd++;
4145     } else
4146       // Calculate min reserved area.
4147       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4148                                                 Flags,
4149                                                 PtrByteSize);
4150 
4151     // FIXME the codegen can be much improved in some cases.
4152     // We do not have to keep everything in memory.
4153     if (Flags.isByVal()) {
4154       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4155 
4156       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4157       ObjSize = Flags.getByValSize();
4158       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4159       // Objects of size 1 and 2 are right justified, everything else is
4160       // left justified.  This means the memory address is adjusted forwards.
4161       if (ObjSize==1 || ObjSize==2) {
4162         CurArgOffset = CurArgOffset + (4 - ObjSize);
4163       }
4164       // The value of the object is its address.
4165       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4166       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4167       InVals.push_back(FIN);
4168       if (ObjSize==1 || ObjSize==2) {
4169         if (GPR_idx != Num_GPR_Regs) {
4170           unsigned VReg;
4171           if (isPPC64)
4172             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4173           else
4174             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4175           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4176           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4177           SDValue Store =
4178               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4179                                 MachinePointerInfo(&*FuncArg), ObjType);
4180           MemOps.push_back(Store);
4181           ++GPR_idx;
4182         }
4183 
4184         ArgOffset += PtrByteSize;
4185 
4186         continue;
4187       }
4188       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4189         // Store whatever pieces of the object are in registers
4190         // to memory.  ArgOffset will be the address of the beginning
4191         // of the object.
4192         if (GPR_idx != Num_GPR_Regs) {
4193           unsigned VReg;
4194           if (isPPC64)
4195             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4196           else
4197             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4198           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4199           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4200           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4201           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4202                                        MachinePointerInfo(&*FuncArg, j));
4203           MemOps.push_back(Store);
4204           ++GPR_idx;
4205           ArgOffset += PtrByteSize;
4206         } else {
4207           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4208           break;
4209         }
4210       }
4211       continue;
4212     }
4213 
4214     switch (ObjectVT.getSimpleVT().SimpleTy) {
4215     default: llvm_unreachable("Unhandled argument type!");
4216     case MVT::i1:
4217     case MVT::i32:
4218       if (!isPPC64) {
4219         if (GPR_idx != Num_GPR_Regs) {
4220           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4221           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4222 
4223           if (ObjectVT == MVT::i1)
4224             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4225 
4226           ++GPR_idx;
4227         } else {
4228           needsLoad = true;
4229           ArgSize = PtrByteSize;
4230         }
4231         // All int arguments reserve stack space in the Darwin ABI.
4232         ArgOffset += PtrByteSize;
4233         break;
4234       }
4235       LLVM_FALLTHROUGH;
4236     case MVT::i64:  // PPC64
4237       if (GPR_idx != Num_GPR_Regs) {
4238         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4239         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4240 
4241         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4242           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4243           // value to MVT::i64 and then truncate to the correct register size.
4244           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4245 
4246         ++GPR_idx;
4247       } else {
4248         needsLoad = true;
4249         ArgSize = PtrByteSize;
4250       }
4251       // All int arguments reserve stack space in the Darwin ABI.
4252       ArgOffset += 8;
4253       break;
4254 
4255     case MVT::f32:
4256     case MVT::f64:
4257       // Every 4 bytes of argument space consumes one of the GPRs available for
4258       // argument passing.
4259       if (GPR_idx != Num_GPR_Regs) {
4260         ++GPR_idx;
4261         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4262           ++GPR_idx;
4263       }
4264       if (FPR_idx != Num_FPR_Regs) {
4265         unsigned VReg;
4266 
4267         if (ObjectVT == MVT::f32)
4268           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4269         else
4270           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4271 
4272         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4273         ++FPR_idx;
4274       } else {
4275         needsLoad = true;
4276       }
4277 
4278       // All FP arguments reserve stack space in the Darwin ABI.
4279       ArgOffset += isPPC64 ? 8 : ObjSize;
4280       break;
4281     case MVT::v4f32:
4282     case MVT::v4i32:
4283     case MVT::v8i16:
4284     case MVT::v16i8:
4285       // Note that vector arguments in registers don't reserve stack space,
4286       // except in varargs functions.
4287       if (VR_idx != Num_VR_Regs) {
4288         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4289         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4290         if (isVarArg) {
4291           while ((ArgOffset % 16) != 0) {
4292             ArgOffset += PtrByteSize;
4293             if (GPR_idx != Num_GPR_Regs)
4294               GPR_idx++;
4295           }
4296           ArgOffset += 16;
4297           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4298         }
4299         ++VR_idx;
4300       } else {
4301         if (!isVarArg && !isPPC64) {
4302           // Vectors go after all the nonvectors.
4303           CurArgOffset = VecArgOffset;
4304           VecArgOffset += 16;
4305         } else {
4306           // Vectors are aligned.
4307           ArgOffset = ((ArgOffset+15)/16)*16;
4308           CurArgOffset = ArgOffset;
4309           ArgOffset += 16;
4310         }
4311         needsLoad = true;
4312       }
4313       break;
4314     }
4315 
4316     // We need to load the argument to a virtual register if we determined above
4317     // that we ran out of physical registers of the appropriate type.
4318     if (needsLoad) {
4319       int FI = MFI.CreateFixedObject(ObjSize,
4320                                      CurArgOffset + (ArgSize - ObjSize),
4321                                      isImmutable);
4322       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4323       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4324     }
4325 
4326     InVals.push_back(ArgVal);
4327   }
4328 
4329   // Allow for Altivec parameters at the end, if needed.
4330   if (nAltivecParamsAtEnd) {
4331     MinReservedArea = ((MinReservedArea+15)/16)*16;
4332     MinReservedArea += 16*nAltivecParamsAtEnd;
4333   }
4334 
4335   // Area that is at least reserved in the caller of this function.
4336   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4337 
4338   // Set the size that is at least reserved in caller of this function.  Tail
4339   // call optimized functions' reserved stack space needs to be aligned so that
4340   // taking the difference between two stack areas will result in an aligned
4341   // stack.
4342   MinReservedArea =
4343       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4344   FuncInfo->setMinReservedArea(MinReservedArea);
4345 
4346   // If the function takes variable number of arguments, make a frame index for
4347   // the start of the first vararg value... for expansion of llvm.va_start.
4348   if (isVarArg) {
4349     int Depth = ArgOffset;
4350 
4351     FuncInfo->setVarArgsFrameIndex(
4352       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4353                             Depth, true));
4354     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4355 
4356     // If this function is vararg, store any remaining integer argument regs
4357     // to their spots on the stack so that they may be loaded by dereferencing
4358     // the result of va_next.
4359     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4360       unsigned VReg;
4361 
4362       if (isPPC64)
4363         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4364       else
4365         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4366 
4367       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4368       SDValue Store =
4369           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4370       MemOps.push_back(Store);
4371       // Increment the address by four for the next argument to store
4372       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4373       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4374     }
4375   }
4376 
4377   if (!MemOps.empty())
4378     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4379 
4380   return Chain;
4381 }
4382 
4383 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4384 /// adjusted to accommodate the arguments for the tailcall.
4385 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4386                                    unsigned ParamSize) {
4387 
4388   if (!isTailCall) return 0;
4389 
4390   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4391   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4392   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4393   // Remember only if the new adjustment is bigger.
4394   if (SPDiff < FI->getTailCallSPDelta())
4395     FI->setTailCallSPDelta(SPDiff);
4396 
4397   return SPDiff;
4398 }
4399 
4400 static bool isFunctionGlobalAddress(SDValue Callee);
4401 
4402 static bool
4403 callsShareTOCBase(const Function *Caller, SDValue Callee,
4404                     const TargetMachine &TM) {
4405   // If !G, Callee can be an external symbol.
4406   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4407   if (!G)
4408     return false;
4409 
4410   // The medium and large code models are expected to provide a sufficiently
4411   // large TOC to provide all data addressing needs of a module with a
4412   // single TOC. Since each module will be addressed with a single TOC then we
4413   // only need to check that caller and callee don't cross dso boundaries.
4414   if (CodeModel::Medium == TM.getCodeModel() ||
4415       CodeModel::Large == TM.getCodeModel())
4416     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4417 
4418   // Otherwise we need to ensure callee and caller are in the same section,
4419   // since the linker may allocate multiple TOCs, and we don't know which
4420   // sections will belong to the same TOC base.
4421 
4422   const GlobalValue *GV = G->getGlobal();
4423   if (!GV->isStrongDefinitionForLinker())
4424     return false;
4425 
4426   // Any explicitly-specified sections and section prefixes must also match.
4427   // Also, if we're using -ffunction-sections, then each function is always in
4428   // a different section (the same is true for COMDAT functions).
4429   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4430       GV->getSection() != Caller->getSection())
4431     return false;
4432   if (const auto *F = dyn_cast<Function>(GV)) {
4433     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4434       return false;
4435   }
4436 
4437   // If the callee might be interposed, then we can't assume the ultimate call
4438   // target will be in the same section. Even in cases where we can assume that
4439   // interposition won't happen, in any case where the linker might insert a
4440   // stub to allow for interposition, we must generate code as though
4441   // interposition might occur. To understand why this matters, consider a
4442   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4443   // in the same section, but a is in a different module (i.e. has a different
4444   // TOC base pointer). If the linker allows for interposition between b and c,
4445   // then it will generate a stub for the call edge between b and c which will
4446   // save the TOC pointer into the designated stack slot allocated by b. If we
4447   // return true here, and therefore allow a tail call between b and c, that
4448   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4449   // pointer into the stack slot allocated by a (where the a -> b stub saved
4450   // a's TOC base pointer). If we're not considering a tail call, but rather,
4451   // whether a nop is needed after the call instruction in b, because the linker
4452   // will insert a stub, it might complain about a missing nop if we omit it
4453   // (although many don't complain in this case).
4454   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4455     return false;
4456 
4457   return true;
4458 }
4459 
4460 static bool
4461 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4462                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4463   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4464 
4465   const unsigned PtrByteSize = 8;
4466   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4467 
4468   static const MCPhysReg GPR[] = {
4469     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4470     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4471   };
4472   static const MCPhysReg VR[] = {
4473     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4474     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4475   };
4476 
4477   const unsigned NumGPRs = array_lengthof(GPR);
4478   const unsigned NumFPRs = 13;
4479   const unsigned NumVRs = array_lengthof(VR);
4480   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4481 
4482   unsigned NumBytes = LinkageSize;
4483   unsigned AvailableFPRs = NumFPRs;
4484   unsigned AvailableVRs = NumVRs;
4485 
4486   for (const ISD::OutputArg& Param : Outs) {
4487     if (Param.Flags.isNest()) continue;
4488 
4489     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4490                                PtrByteSize, LinkageSize, ParamAreaSize,
4491                                NumBytes, AvailableFPRs, AvailableVRs,
4492                                Subtarget.hasQPX()))
4493       return true;
4494   }
4495   return false;
4496 }
4497 
4498 static bool
4499 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4500   if (CS.arg_size() != CallerFn->arg_size())
4501     return false;
4502 
4503   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4504   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4505   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4506 
4507   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4508     const Value* CalleeArg = *CalleeArgIter;
4509     const Value* CallerArg = &(*CallerArgIter);
4510     if (CalleeArg == CallerArg)
4511       continue;
4512 
4513     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4514     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4515     //      }
4516     // 1st argument of callee is undef and has the same type as caller.
4517     if (CalleeArg->getType() == CallerArg->getType() &&
4518         isa<UndefValue>(CalleeArg))
4519       continue;
4520 
4521     return false;
4522   }
4523 
4524   return true;
4525 }
4526 
4527 // Returns true if TCO is possible between the callers and callees
4528 // calling conventions.
4529 static bool
4530 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4531                                     CallingConv::ID CalleeCC) {
4532   // Tail calls are possible with fastcc and ccc.
4533   auto isTailCallableCC  = [] (CallingConv::ID CC){
4534       return  CC == CallingConv::C || CC == CallingConv::Fast;
4535   };
4536   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4537     return false;
4538 
4539   // We can safely tail call both fastcc and ccc callees from a c calling
4540   // convention caller. If the caller is fastcc, we may have less stack space
4541   // than a non-fastcc caller with the same signature so disable tail-calls in
4542   // that case.
4543   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4544 }
4545 
4546 bool
4547 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4548                                     SDValue Callee,
4549                                     CallingConv::ID CalleeCC,
4550                                     ImmutableCallSite CS,
4551                                     bool isVarArg,
4552                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4553                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4554                                     SelectionDAG& DAG) const {
4555   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4556 
4557   if (DisableSCO && !TailCallOpt) return false;
4558 
4559   // Variadic argument functions are not supported.
4560   if (isVarArg) return false;
4561 
4562   auto &Caller = DAG.getMachineFunction().getFunction();
4563   // Check that the calling conventions are compatible for tco.
4564   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4565     return false;
4566 
4567   // Caller contains any byval parameter is not supported.
4568   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4569     return false;
4570 
4571   // Callee contains any byval parameter is not supported, too.
4572   // Note: This is a quick work around, because in some cases, e.g.
4573   // caller's stack size > callee's stack size, we are still able to apply
4574   // sibling call optimization. For example, gcc is able to do SCO for caller1
4575   // in the following example, but not for caller2.
4576   //   struct test {
4577   //     long int a;
4578   //     char ary[56];
4579   //   } gTest;
4580   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4581   //     b->a = v.a;
4582   //     return 0;
4583   //   }
4584   //   void caller1(struct test a, struct test c, struct test *b) {
4585   //     callee(gTest, b); }
4586   //   void caller2(struct test *b) { callee(gTest, b); }
4587   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4588     return false;
4589 
4590   // If callee and caller use different calling conventions, we cannot pass
4591   // parameters on stack since offsets for the parameter area may be different.
4592   if (Caller.getCallingConv() != CalleeCC &&
4593       needStackSlotPassParameters(Subtarget, Outs))
4594     return false;
4595 
4596   // No TCO/SCO on indirect call because Caller have to restore its TOC
4597   if (!isFunctionGlobalAddress(Callee) &&
4598       !isa<ExternalSymbolSDNode>(Callee))
4599     return false;
4600 
4601   // If the caller and callee potentially have different TOC bases then we
4602   // cannot tail call since we need to restore the TOC pointer after the call.
4603   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4604   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4605     return false;
4606 
4607   // TCO allows altering callee ABI, so we don't have to check further.
4608   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4609     return true;
4610 
4611   if (DisableSCO) return false;
4612 
4613   // If callee use the same argument list that caller is using, then we can
4614   // apply SCO on this case. If it is not, then we need to check if callee needs
4615   // stack for passing arguments.
4616   if (!hasSameArgumentList(&Caller, CS) &&
4617       needStackSlotPassParameters(Subtarget, Outs)) {
4618     return false;
4619   }
4620 
4621   return true;
4622 }
4623 
4624 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4625 /// for tail call optimization. Targets which want to do tail call
4626 /// optimization should implement this function.
4627 bool
4628 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4629                                                      CallingConv::ID CalleeCC,
4630                                                      bool isVarArg,
4631                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4632                                                      SelectionDAG& DAG) const {
4633   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4634     return false;
4635 
4636   // Variable argument functions are not supported.
4637   if (isVarArg)
4638     return false;
4639 
4640   MachineFunction &MF = DAG.getMachineFunction();
4641   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4642   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4643     // Functions containing by val parameters are not supported.
4644     for (unsigned i = 0; i != Ins.size(); i++) {
4645        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4646        if (Flags.isByVal()) return false;
4647     }
4648 
4649     // Non-PIC/GOT tail calls are supported.
4650     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4651       return true;
4652 
4653     // At the moment we can only do local tail calls (in same module, hidden
4654     // or protected) if we are generating PIC.
4655     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4656       return G->getGlobal()->hasHiddenVisibility()
4657           || G->getGlobal()->hasProtectedVisibility();
4658   }
4659 
4660   return false;
4661 }
4662 
4663 /// isCallCompatibleAddress - Return the immediate to use if the specified
4664 /// 32-bit value is representable in the immediate field of a BxA instruction.
4665 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4666   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4667   if (!C) return nullptr;
4668 
4669   int Addr = C->getZExtValue();
4670   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4671       SignExtend32<26>(Addr) != Addr)
4672     return nullptr;  // Top 6 bits have to be sext of immediate.
4673 
4674   return DAG
4675       .getConstant(
4676           (int)C->getZExtValue() >> 2, SDLoc(Op),
4677           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4678       .getNode();
4679 }
4680 
4681 namespace {
4682 
4683 struct TailCallArgumentInfo {
4684   SDValue Arg;
4685   SDValue FrameIdxOp;
4686   int FrameIdx = 0;
4687 
4688   TailCallArgumentInfo() = default;
4689 };
4690 
4691 } // end anonymous namespace
4692 
4693 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4694 static void StoreTailCallArgumentsToStackSlot(
4695     SelectionDAG &DAG, SDValue Chain,
4696     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4697     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4698   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4699     SDValue Arg = TailCallArgs[i].Arg;
4700     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4701     int FI = TailCallArgs[i].FrameIdx;
4702     // Store relative to framepointer.
4703     MemOpChains.push_back(DAG.getStore(
4704         Chain, dl, Arg, FIN,
4705         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4706   }
4707 }
4708 
4709 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4710 /// the appropriate stack slot for the tail call optimized function call.
4711 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4712                                              SDValue OldRetAddr, SDValue OldFP,
4713                                              int SPDiff, const SDLoc &dl) {
4714   if (SPDiff) {
4715     // Calculate the new stack slot for the return address.
4716     MachineFunction &MF = DAG.getMachineFunction();
4717     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4718     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4719     bool isPPC64 = Subtarget.isPPC64();
4720     int SlotSize = isPPC64 ? 8 : 4;
4721     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4722     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4723                                                          NewRetAddrLoc, true);
4724     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4725     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4726     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4727                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4728 
4729     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4730     // slot as the FP is never overwritten.
4731     if (Subtarget.isDarwinABI()) {
4732       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4733       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4734                                                          true);
4735       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4736       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4737                            MachinePointerInfo::getFixedStack(
4738                                DAG.getMachineFunction(), NewFPIdx));
4739     }
4740   }
4741   return Chain;
4742 }
4743 
4744 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4745 /// the position of the argument.
4746 static void
4747 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4748                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4749                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4750   int Offset = ArgOffset + SPDiff;
4751   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4752   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4753   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4754   SDValue FIN = DAG.getFrameIndex(FI, VT);
4755   TailCallArgumentInfo Info;
4756   Info.Arg = Arg;
4757   Info.FrameIdxOp = FIN;
4758   Info.FrameIdx = FI;
4759   TailCallArguments.push_back(Info);
4760 }
4761 
4762 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4763 /// stack slot. Returns the chain as result and the loaded frame pointers in
4764 /// LROpOut/FPOpout. Used when tail calling.
4765 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4766     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4767     SDValue &FPOpOut, const SDLoc &dl) const {
4768   if (SPDiff) {
4769     // Load the LR and FP stack slot for later adjusting.
4770     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4771     LROpOut = getReturnAddrFrameIndex(DAG);
4772     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4773     Chain = SDValue(LROpOut.getNode(), 1);
4774 
4775     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4776     // slot as the FP is never overwritten.
4777     if (Subtarget.isDarwinABI()) {
4778       FPOpOut = getFramePointerFrameIndex(DAG);
4779       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4780       Chain = SDValue(FPOpOut.getNode(), 1);
4781     }
4782   }
4783   return Chain;
4784 }
4785 
4786 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4787 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4788 /// specified by the specific parameter attribute. The copy will be passed as
4789 /// a byval function parameter.
4790 /// Sometimes what we are copying is the end of a larger object, the part that
4791 /// does not fit in registers.
4792 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4793                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4794                                          SelectionDAG &DAG, const SDLoc &dl) {
4795   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4796   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4797                        false, false, false, MachinePointerInfo(),
4798                        MachinePointerInfo());
4799 }
4800 
4801 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4802 /// tail calls.
4803 static void LowerMemOpCallTo(
4804     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4805     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4806     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4807     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4808   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4809   if (!isTailCall) {
4810     if (isVector) {
4811       SDValue StackPtr;
4812       if (isPPC64)
4813         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4814       else
4815         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4816       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4817                            DAG.getConstant(ArgOffset, dl, PtrVT));
4818     }
4819     MemOpChains.push_back(
4820         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4821     // Calculate and remember argument location.
4822   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4823                                   TailCallArguments);
4824 }
4825 
4826 static void
4827 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4828                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4829                 SDValue FPOp,
4830                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4831   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4832   // might overwrite each other in case of tail call optimization.
4833   SmallVector<SDValue, 8> MemOpChains2;
4834   // Do not flag preceding copytoreg stuff together with the following stuff.
4835   InFlag = SDValue();
4836   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4837                                     MemOpChains2, dl);
4838   if (!MemOpChains2.empty())
4839     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4840 
4841   // Store the return address to the appropriate stack slot.
4842   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4843 
4844   // Emit callseq_end just before tailcall node.
4845   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4846                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4847   InFlag = Chain.getValue(1);
4848 }
4849 
4850 // Is this global address that of a function that can be called by name? (as
4851 // opposed to something that must hold a descriptor for an indirect call).
4852 static bool isFunctionGlobalAddress(SDValue Callee) {
4853   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4854     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4855         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4856       return false;
4857 
4858     return G->getGlobal()->getValueType()->isFunctionTy();
4859   }
4860 
4861   return false;
4862 }
4863 
4864 static unsigned
4865 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4866             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4867             bool isPatchPoint, bool hasNest,
4868             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4869             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4870             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4871   bool isPPC64 = Subtarget.isPPC64();
4872   bool isSVR4ABI = Subtarget.isSVR4ABI();
4873   bool isELFv2ABI = Subtarget.isELFv2ABI();
4874 
4875   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4876   NodeTys.push_back(MVT::Other);   // Returns a chain
4877   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4878 
4879   unsigned CallOpc = PPCISD::CALL;
4880 
4881   bool needIndirectCall = true;
4882   if (!isSVR4ABI || !isPPC64)
4883     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4884       // If this is an absolute destination address, use the munged value.
4885       Callee = SDValue(Dest, 0);
4886       needIndirectCall = false;
4887     }
4888 
4889   // PC-relative references to external symbols should go through $stub, unless
4890   // we're building with the leopard linker or later, which automatically
4891   // synthesizes these stubs.
4892   const TargetMachine &TM = DAG.getTarget();
4893   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4894   const GlobalValue *GV = nullptr;
4895   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4896     GV = G->getGlobal();
4897   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4898   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4899 
4900   if (isFunctionGlobalAddress(Callee)) {
4901     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4902     // A call to a TLS address is actually an indirect call to a
4903     // thread-specific pointer.
4904     unsigned OpFlags = 0;
4905     if (UsePlt)
4906       OpFlags = PPCII::MO_PLT;
4907 
4908     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4909     // every direct call is) turn it into a TargetGlobalAddress /
4910     // TargetExternalSymbol node so that legalize doesn't hack it.
4911     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4912                                         Callee.getValueType(), 0, OpFlags);
4913     needIndirectCall = false;
4914   }
4915 
4916   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4917     unsigned char OpFlags = 0;
4918 
4919     if (UsePlt)
4920       OpFlags = PPCII::MO_PLT;
4921 
4922     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4923                                          OpFlags);
4924     needIndirectCall = false;
4925   }
4926 
4927   if (isPatchPoint) {
4928     // We'll form an invalid direct call when lowering a patchpoint; the full
4929     // sequence for an indirect call is complicated, and many of the
4930     // instructions introduced might have side effects (and, thus, can't be
4931     // removed later). The call itself will be removed as soon as the
4932     // argument/return lowering is complete, so the fact that it has the wrong
4933     // kind of operands should not really matter.
4934     needIndirectCall = false;
4935   }
4936 
4937   if (needIndirectCall) {
4938     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4939     // to do the call, we can't use PPCISD::CALL.
4940     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4941 
4942     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4943       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4944       // entry point, but to the function descriptor (the function entry point
4945       // address is part of the function descriptor though).
4946       // The function descriptor is a three doubleword structure with the
4947       // following fields: function entry point, TOC base address and
4948       // environment pointer.
4949       // Thus for a call through a function pointer, the following actions need
4950       // to be performed:
4951       //   1. Save the TOC of the caller in the TOC save area of its stack
4952       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4953       //   2. Load the address of the function entry point from the function
4954       //      descriptor.
4955       //   3. Load the TOC of the callee from the function descriptor into r2.
4956       //   4. Load the environment pointer from the function descriptor into
4957       //      r11.
4958       //   5. Branch to the function entry point address.
4959       //   6. On return of the callee, the TOC of the caller needs to be
4960       //      restored (this is done in FinishCall()).
4961       //
4962       // The loads are scheduled at the beginning of the call sequence, and the
4963       // register copies are flagged together to ensure that no other
4964       // operations can be scheduled in between. E.g. without flagging the
4965       // copies together, a TOC access in the caller could be scheduled between
4966       // the assignment of the callee TOC and the branch to the callee, which
4967       // results in the TOC access going through the TOC of the callee instead
4968       // of going through the TOC of the caller, which leads to incorrect code.
4969 
4970       // Load the address of the function entry point from the function
4971       // descriptor.
4972       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4973       if (LDChain.getValueType() == MVT::Glue)
4974         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4975 
4976       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4977                           ? (MachineMemOperand::MODereferenceable |
4978                              MachineMemOperand::MOInvariant)
4979                           : MachineMemOperand::MONone;
4980 
4981       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4982       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4983                                         /* Alignment = */ 8, MMOFlags);
4984 
4985       // Load environment pointer into r11.
4986       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4987       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4988       SDValue LoadEnvPtr =
4989           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4990                       /* Alignment = */ 8, MMOFlags);
4991 
4992       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4993       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4994       SDValue TOCPtr =
4995           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4996                       /* Alignment = */ 8, MMOFlags);
4997 
4998       setUsesTOCBasePtr(DAG);
4999       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
5000                                         InFlag);
5001       Chain = TOCVal.getValue(0);
5002       InFlag = TOCVal.getValue(1);
5003 
5004       // If the function call has an explicit 'nest' parameter, it takes the
5005       // place of the environment pointer.
5006       if (!hasNest) {
5007         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5008                                           InFlag);
5009 
5010         Chain = EnvVal.getValue(0);
5011         InFlag = EnvVal.getValue(1);
5012       }
5013 
5014       MTCTROps[0] = Chain;
5015       MTCTROps[1] = LoadFuncPtr;
5016       MTCTROps[2] = InFlag;
5017     }
5018 
5019     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5020                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5021     InFlag = Chain.getValue(1);
5022 
5023     NodeTys.clear();
5024     NodeTys.push_back(MVT::Other);
5025     NodeTys.push_back(MVT::Glue);
5026     Ops.push_back(Chain);
5027     CallOpc = PPCISD::BCTRL;
5028     Callee.setNode(nullptr);
5029     // Add use of X11 (holding environment pointer)
5030     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
5031       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5032     // Add CTR register as callee so a bctr can be emitted later.
5033     if (isTailCall)
5034       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5035   }
5036 
5037   // If this is a direct call, pass the chain and the callee.
5038   if (Callee.getNode()) {
5039     Ops.push_back(Chain);
5040     Ops.push_back(Callee);
5041   }
5042   // If this is a tail call add stack pointer delta.
5043   if (isTailCall)
5044     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5045 
5046   // Add argument registers to the end of the list so that they are known live
5047   // into the call.
5048   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5049     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5050                                   RegsToPass[i].second.getValueType()));
5051 
5052   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
5053   // into the call.
5054   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
5055     setUsesTOCBasePtr(DAG);
5056     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
5057   }
5058 
5059   return CallOpc;
5060 }
5061 
5062 SDValue PPCTargetLowering::LowerCallResult(
5063     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5064     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5065     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5066   SmallVector<CCValAssign, 16> RVLocs;
5067   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5068                     *DAG.getContext());
5069 
5070   CCRetInfo.AnalyzeCallResult(
5071       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5072                ? RetCC_PPC_Cold
5073                : RetCC_PPC);
5074 
5075   // Copy all of the result registers out of their specified physreg.
5076   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5077     CCValAssign &VA = RVLocs[i];
5078     assert(VA.isRegLoc() && "Can only return in registers!");
5079 
5080     SDValue Val = DAG.getCopyFromReg(Chain, dl,
5081                                      VA.getLocReg(), VA.getLocVT(), InFlag);
5082     Chain = Val.getValue(1);
5083     InFlag = Val.getValue(2);
5084 
5085     switch (VA.getLocInfo()) {
5086     default: llvm_unreachable("Unknown loc info!");
5087     case CCValAssign::Full: break;
5088     case CCValAssign::AExt:
5089       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5090       break;
5091     case CCValAssign::ZExt:
5092       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5093                         DAG.getValueType(VA.getValVT()));
5094       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5095       break;
5096     case CCValAssign::SExt:
5097       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5098                         DAG.getValueType(VA.getValVT()));
5099       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5100       break;
5101     }
5102 
5103     InVals.push_back(Val);
5104   }
5105 
5106   return Chain;
5107 }
5108 
5109 SDValue PPCTargetLowering::FinishCall(
5110     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5111     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5112     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5113     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5114     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5115     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5116   std::vector<EVT> NodeTys;
5117   SmallVector<SDValue, 8> Ops;
5118   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5119                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5120                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5121 
5122   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5123   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5124     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5125 
5126   // When performing tail call optimization the callee pops its arguments off
5127   // the stack. Account for this here so these bytes can be pushed back on in
5128   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5129   int BytesCalleePops =
5130     (CallConv == CallingConv::Fast &&
5131      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5132 
5133   // Add a register mask operand representing the call-preserved registers.
5134   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5135   const uint32_t *Mask =
5136       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5137   assert(Mask && "Missing call preserved mask for calling convention");
5138   Ops.push_back(DAG.getRegisterMask(Mask));
5139 
5140   if (InFlag.getNode())
5141     Ops.push_back(InFlag);
5142 
5143   // Emit tail call.
5144   if (isTailCall) {
5145     assert(((Callee.getOpcode() == ISD::Register &&
5146              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5147             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5148             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5149             isa<ConstantSDNode>(Callee)) &&
5150     "Expecting an global address, external symbol, absolute value or register");
5151 
5152     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5153     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5154   }
5155 
5156   // Add a NOP immediately after the branch instruction when using the 64-bit
5157   // SVR4 ABI. At link time, if caller and callee are in a different module and
5158   // thus have a different TOC, the call will be replaced with a call to a stub
5159   // function which saves the current TOC, loads the TOC of the callee and
5160   // branches to the callee. The NOP will be replaced with a load instruction
5161   // which restores the TOC of the caller from the TOC save slot of the current
5162   // stack frame. If caller and callee belong to the same module (and have the
5163   // same TOC), the NOP will remain unchanged.
5164 
5165   MachineFunction &MF = DAG.getMachineFunction();
5166   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
5167       !isPatchPoint) {
5168     if (CallOpc == PPCISD::BCTRL) {
5169       // This is a call through a function pointer.
5170       // Restore the caller TOC from the save area into R2.
5171       // See PrepareCall() for more information about calls through function
5172       // pointers in the 64-bit SVR4 ABI.
5173       // We are using a target-specific load with r2 hard coded, because the
5174       // result of a target-independent load would never go directly into r2,
5175       // since r2 is a reserved register (which prevents the register allocator
5176       // from allocating it), resulting in an additional register being
5177       // allocated and an unnecessary move instruction being generated.
5178       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5179 
5180       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5181       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5182       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5183       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5184       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5185 
5186       // The address needs to go after the chain input but before the flag (or
5187       // any other variadic arguments).
5188       Ops.insert(std::next(Ops.begin()), AddTOC);
5189     } else if (CallOpc == PPCISD::CALL &&
5190       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5191       // Otherwise insert NOP for non-local calls.
5192       CallOpc = PPCISD::CALL_NOP;
5193     }
5194   }
5195 
5196   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5197   InFlag = Chain.getValue(1);
5198 
5199   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5200                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5201                              InFlag, dl);
5202   if (!Ins.empty())
5203     InFlag = Chain.getValue(1);
5204 
5205   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5206                          Ins, dl, DAG, InVals);
5207 }
5208 
5209 SDValue
5210 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5211                              SmallVectorImpl<SDValue> &InVals) const {
5212   SelectionDAG &DAG                     = CLI.DAG;
5213   SDLoc &dl                             = CLI.DL;
5214   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5215   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5216   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5217   SDValue Chain                         = CLI.Chain;
5218   SDValue Callee                        = CLI.Callee;
5219   bool &isTailCall                      = CLI.IsTailCall;
5220   CallingConv::ID CallConv              = CLI.CallConv;
5221   bool isVarArg                         = CLI.IsVarArg;
5222   bool isPatchPoint                     = CLI.IsPatchPoint;
5223   ImmutableCallSite CS                  = CLI.CS;
5224 
5225   if (isTailCall) {
5226     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5227       isTailCall = false;
5228     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5229       isTailCall =
5230         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5231                                                  isVarArg, Outs, Ins, DAG);
5232     else
5233       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5234                                                      Ins, DAG);
5235     if (isTailCall) {
5236       ++NumTailCalls;
5237       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5238         ++NumSiblingCalls;
5239 
5240       assert(isa<GlobalAddressSDNode>(Callee) &&
5241              "Callee should be an llvm::Function object.");
5242       LLVM_DEBUG(
5243           const GlobalValue *GV =
5244               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5245           const unsigned Width =
5246               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5247           dbgs() << "TCO caller: "
5248                  << left_justify(DAG.getMachineFunction().getName(), Width)
5249                  << ", callee linkage: " << GV->getVisibility() << ", "
5250                  << GV->getLinkage() << "\n");
5251     }
5252   }
5253 
5254   if (!isTailCall && CS && CS.isMustTailCall())
5255     report_fatal_error("failed to perform tail call elimination on a call "
5256                        "site marked musttail");
5257 
5258   // When long calls (i.e. indirect calls) are always used, calls are always
5259   // made via function pointer. If we have a function name, first translate it
5260   // into a pointer.
5261   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5262       !isTailCall)
5263     Callee = LowerGlobalAddress(Callee, DAG);
5264 
5265   if (Subtarget.isSVR4ABI()) {
5266     if (Subtarget.isPPC64())
5267       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5268                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5269                               dl, DAG, InVals, CS);
5270     else
5271       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5272                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5273                               dl, DAG, InVals, CS);
5274   }
5275 
5276   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5277                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5278                           dl, DAG, InVals, CS);
5279 }
5280 
5281 SDValue PPCTargetLowering::LowerCall_32SVR4(
5282     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5283     bool isTailCall, bool isPatchPoint,
5284     const SmallVectorImpl<ISD::OutputArg> &Outs,
5285     const SmallVectorImpl<SDValue> &OutVals,
5286     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5287     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5288     ImmutableCallSite CS) const {
5289   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5290   // of the 32-bit SVR4 ABI stack frame layout.
5291 
5292   assert((CallConv == CallingConv::C ||
5293           CallConv == CallingConv::Cold ||
5294           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5295 
5296   unsigned PtrByteSize = 4;
5297 
5298   MachineFunction &MF = DAG.getMachineFunction();
5299 
5300   // Mark this function as potentially containing a function that contains a
5301   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5302   // and restoring the callers stack pointer in this functions epilog. This is
5303   // done because by tail calling the called function might overwrite the value
5304   // in this function's (MF) stack pointer stack slot 0(SP).
5305   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5306       CallConv == CallingConv::Fast)
5307     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5308 
5309   // Count how many bytes are to be pushed on the stack, including the linkage
5310   // area, parameter list area and the part of the local variable space which
5311   // contains copies of aggregates which are passed by value.
5312 
5313   // Assign locations to all of the outgoing arguments.
5314   SmallVector<CCValAssign, 16> ArgLocs;
5315   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5316 
5317   // Reserve space for the linkage area on the stack.
5318   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5319                        PtrByteSize);
5320   if (useSoftFloat())
5321     CCInfo.PreAnalyzeCallOperands(Outs);
5322 
5323   if (isVarArg) {
5324     // Handle fixed and variable vector arguments differently.
5325     // Fixed vector arguments go into registers as long as registers are
5326     // available. Variable vector arguments always go into memory.
5327     unsigned NumArgs = Outs.size();
5328 
5329     for (unsigned i = 0; i != NumArgs; ++i) {
5330       MVT ArgVT = Outs[i].VT;
5331       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5332       bool Result;
5333 
5334       if (Outs[i].IsFixed) {
5335         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5336                                CCInfo);
5337       } else {
5338         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5339                                       ArgFlags, CCInfo);
5340       }
5341 
5342       if (Result) {
5343 #ifndef NDEBUG
5344         errs() << "Call operand #" << i << " has unhandled type "
5345              << EVT(ArgVT).getEVTString() << "\n";
5346 #endif
5347         llvm_unreachable(nullptr);
5348       }
5349     }
5350   } else {
5351     // All arguments are treated the same.
5352     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5353   }
5354   CCInfo.clearWasPPCF128();
5355 
5356   // Assign locations to all of the outgoing aggregate by value arguments.
5357   SmallVector<CCValAssign, 16> ByValArgLocs;
5358   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5359 
5360   // Reserve stack space for the allocations in CCInfo.
5361   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5362 
5363   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5364 
5365   // Size of the linkage area, parameter list area and the part of the local
5366   // space variable where copies of aggregates which are passed by value are
5367   // stored.
5368   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5369 
5370   // Calculate by how many bytes the stack has to be adjusted in case of tail
5371   // call optimization.
5372   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5373 
5374   // Adjust the stack pointer for the new arguments...
5375   // These operations are automatically eliminated by the prolog/epilog pass
5376   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5377   SDValue CallSeqStart = Chain;
5378 
5379   // Load the return address and frame pointer so it can be moved somewhere else
5380   // later.
5381   SDValue LROp, FPOp;
5382   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5383 
5384   // Set up a copy of the stack pointer for use loading and storing any
5385   // arguments that may not fit in the registers available for argument
5386   // passing.
5387   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5388 
5389   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5390   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5391   SmallVector<SDValue, 8> MemOpChains;
5392 
5393   bool seenFloatArg = false;
5394   // Walk the register/memloc assignments, inserting copies/loads.
5395   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5396        i != e;
5397        ++i) {
5398     CCValAssign &VA = ArgLocs[i];
5399     SDValue Arg = OutVals[i];
5400     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5401 
5402     if (Flags.isByVal()) {
5403       // Argument is an aggregate which is passed by value, thus we need to
5404       // create a copy of it in the local variable space of the current stack
5405       // frame (which is the stack frame of the caller) and pass the address of
5406       // this copy to the callee.
5407       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5408       CCValAssign &ByValVA = ByValArgLocs[j++];
5409       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5410 
5411       // Memory reserved in the local variable space of the callers stack frame.
5412       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5413 
5414       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5415       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5416                            StackPtr, PtrOff);
5417 
5418       // Create a copy of the argument in the local area of the current
5419       // stack frame.
5420       SDValue MemcpyCall =
5421         CreateCopyOfByValArgument(Arg, PtrOff,
5422                                   CallSeqStart.getNode()->getOperand(0),
5423                                   Flags, DAG, dl);
5424 
5425       // This must go outside the CALLSEQ_START..END.
5426       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5427                                                      SDLoc(MemcpyCall));
5428       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5429                              NewCallSeqStart.getNode());
5430       Chain = CallSeqStart = NewCallSeqStart;
5431 
5432       // Pass the address of the aggregate copy on the stack either in a
5433       // physical register or in the parameter list area of the current stack
5434       // frame to the callee.
5435       Arg = PtrOff;
5436     }
5437 
5438     if (VA.isRegLoc()) {
5439       if (Arg.getValueType() == MVT::i1)
5440         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5441 
5442       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5443       // Put argument in a physical register.
5444       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5445     } else {
5446       // Put argument in the parameter list area of the current stack frame.
5447       assert(VA.isMemLoc());
5448       unsigned LocMemOffset = VA.getLocMemOffset();
5449 
5450       if (!isTailCall) {
5451         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5452         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5453                              StackPtr, PtrOff);
5454 
5455         MemOpChains.push_back(
5456             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5457       } else {
5458         // Calculate and remember argument location.
5459         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5460                                  TailCallArguments);
5461       }
5462     }
5463   }
5464 
5465   if (!MemOpChains.empty())
5466     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5467 
5468   // Build a sequence of copy-to-reg nodes chained together with token chain
5469   // and flag operands which copy the outgoing args into the appropriate regs.
5470   SDValue InFlag;
5471   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5472     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5473                              RegsToPass[i].second, InFlag);
5474     InFlag = Chain.getValue(1);
5475   }
5476 
5477   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5478   // registers.
5479   if (isVarArg) {
5480     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5481     SDValue Ops[] = { Chain, InFlag };
5482 
5483     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5484                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5485 
5486     InFlag = Chain.getValue(1);
5487   }
5488 
5489   if (isTailCall)
5490     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5491                     TailCallArguments);
5492 
5493   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5494                     /* unused except on PPC64 ELFv1 */ false, DAG,
5495                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5496                     NumBytes, Ins, InVals, CS);
5497 }
5498 
5499 // Copy an argument into memory, being careful to do this outside the
5500 // call sequence for the call to which the argument belongs.
5501 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5502     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5503     SelectionDAG &DAG, const SDLoc &dl) const {
5504   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5505                         CallSeqStart.getNode()->getOperand(0),
5506                         Flags, DAG, dl);
5507   // The MEMCPY must go outside the CALLSEQ_START..END.
5508   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5509   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5510                                                  SDLoc(MemcpyCall));
5511   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5512                          NewCallSeqStart.getNode());
5513   return NewCallSeqStart;
5514 }
5515 
5516 SDValue PPCTargetLowering::LowerCall_64SVR4(
5517     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5518     bool isTailCall, bool isPatchPoint,
5519     const SmallVectorImpl<ISD::OutputArg> &Outs,
5520     const SmallVectorImpl<SDValue> &OutVals,
5521     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5522     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5523     ImmutableCallSite CS) const {
5524   bool isELFv2ABI = Subtarget.isELFv2ABI();
5525   bool isLittleEndian = Subtarget.isLittleEndian();
5526   unsigned NumOps = Outs.size();
5527   bool hasNest = false;
5528   bool IsSibCall = false;
5529 
5530   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5531   unsigned PtrByteSize = 8;
5532 
5533   MachineFunction &MF = DAG.getMachineFunction();
5534 
5535   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5536     IsSibCall = true;
5537 
5538   // Mark this function as potentially containing a function that contains a
5539   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5540   // and restoring the callers stack pointer in this functions epilog. This is
5541   // done because by tail calling the called function might overwrite the value
5542   // in this function's (MF) stack pointer stack slot 0(SP).
5543   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5544       CallConv == CallingConv::Fast)
5545     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5546 
5547   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5548          "fastcc not supported on varargs functions");
5549 
5550   // Count how many bytes are to be pushed on the stack, including the linkage
5551   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5552   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5553   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5554   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5555   unsigned NumBytes = LinkageSize;
5556   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5557   unsigned &QFPR_idx = FPR_idx;
5558 
5559   static const MCPhysReg GPR[] = {
5560     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5561     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5562   };
5563   static const MCPhysReg VR[] = {
5564     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5565     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5566   };
5567 
5568   const unsigned NumGPRs = array_lengthof(GPR);
5569   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5570   const unsigned NumVRs  = array_lengthof(VR);
5571   const unsigned NumQFPRs = NumFPRs;
5572 
5573   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5574   // can be passed to the callee in registers.
5575   // For the fast calling convention, there is another check below.
5576   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5577   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5578   if (!HasParameterArea) {
5579     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5580     unsigned AvailableFPRs = NumFPRs;
5581     unsigned AvailableVRs = NumVRs;
5582     unsigned NumBytesTmp = NumBytes;
5583     for (unsigned i = 0; i != NumOps; ++i) {
5584       if (Outs[i].Flags.isNest()) continue;
5585       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5586                                 PtrByteSize, LinkageSize, ParamAreaSize,
5587                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5588                                 Subtarget.hasQPX()))
5589         HasParameterArea = true;
5590     }
5591   }
5592 
5593   // When using the fast calling convention, we don't provide backing for
5594   // arguments that will be in registers.
5595   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5596 
5597   // Avoid allocating parameter area for fastcc functions if all the arguments
5598   // can be passed in the registers.
5599   if (CallConv == CallingConv::Fast)
5600     HasParameterArea = false;
5601 
5602   // Add up all the space actually used.
5603   for (unsigned i = 0; i != NumOps; ++i) {
5604     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5605     EVT ArgVT = Outs[i].VT;
5606     EVT OrigVT = Outs[i].ArgVT;
5607 
5608     if (Flags.isNest())
5609       continue;
5610 
5611     if (CallConv == CallingConv::Fast) {
5612       if (Flags.isByVal()) {
5613         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5614         if (NumGPRsUsed > NumGPRs)
5615           HasParameterArea = true;
5616       } else {
5617         switch (ArgVT.getSimpleVT().SimpleTy) {
5618         default: llvm_unreachable("Unexpected ValueType for argument!");
5619         case MVT::i1:
5620         case MVT::i32:
5621         case MVT::i64:
5622           if (++NumGPRsUsed <= NumGPRs)
5623             continue;
5624           break;
5625         case MVT::v4i32:
5626         case MVT::v8i16:
5627         case MVT::v16i8:
5628         case MVT::v2f64:
5629         case MVT::v2i64:
5630         case MVT::v1i128:
5631         case MVT::f128:
5632           if (++NumVRsUsed <= NumVRs)
5633             continue;
5634           break;
5635         case MVT::v4f32:
5636           // When using QPX, this is handled like a FP register, otherwise, it
5637           // is an Altivec register.
5638           if (Subtarget.hasQPX()) {
5639             if (++NumFPRsUsed <= NumFPRs)
5640               continue;
5641           } else {
5642             if (++NumVRsUsed <= NumVRs)
5643               continue;
5644           }
5645           break;
5646         case MVT::f32:
5647         case MVT::f64:
5648         case MVT::v4f64: // QPX
5649         case MVT::v4i1:  // QPX
5650           if (++NumFPRsUsed <= NumFPRs)
5651             continue;
5652           break;
5653         }
5654         HasParameterArea = true;
5655       }
5656     }
5657 
5658     /* Respect alignment of argument on the stack.  */
5659     unsigned Align =
5660       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5661     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5662 
5663     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5664     if (Flags.isInConsecutiveRegsLast())
5665       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5666   }
5667 
5668   unsigned NumBytesActuallyUsed = NumBytes;
5669 
5670   // In the old ELFv1 ABI,
5671   // the prolog code of the callee may store up to 8 GPR argument registers to
5672   // the stack, allowing va_start to index over them in memory if its varargs.
5673   // Because we cannot tell if this is needed on the caller side, we have to
5674   // conservatively assume that it is needed.  As such, make sure we have at
5675   // least enough stack space for the caller to store the 8 GPRs.
5676   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5677   // really requires memory operands, e.g. a vararg function.
5678   if (HasParameterArea)
5679     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5680   else
5681     NumBytes = LinkageSize;
5682 
5683   // Tail call needs the stack to be aligned.
5684   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5685       CallConv == CallingConv::Fast)
5686     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5687 
5688   int SPDiff = 0;
5689 
5690   // Calculate by how many bytes the stack has to be adjusted in case of tail
5691   // call optimization.
5692   if (!IsSibCall)
5693     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5694 
5695   // To protect arguments on the stack from being clobbered in a tail call,
5696   // force all the loads to happen before doing any other lowering.
5697   if (isTailCall)
5698     Chain = DAG.getStackArgumentTokenFactor(Chain);
5699 
5700   // Adjust the stack pointer for the new arguments...
5701   // These operations are automatically eliminated by the prolog/epilog pass
5702   if (!IsSibCall)
5703     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5704   SDValue CallSeqStart = Chain;
5705 
5706   // Load the return address and frame pointer so it can be move somewhere else
5707   // later.
5708   SDValue LROp, FPOp;
5709   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5710 
5711   // Set up a copy of the stack pointer for use loading and storing any
5712   // arguments that may not fit in the registers available for argument
5713   // passing.
5714   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5715 
5716   // Figure out which arguments are going to go in registers, and which in
5717   // memory.  Also, if this is a vararg function, floating point operations
5718   // must be stored to our stack, and loaded into integer regs as well, if
5719   // any integer regs are available for argument passing.
5720   unsigned ArgOffset = LinkageSize;
5721 
5722   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5723   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5724 
5725   SmallVector<SDValue, 8> MemOpChains;
5726   for (unsigned i = 0; i != NumOps; ++i) {
5727     SDValue Arg = OutVals[i];
5728     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5729     EVT ArgVT = Outs[i].VT;
5730     EVT OrigVT = Outs[i].ArgVT;
5731 
5732     // PtrOff will be used to store the current argument to the stack if a
5733     // register cannot be found for it.
5734     SDValue PtrOff;
5735 
5736     // We re-align the argument offset for each argument, except when using the
5737     // fast calling convention, when we need to make sure we do that only when
5738     // we'll actually use a stack slot.
5739     auto ComputePtrOff = [&]() {
5740       /* Respect alignment of argument on the stack.  */
5741       unsigned Align =
5742         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5743       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5744 
5745       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5746 
5747       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5748     };
5749 
5750     if (CallConv != CallingConv::Fast) {
5751       ComputePtrOff();
5752 
5753       /* Compute GPR index associated with argument offset.  */
5754       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5755       GPR_idx = std::min(GPR_idx, NumGPRs);
5756     }
5757 
5758     // Promote integers to 64-bit values.
5759     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5760       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5761       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5762       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5763     }
5764 
5765     // FIXME memcpy is used way more than necessary.  Correctness first.
5766     // Note: "by value" is code for passing a structure by value, not
5767     // basic types.
5768     if (Flags.isByVal()) {
5769       // Note: Size includes alignment padding, so
5770       //   struct x { short a; char b; }
5771       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5772       // These are the proper values we need for right-justifying the
5773       // aggregate in a parameter register.
5774       unsigned Size = Flags.getByValSize();
5775 
5776       // An empty aggregate parameter takes up no storage and no
5777       // registers.
5778       if (Size == 0)
5779         continue;
5780 
5781       if (CallConv == CallingConv::Fast)
5782         ComputePtrOff();
5783 
5784       // All aggregates smaller than 8 bytes must be passed right-justified.
5785       if (Size==1 || Size==2 || Size==4) {
5786         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5787         if (GPR_idx != NumGPRs) {
5788           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5789                                         MachinePointerInfo(), VT);
5790           MemOpChains.push_back(Load.getValue(1));
5791           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5792 
5793           ArgOffset += PtrByteSize;
5794           continue;
5795         }
5796       }
5797 
5798       if (GPR_idx == NumGPRs && Size < 8) {
5799         SDValue AddPtr = PtrOff;
5800         if (!isLittleEndian) {
5801           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5802                                           PtrOff.getValueType());
5803           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5804         }
5805         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5806                                                           CallSeqStart,
5807                                                           Flags, DAG, dl);
5808         ArgOffset += PtrByteSize;
5809         continue;
5810       }
5811       // Copy entire object into memory.  There are cases where gcc-generated
5812       // code assumes it is there, even if it could be put entirely into
5813       // registers.  (This is not what the doc says.)
5814 
5815       // FIXME: The above statement is likely due to a misunderstanding of the
5816       // documents.  All arguments must be copied into the parameter area BY
5817       // THE CALLEE in the event that the callee takes the address of any
5818       // formal argument.  That has not yet been implemented.  However, it is
5819       // reasonable to use the stack area as a staging area for the register
5820       // load.
5821 
5822       // Skip this for small aggregates, as we will use the same slot for a
5823       // right-justified copy, below.
5824       if (Size >= 8)
5825         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5826                                                           CallSeqStart,
5827                                                           Flags, DAG, dl);
5828 
5829       // When a register is available, pass a small aggregate right-justified.
5830       if (Size < 8 && GPR_idx != NumGPRs) {
5831         // The easiest way to get this right-justified in a register
5832         // is to copy the structure into the rightmost portion of a
5833         // local variable slot, then load the whole slot into the
5834         // register.
5835         // FIXME: The memcpy seems to produce pretty awful code for
5836         // small aggregates, particularly for packed ones.
5837         // FIXME: It would be preferable to use the slot in the
5838         // parameter save area instead of a new local variable.
5839         SDValue AddPtr = PtrOff;
5840         if (!isLittleEndian) {
5841           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5842           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5843         }
5844         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5845                                                           CallSeqStart,
5846                                                           Flags, DAG, dl);
5847 
5848         // Load the slot into the register.
5849         SDValue Load =
5850             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5851         MemOpChains.push_back(Load.getValue(1));
5852         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5853 
5854         // Done with this argument.
5855         ArgOffset += PtrByteSize;
5856         continue;
5857       }
5858 
5859       // For aggregates larger than PtrByteSize, copy the pieces of the
5860       // object that fit into registers from the parameter save area.
5861       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5862         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5863         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5864         if (GPR_idx != NumGPRs) {
5865           SDValue Load =
5866               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5867           MemOpChains.push_back(Load.getValue(1));
5868           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5869           ArgOffset += PtrByteSize;
5870         } else {
5871           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5872           break;
5873         }
5874       }
5875       continue;
5876     }
5877 
5878     switch (Arg.getSimpleValueType().SimpleTy) {
5879     default: llvm_unreachable("Unexpected ValueType for argument!");
5880     case MVT::i1:
5881     case MVT::i32:
5882     case MVT::i64:
5883       if (Flags.isNest()) {
5884         // The 'nest' parameter, if any, is passed in R11.
5885         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5886         hasNest = true;
5887         break;
5888       }
5889 
5890       // These can be scalar arguments or elements of an integer array type
5891       // passed directly.  Clang may use those instead of "byval" aggregate
5892       // types to avoid forcing arguments to memory unnecessarily.
5893       if (GPR_idx != NumGPRs) {
5894         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5895       } else {
5896         if (CallConv == CallingConv::Fast)
5897           ComputePtrOff();
5898 
5899         assert(HasParameterArea &&
5900                "Parameter area must exist to pass an argument in memory.");
5901         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5902                          true, isTailCall, false, MemOpChains,
5903                          TailCallArguments, dl);
5904         if (CallConv == CallingConv::Fast)
5905           ArgOffset += PtrByteSize;
5906       }
5907       if (CallConv != CallingConv::Fast)
5908         ArgOffset += PtrByteSize;
5909       break;
5910     case MVT::f32:
5911     case MVT::f64: {
5912       // These can be scalar arguments or elements of a float array type
5913       // passed directly.  The latter are used to implement ELFv2 homogenous
5914       // float aggregates.
5915 
5916       // Named arguments go into FPRs first, and once they overflow, the
5917       // remaining arguments go into GPRs and then the parameter save area.
5918       // Unnamed arguments for vararg functions always go to GPRs and
5919       // then the parameter save area.  For now, put all arguments to vararg
5920       // routines always in both locations (FPR *and* GPR or stack slot).
5921       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5922       bool NeededLoad = false;
5923 
5924       // First load the argument into the next available FPR.
5925       if (FPR_idx != NumFPRs)
5926         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5927 
5928       // Next, load the argument into GPR or stack slot if needed.
5929       if (!NeedGPROrStack)
5930         ;
5931       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5932         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5933         // once we support fp <-> gpr moves.
5934 
5935         // In the non-vararg case, this can only ever happen in the
5936         // presence of f32 array types, since otherwise we never run
5937         // out of FPRs before running out of GPRs.
5938         SDValue ArgVal;
5939 
5940         // Double values are always passed in a single GPR.
5941         if (Arg.getValueType() != MVT::f32) {
5942           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5943 
5944         // Non-array float values are extended and passed in a GPR.
5945         } else if (!Flags.isInConsecutiveRegs()) {
5946           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5947           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5948 
5949         // If we have an array of floats, we collect every odd element
5950         // together with its predecessor into one GPR.
5951         } else if (ArgOffset % PtrByteSize != 0) {
5952           SDValue Lo, Hi;
5953           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5954           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5955           if (!isLittleEndian)
5956             std::swap(Lo, Hi);
5957           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5958 
5959         // The final element, if even, goes into the first half of a GPR.
5960         } else if (Flags.isInConsecutiveRegsLast()) {
5961           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5962           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5963           if (!isLittleEndian)
5964             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5965                                  DAG.getConstant(32, dl, MVT::i32));
5966 
5967         // Non-final even elements are skipped; they will be handled
5968         // together the with subsequent argument on the next go-around.
5969         } else
5970           ArgVal = SDValue();
5971 
5972         if (ArgVal.getNode())
5973           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5974       } else {
5975         if (CallConv == CallingConv::Fast)
5976           ComputePtrOff();
5977 
5978         // Single-precision floating-point values are mapped to the
5979         // second (rightmost) word of the stack doubleword.
5980         if (Arg.getValueType() == MVT::f32 &&
5981             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5982           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5983           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5984         }
5985 
5986         assert(HasParameterArea &&
5987                "Parameter area must exist to pass an argument in memory.");
5988         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5989                          true, isTailCall, false, MemOpChains,
5990                          TailCallArguments, dl);
5991 
5992         NeededLoad = true;
5993       }
5994       // When passing an array of floats, the array occupies consecutive
5995       // space in the argument area; only round up to the next doubleword
5996       // at the end of the array.  Otherwise, each float takes 8 bytes.
5997       if (CallConv != CallingConv::Fast || NeededLoad) {
5998         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5999                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6000         if (Flags.isInConsecutiveRegsLast())
6001           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6002       }
6003       break;
6004     }
6005     case MVT::v4f32:
6006     case MVT::v4i32:
6007     case MVT::v8i16:
6008     case MVT::v16i8:
6009     case MVT::v2f64:
6010     case MVT::v2i64:
6011     case MVT::v1i128:
6012     case MVT::f128:
6013       if (!Subtarget.hasQPX()) {
6014       // These can be scalar arguments or elements of a vector array type
6015       // passed directly.  The latter are used to implement ELFv2 homogenous
6016       // vector aggregates.
6017 
6018       // For a varargs call, named arguments go into VRs or on the stack as
6019       // usual; unnamed arguments always go to the stack or the corresponding
6020       // GPRs when within range.  For now, we always put the value in both
6021       // locations (or even all three).
6022       if (isVarArg) {
6023         assert(HasParameterArea &&
6024                "Parameter area must exist if we have a varargs call.");
6025         // We could elide this store in the case where the object fits
6026         // entirely in R registers.  Maybe later.
6027         SDValue Store =
6028             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6029         MemOpChains.push_back(Store);
6030         if (VR_idx != NumVRs) {
6031           SDValue Load =
6032               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6033           MemOpChains.push_back(Load.getValue(1));
6034           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6035         }
6036         ArgOffset += 16;
6037         for (unsigned i=0; i<16; i+=PtrByteSize) {
6038           if (GPR_idx == NumGPRs)
6039             break;
6040           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6041                                    DAG.getConstant(i, dl, PtrVT));
6042           SDValue Load =
6043               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6044           MemOpChains.push_back(Load.getValue(1));
6045           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6046         }
6047         break;
6048       }
6049 
6050       // Non-varargs Altivec params go into VRs or on the stack.
6051       if (VR_idx != NumVRs) {
6052         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6053       } else {
6054         if (CallConv == CallingConv::Fast)
6055           ComputePtrOff();
6056 
6057         assert(HasParameterArea &&
6058                "Parameter area must exist to pass an argument in memory.");
6059         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6060                          true, isTailCall, true, MemOpChains,
6061                          TailCallArguments, dl);
6062         if (CallConv == CallingConv::Fast)
6063           ArgOffset += 16;
6064       }
6065 
6066       if (CallConv != CallingConv::Fast)
6067         ArgOffset += 16;
6068       break;
6069       } // not QPX
6070 
6071       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6072              "Invalid QPX parameter type");
6073 
6074       /* fall through */
6075     case MVT::v4f64:
6076     case MVT::v4i1: {
6077       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6078       if (isVarArg) {
6079         assert(HasParameterArea &&
6080                "Parameter area must exist if we have a varargs call.");
6081         // We could elide this store in the case where the object fits
6082         // entirely in R registers.  Maybe later.
6083         SDValue Store =
6084             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6085         MemOpChains.push_back(Store);
6086         if (QFPR_idx != NumQFPRs) {
6087           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6088                                      PtrOff, MachinePointerInfo());
6089           MemOpChains.push_back(Load.getValue(1));
6090           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6091         }
6092         ArgOffset += (IsF32 ? 16 : 32);
6093         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6094           if (GPR_idx == NumGPRs)
6095             break;
6096           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6097                                    DAG.getConstant(i, dl, PtrVT));
6098           SDValue Load =
6099               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6100           MemOpChains.push_back(Load.getValue(1));
6101           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6102         }
6103         break;
6104       }
6105 
6106       // Non-varargs QPX params go into registers or on the stack.
6107       if (QFPR_idx != NumQFPRs) {
6108         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6109       } else {
6110         if (CallConv == CallingConv::Fast)
6111           ComputePtrOff();
6112 
6113         assert(HasParameterArea &&
6114                "Parameter area must exist to pass an argument in memory.");
6115         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6116                          true, isTailCall, true, MemOpChains,
6117                          TailCallArguments, dl);
6118         if (CallConv == CallingConv::Fast)
6119           ArgOffset += (IsF32 ? 16 : 32);
6120       }
6121 
6122       if (CallConv != CallingConv::Fast)
6123         ArgOffset += (IsF32 ? 16 : 32);
6124       break;
6125       }
6126     }
6127   }
6128 
6129   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6130          "mismatch in size of parameter area");
6131   (void)NumBytesActuallyUsed;
6132 
6133   if (!MemOpChains.empty())
6134     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6135 
6136   // Check if this is an indirect call (MTCTR/BCTRL).
6137   // See PrepareCall() for more information about calls through function
6138   // pointers in the 64-bit SVR4 ABI.
6139   if (!isTailCall && !isPatchPoint &&
6140       !isFunctionGlobalAddress(Callee) &&
6141       !isa<ExternalSymbolSDNode>(Callee)) {
6142     // Load r2 into a virtual register and store it to the TOC save area.
6143     setUsesTOCBasePtr(DAG);
6144     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6145     // TOC save area offset.
6146     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6147     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6148     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6149     Chain = DAG.getStore(
6150         Val.getValue(1), dl, Val, AddPtr,
6151         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6152     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6153     // This does not mean the MTCTR instruction must use R12; it's easier
6154     // to model this as an extra parameter, so do that.
6155     if (isELFv2ABI && !isPatchPoint)
6156       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6157   }
6158 
6159   // Build a sequence of copy-to-reg nodes chained together with token chain
6160   // and flag operands which copy the outgoing args into the appropriate regs.
6161   SDValue InFlag;
6162   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6163     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6164                              RegsToPass[i].second, InFlag);
6165     InFlag = Chain.getValue(1);
6166   }
6167 
6168   if (isTailCall && !IsSibCall)
6169     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6170                     TailCallArguments);
6171 
6172   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6173                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6174                     SPDiff, NumBytes, Ins, InVals, CS);
6175 }
6176 
6177 SDValue PPCTargetLowering::LowerCall_Darwin(
6178     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6179     bool isTailCall, bool isPatchPoint,
6180     const SmallVectorImpl<ISD::OutputArg> &Outs,
6181     const SmallVectorImpl<SDValue> &OutVals,
6182     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6183     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6184     ImmutableCallSite CS) const {
6185   unsigned NumOps = Outs.size();
6186 
6187   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6188   bool isPPC64 = PtrVT == MVT::i64;
6189   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6190 
6191   MachineFunction &MF = DAG.getMachineFunction();
6192 
6193   // Mark this function as potentially containing a function that contains a
6194   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6195   // and restoring the callers stack pointer in this functions epilog. This is
6196   // done because by tail calling the called function might overwrite the value
6197   // in this function's (MF) stack pointer stack slot 0(SP).
6198   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6199       CallConv == CallingConv::Fast)
6200     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6201 
6202   // Count how many bytes are to be pushed on the stack, including the linkage
6203   // area, and parameter passing area.  We start with 24/48 bytes, which is
6204   // prereserved space for [SP][CR][LR][3 x unused].
6205   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6206   unsigned NumBytes = LinkageSize;
6207 
6208   // Add up all the space actually used.
6209   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6210   // they all go in registers, but we must reserve stack space for them for
6211   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6212   // assigned stack space in order, with padding so Altivec parameters are
6213   // 16-byte aligned.
6214   unsigned nAltivecParamsAtEnd = 0;
6215   for (unsigned i = 0; i != NumOps; ++i) {
6216     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6217     EVT ArgVT = Outs[i].VT;
6218     // Varargs Altivec parameters are padded to a 16 byte boundary.
6219     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6220         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6221         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6222       if (!isVarArg && !isPPC64) {
6223         // Non-varargs Altivec parameters go after all the non-Altivec
6224         // parameters; handle those later so we know how much padding we need.
6225         nAltivecParamsAtEnd++;
6226         continue;
6227       }
6228       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6229       NumBytes = ((NumBytes+15)/16)*16;
6230     }
6231     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6232   }
6233 
6234   // Allow for Altivec parameters at the end, if needed.
6235   if (nAltivecParamsAtEnd) {
6236     NumBytes = ((NumBytes+15)/16)*16;
6237     NumBytes += 16*nAltivecParamsAtEnd;
6238   }
6239 
6240   // The prolog code of the callee may store up to 8 GPR argument registers to
6241   // the stack, allowing va_start to index over them in memory if its varargs.
6242   // Because we cannot tell if this is needed on the caller side, we have to
6243   // conservatively assume that it is needed.  As such, make sure we have at
6244   // least enough stack space for the caller to store the 8 GPRs.
6245   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6246 
6247   // Tail call needs the stack to be aligned.
6248   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6249       CallConv == CallingConv::Fast)
6250     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6251 
6252   // Calculate by how many bytes the stack has to be adjusted in case of tail
6253   // call optimization.
6254   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6255 
6256   // To protect arguments on the stack from being clobbered in a tail call,
6257   // force all the loads to happen before doing any other lowering.
6258   if (isTailCall)
6259     Chain = DAG.getStackArgumentTokenFactor(Chain);
6260 
6261   // Adjust the stack pointer for the new arguments...
6262   // These operations are automatically eliminated by the prolog/epilog pass
6263   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6264   SDValue CallSeqStart = Chain;
6265 
6266   // Load the return address and frame pointer so it can be move somewhere else
6267   // later.
6268   SDValue LROp, FPOp;
6269   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6270 
6271   // Set up a copy of the stack pointer for use loading and storing any
6272   // arguments that may not fit in the registers available for argument
6273   // passing.
6274   SDValue StackPtr;
6275   if (isPPC64)
6276     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6277   else
6278     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6279 
6280   // Figure out which arguments are going to go in registers, and which in
6281   // memory.  Also, if this is a vararg function, floating point operations
6282   // must be stored to our stack, and loaded into integer regs as well, if
6283   // any integer regs are available for argument passing.
6284   unsigned ArgOffset = LinkageSize;
6285   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6286 
6287   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6288     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6289     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6290   };
6291   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6292     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6293     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6294   };
6295   static const MCPhysReg VR[] = {
6296     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6297     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6298   };
6299   const unsigned NumGPRs = array_lengthof(GPR_32);
6300   const unsigned NumFPRs = 13;
6301   const unsigned NumVRs  = array_lengthof(VR);
6302 
6303   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6304 
6305   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6306   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6307 
6308   SmallVector<SDValue, 8> MemOpChains;
6309   for (unsigned i = 0; i != NumOps; ++i) {
6310     SDValue Arg = OutVals[i];
6311     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6312 
6313     // PtrOff will be used to store the current argument to the stack if a
6314     // register cannot be found for it.
6315     SDValue PtrOff;
6316 
6317     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6318 
6319     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6320 
6321     // On PPC64, promote integers to 64-bit values.
6322     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6323       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6324       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6325       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6326     }
6327 
6328     // FIXME memcpy is used way more than necessary.  Correctness first.
6329     // Note: "by value" is code for passing a structure by value, not
6330     // basic types.
6331     if (Flags.isByVal()) {
6332       unsigned Size = Flags.getByValSize();
6333       // Very small objects are passed right-justified.  Everything else is
6334       // passed left-justified.
6335       if (Size==1 || Size==2) {
6336         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6337         if (GPR_idx != NumGPRs) {
6338           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6339                                         MachinePointerInfo(), VT);
6340           MemOpChains.push_back(Load.getValue(1));
6341           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6342 
6343           ArgOffset += PtrByteSize;
6344         } else {
6345           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6346                                           PtrOff.getValueType());
6347           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6348           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6349                                                             CallSeqStart,
6350                                                             Flags, DAG, dl);
6351           ArgOffset += PtrByteSize;
6352         }
6353         continue;
6354       }
6355       // Copy entire object into memory.  There are cases where gcc-generated
6356       // code assumes it is there, even if it could be put entirely into
6357       // registers.  (This is not what the doc says.)
6358       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6359                                                         CallSeqStart,
6360                                                         Flags, DAG, dl);
6361 
6362       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6363       // copy the pieces of the object that fit into registers from the
6364       // parameter save area.
6365       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6366         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6367         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6368         if (GPR_idx != NumGPRs) {
6369           SDValue Load =
6370               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6371           MemOpChains.push_back(Load.getValue(1));
6372           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6373           ArgOffset += PtrByteSize;
6374         } else {
6375           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6376           break;
6377         }
6378       }
6379       continue;
6380     }
6381 
6382     switch (Arg.getSimpleValueType().SimpleTy) {
6383     default: llvm_unreachable("Unexpected ValueType for argument!");
6384     case MVT::i1:
6385     case MVT::i32:
6386     case MVT::i64:
6387       if (GPR_idx != NumGPRs) {
6388         if (Arg.getValueType() == MVT::i1)
6389           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6390 
6391         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6392       } else {
6393         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6394                          isPPC64, isTailCall, false, MemOpChains,
6395                          TailCallArguments, dl);
6396       }
6397       ArgOffset += PtrByteSize;
6398       break;
6399     case MVT::f32:
6400     case MVT::f64:
6401       if (FPR_idx != NumFPRs) {
6402         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6403 
6404         if (isVarArg) {
6405           SDValue Store =
6406               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6407           MemOpChains.push_back(Store);
6408 
6409           // Float varargs are always shadowed in available integer registers
6410           if (GPR_idx != NumGPRs) {
6411             SDValue Load =
6412                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6413             MemOpChains.push_back(Load.getValue(1));
6414             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6415           }
6416           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6417             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6418             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6419             SDValue Load =
6420                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6421             MemOpChains.push_back(Load.getValue(1));
6422             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6423           }
6424         } else {
6425           // If we have any FPRs remaining, we may also have GPRs remaining.
6426           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6427           // GPRs.
6428           if (GPR_idx != NumGPRs)
6429             ++GPR_idx;
6430           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6431               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6432             ++GPR_idx;
6433         }
6434       } else
6435         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6436                          isPPC64, isTailCall, false, MemOpChains,
6437                          TailCallArguments, dl);
6438       if (isPPC64)
6439         ArgOffset += 8;
6440       else
6441         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6442       break;
6443     case MVT::v4f32:
6444     case MVT::v4i32:
6445     case MVT::v8i16:
6446     case MVT::v16i8:
6447       if (isVarArg) {
6448         // These go aligned on the stack, or in the corresponding R registers
6449         // when within range.  The Darwin PPC ABI doc claims they also go in
6450         // V registers; in fact gcc does this only for arguments that are
6451         // prototyped, not for those that match the ...  We do it for all
6452         // arguments, seems to work.
6453         while (ArgOffset % 16 !=0) {
6454           ArgOffset += PtrByteSize;
6455           if (GPR_idx != NumGPRs)
6456             GPR_idx++;
6457         }
6458         // We could elide this store in the case where the object fits
6459         // entirely in R registers.  Maybe later.
6460         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6461                              DAG.getConstant(ArgOffset, dl, PtrVT));
6462         SDValue Store =
6463             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6464         MemOpChains.push_back(Store);
6465         if (VR_idx != NumVRs) {
6466           SDValue Load =
6467               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6468           MemOpChains.push_back(Load.getValue(1));
6469           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6470         }
6471         ArgOffset += 16;
6472         for (unsigned i=0; i<16; i+=PtrByteSize) {
6473           if (GPR_idx == NumGPRs)
6474             break;
6475           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6476                                    DAG.getConstant(i, dl, PtrVT));
6477           SDValue Load =
6478               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6479           MemOpChains.push_back(Load.getValue(1));
6480           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6481         }
6482         break;
6483       }
6484 
6485       // Non-varargs Altivec params generally go in registers, but have
6486       // stack space allocated at the end.
6487       if (VR_idx != NumVRs) {
6488         // Doesn't have GPR space allocated.
6489         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6490       } else if (nAltivecParamsAtEnd==0) {
6491         // We are emitting Altivec params in order.
6492         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6493                          isPPC64, isTailCall, true, MemOpChains,
6494                          TailCallArguments, dl);
6495         ArgOffset += 16;
6496       }
6497       break;
6498     }
6499   }
6500   // If all Altivec parameters fit in registers, as they usually do,
6501   // they get stack space following the non-Altivec parameters.  We
6502   // don't track this here because nobody below needs it.
6503   // If there are more Altivec parameters than fit in registers emit
6504   // the stores here.
6505   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6506     unsigned j = 0;
6507     // Offset is aligned; skip 1st 12 params which go in V registers.
6508     ArgOffset = ((ArgOffset+15)/16)*16;
6509     ArgOffset += 12*16;
6510     for (unsigned i = 0; i != NumOps; ++i) {
6511       SDValue Arg = OutVals[i];
6512       EVT ArgType = Outs[i].VT;
6513       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6514           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6515         if (++j > NumVRs) {
6516           SDValue PtrOff;
6517           // We are emitting Altivec params in order.
6518           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6519                            isPPC64, isTailCall, true, MemOpChains,
6520                            TailCallArguments, dl);
6521           ArgOffset += 16;
6522         }
6523       }
6524     }
6525   }
6526 
6527   if (!MemOpChains.empty())
6528     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6529 
6530   // On Darwin, R12 must contain the address of an indirect callee.  This does
6531   // not mean the MTCTR instruction must use R12; it's easier to model this as
6532   // an extra parameter, so do that.
6533   if (!isTailCall &&
6534       !isFunctionGlobalAddress(Callee) &&
6535       !isa<ExternalSymbolSDNode>(Callee) &&
6536       !isBLACompatibleAddress(Callee, DAG))
6537     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6538                                                    PPC::R12), Callee));
6539 
6540   // Build a sequence of copy-to-reg nodes chained together with token chain
6541   // and flag operands which copy the outgoing args into the appropriate regs.
6542   SDValue InFlag;
6543   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6544     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6545                              RegsToPass[i].second, InFlag);
6546     InFlag = Chain.getValue(1);
6547   }
6548 
6549   if (isTailCall)
6550     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6551                     TailCallArguments);
6552 
6553   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6554                     /* unused except on PPC64 ELFv1 */ false, DAG,
6555                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6556                     NumBytes, Ins, InVals, CS);
6557 }
6558 
6559 bool
6560 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6561                                   MachineFunction &MF, bool isVarArg,
6562                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6563                                   LLVMContext &Context) const {
6564   SmallVector<CCValAssign, 16> RVLocs;
6565   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6566   return CCInfo.CheckReturn(
6567       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6568                 ? RetCC_PPC_Cold
6569                 : RetCC_PPC);
6570 }
6571 
6572 SDValue
6573 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6574                                bool isVarArg,
6575                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6576                                const SmallVectorImpl<SDValue> &OutVals,
6577                                const SDLoc &dl, SelectionDAG &DAG) const {
6578   SmallVector<CCValAssign, 16> RVLocs;
6579   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6580                  *DAG.getContext());
6581   CCInfo.AnalyzeReturn(Outs,
6582                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6583                            ? RetCC_PPC_Cold
6584                            : RetCC_PPC);
6585 
6586   SDValue Flag;
6587   SmallVector<SDValue, 4> RetOps(1, Chain);
6588 
6589   // Copy the result values into the output registers.
6590   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6591     CCValAssign &VA = RVLocs[i];
6592     assert(VA.isRegLoc() && "Can only return in registers!");
6593 
6594     SDValue Arg = OutVals[i];
6595 
6596     switch (VA.getLocInfo()) {
6597     default: llvm_unreachable("Unknown loc info!");
6598     case CCValAssign::Full: break;
6599     case CCValAssign::AExt:
6600       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6601       break;
6602     case CCValAssign::ZExt:
6603       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6604       break;
6605     case CCValAssign::SExt:
6606       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6607       break;
6608     }
6609 
6610     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6611     Flag = Chain.getValue(1);
6612     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6613   }
6614 
6615   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6616   const MCPhysReg *I =
6617     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6618   if (I) {
6619     for (; *I; ++I) {
6620 
6621       if (PPC::G8RCRegClass.contains(*I))
6622         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6623       else if (PPC::F8RCRegClass.contains(*I))
6624         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6625       else if (PPC::CRRCRegClass.contains(*I))
6626         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6627       else if (PPC::VRRCRegClass.contains(*I))
6628         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6629       else
6630         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6631     }
6632   }
6633 
6634   RetOps[0] = Chain;  // Update chain.
6635 
6636   // Add the flag if we have it.
6637   if (Flag.getNode())
6638     RetOps.push_back(Flag);
6639 
6640   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6641 }
6642 
6643 SDValue
6644 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6645                                                 SelectionDAG &DAG) const {
6646   SDLoc dl(Op);
6647 
6648   // Get the correct type for integers.
6649   EVT IntVT = Op.getValueType();
6650 
6651   // Get the inputs.
6652   SDValue Chain = Op.getOperand(0);
6653   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6654   // Build a DYNAREAOFFSET node.
6655   SDValue Ops[2] = {Chain, FPSIdx};
6656   SDVTList VTs = DAG.getVTList(IntVT);
6657   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6658 }
6659 
6660 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6661                                              SelectionDAG &DAG) const {
6662   // When we pop the dynamic allocation we need to restore the SP link.
6663   SDLoc dl(Op);
6664 
6665   // Get the correct type for pointers.
6666   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6667 
6668   // Construct the stack pointer operand.
6669   bool isPPC64 = Subtarget.isPPC64();
6670   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6671   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6672 
6673   // Get the operands for the STACKRESTORE.
6674   SDValue Chain = Op.getOperand(0);
6675   SDValue SaveSP = Op.getOperand(1);
6676 
6677   // Load the old link SP.
6678   SDValue LoadLinkSP =
6679       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6680 
6681   // Restore the stack pointer.
6682   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6683 
6684   // Store the old link SP.
6685   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6686 }
6687 
6688 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6689   MachineFunction &MF = DAG.getMachineFunction();
6690   bool isPPC64 = Subtarget.isPPC64();
6691   EVT PtrVT = getPointerTy(MF.getDataLayout());
6692 
6693   // Get current frame pointer save index.  The users of this index will be
6694   // primarily DYNALLOC instructions.
6695   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6696   int RASI = FI->getReturnAddrSaveIndex();
6697 
6698   // If the frame pointer save index hasn't been defined yet.
6699   if (!RASI) {
6700     // Find out what the fix offset of the frame pointer save area.
6701     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6702     // Allocate the frame index for frame pointer save area.
6703     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6704     // Save the result.
6705     FI->setReturnAddrSaveIndex(RASI);
6706   }
6707   return DAG.getFrameIndex(RASI, PtrVT);
6708 }
6709 
6710 SDValue
6711 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6712   MachineFunction &MF = DAG.getMachineFunction();
6713   bool isPPC64 = Subtarget.isPPC64();
6714   EVT PtrVT = getPointerTy(MF.getDataLayout());
6715 
6716   // Get current frame pointer save index.  The users of this index will be
6717   // primarily DYNALLOC instructions.
6718   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6719   int FPSI = FI->getFramePointerSaveIndex();
6720 
6721   // If the frame pointer save index hasn't been defined yet.
6722   if (!FPSI) {
6723     // Find out what the fix offset of the frame pointer save area.
6724     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6725     // Allocate the frame index for frame pointer save area.
6726     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6727     // Save the result.
6728     FI->setFramePointerSaveIndex(FPSI);
6729   }
6730   return DAG.getFrameIndex(FPSI, PtrVT);
6731 }
6732 
6733 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6734                                                    SelectionDAG &DAG) const {
6735   // Get the inputs.
6736   SDValue Chain = Op.getOperand(0);
6737   SDValue Size  = Op.getOperand(1);
6738   SDLoc dl(Op);
6739 
6740   // Get the correct type for pointers.
6741   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6742   // Negate the size.
6743   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6744                                 DAG.getConstant(0, dl, PtrVT), Size);
6745   // Construct a node for the frame pointer save index.
6746   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6747   // Build a DYNALLOC node.
6748   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6749   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6750   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6751 }
6752 
6753 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6754                                                      SelectionDAG &DAG) const {
6755   MachineFunction &MF = DAG.getMachineFunction();
6756 
6757   bool isPPC64 = Subtarget.isPPC64();
6758   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6759 
6760   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6761   return DAG.getFrameIndex(FI, PtrVT);
6762 }
6763 
6764 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6765                                                SelectionDAG &DAG) const {
6766   SDLoc DL(Op);
6767   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6768                      DAG.getVTList(MVT::i32, MVT::Other),
6769                      Op.getOperand(0), Op.getOperand(1));
6770 }
6771 
6772 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6773                                                 SelectionDAG &DAG) const {
6774   SDLoc DL(Op);
6775   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6776                      Op.getOperand(0), Op.getOperand(1));
6777 }
6778 
6779 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6780   if (Op.getValueType().isVector())
6781     return LowerVectorLoad(Op, DAG);
6782 
6783   assert(Op.getValueType() == MVT::i1 &&
6784          "Custom lowering only for i1 loads");
6785 
6786   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6787 
6788   SDLoc dl(Op);
6789   LoadSDNode *LD = cast<LoadSDNode>(Op);
6790 
6791   SDValue Chain = LD->getChain();
6792   SDValue BasePtr = LD->getBasePtr();
6793   MachineMemOperand *MMO = LD->getMemOperand();
6794 
6795   SDValue NewLD =
6796       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6797                      BasePtr, MVT::i8, MMO);
6798   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6799 
6800   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6801   return DAG.getMergeValues(Ops, dl);
6802 }
6803 
6804 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6805   if (Op.getOperand(1).getValueType().isVector())
6806     return LowerVectorStore(Op, DAG);
6807 
6808   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6809          "Custom lowering only for i1 stores");
6810 
6811   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6812 
6813   SDLoc dl(Op);
6814   StoreSDNode *ST = cast<StoreSDNode>(Op);
6815 
6816   SDValue Chain = ST->getChain();
6817   SDValue BasePtr = ST->getBasePtr();
6818   SDValue Value = ST->getValue();
6819   MachineMemOperand *MMO = ST->getMemOperand();
6820 
6821   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6822                       Value);
6823   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6824 }
6825 
6826 // FIXME: Remove this once the ANDI glue bug is fixed:
6827 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6828   assert(Op.getValueType() == MVT::i1 &&
6829          "Custom lowering only for i1 results");
6830 
6831   SDLoc DL(Op);
6832   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6833                      Op.getOperand(0));
6834 }
6835 
6836 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6837 /// possible.
6838 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6839   // Not FP? Not a fsel.
6840   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6841       !Op.getOperand(2).getValueType().isFloatingPoint())
6842     return Op;
6843 
6844   // We might be able to do better than this under some circumstances, but in
6845   // general, fsel-based lowering of select is a finite-math-only optimization.
6846   // For more information, see section F.3 of the 2.06 ISA specification.
6847   if (!DAG.getTarget().Options.NoInfsFPMath ||
6848       !DAG.getTarget().Options.NoNaNsFPMath)
6849     return Op;
6850   // TODO: Propagate flags from the select rather than global settings.
6851   SDNodeFlags Flags;
6852   Flags.setNoInfs(true);
6853   Flags.setNoNaNs(true);
6854 
6855   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6856 
6857   EVT ResVT = Op.getValueType();
6858   EVT CmpVT = Op.getOperand(0).getValueType();
6859   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6860   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6861   SDLoc dl(Op);
6862 
6863   // If the RHS of the comparison is a 0.0, we don't need to do the
6864   // subtraction at all.
6865   SDValue Sel1;
6866   if (isFloatingPointZero(RHS))
6867     switch (CC) {
6868     default: break;       // SETUO etc aren't handled by fsel.
6869     case ISD::SETNE:
6870       std::swap(TV, FV);
6871       LLVM_FALLTHROUGH;
6872     case ISD::SETEQ:
6873       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6874         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6875       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6876       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6877         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6878       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6879                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6880     case ISD::SETULT:
6881     case ISD::SETLT:
6882       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6883       LLVM_FALLTHROUGH;
6884     case ISD::SETOGE:
6885     case ISD::SETGE:
6886       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6887         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6888       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6889     case ISD::SETUGT:
6890     case ISD::SETGT:
6891       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6892       LLVM_FALLTHROUGH;
6893     case ISD::SETOLE:
6894     case ISD::SETLE:
6895       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6896         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6897       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6898                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6899     }
6900 
6901   SDValue Cmp;
6902   switch (CC) {
6903   default: break;       // SETUO etc aren't handled by fsel.
6904   case ISD::SETNE:
6905     std::swap(TV, FV);
6906     LLVM_FALLTHROUGH;
6907   case ISD::SETEQ:
6908     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6909     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6910       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6911     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6912     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6913       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6914     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6915                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6916   case ISD::SETULT:
6917   case ISD::SETLT:
6918     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6919     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6920       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6921     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6922   case ISD::SETOGE:
6923   case ISD::SETGE:
6924     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6925     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6926       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6927     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6928   case ISD::SETUGT:
6929   case ISD::SETGT:
6930     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6931     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6932       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6933     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6934   case ISD::SETOLE:
6935   case ISD::SETLE:
6936     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6937     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6938       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6939     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6940   }
6941   return Op;
6942 }
6943 
6944 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6945                                                SelectionDAG &DAG,
6946                                                const SDLoc &dl) const {
6947   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6948   SDValue Src = Op.getOperand(0);
6949   if (Src.getValueType() == MVT::f32)
6950     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6951 
6952   SDValue Tmp;
6953   switch (Op.getSimpleValueType().SimpleTy) {
6954   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6955   case MVT::i32:
6956     Tmp = DAG.getNode(
6957         Op.getOpcode() == ISD::FP_TO_SINT
6958             ? PPCISD::FCTIWZ
6959             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6960         dl, MVT::f64, Src);
6961     break;
6962   case MVT::i64:
6963     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6964            "i64 FP_TO_UINT is supported only with FPCVT");
6965     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6966                                                         PPCISD::FCTIDUZ,
6967                       dl, MVT::f64, Src);
6968     break;
6969   }
6970 
6971   // Convert the FP value to an int value through memory.
6972   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6973     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6974   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6975   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6976   MachinePointerInfo MPI =
6977       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6978 
6979   // Emit a store to the stack slot.
6980   SDValue Chain;
6981   if (i32Stack) {
6982     MachineFunction &MF = DAG.getMachineFunction();
6983     MachineMemOperand *MMO =
6984       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6985     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6986     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6987               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6988   } else
6989     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6990 
6991   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6992   // add in a bias on big endian.
6993   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6994     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6995                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6996     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6997   }
6998 
6999   RLI.Chain = Chain;
7000   RLI.Ptr = FIPtr;
7001   RLI.MPI = MPI;
7002 }
7003 
7004 /// Custom lowers floating point to integer conversions to use
7005 /// the direct move instructions available in ISA 2.07 to avoid the
7006 /// need for load/store combinations.
7007 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7008                                                     SelectionDAG &DAG,
7009                                                     const SDLoc &dl) const {
7010   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7011   SDValue Src = Op.getOperand(0);
7012 
7013   if (Src.getValueType() == MVT::f32)
7014     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7015 
7016   SDValue Tmp;
7017   switch (Op.getSimpleValueType().SimpleTy) {
7018   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7019   case MVT::i32:
7020     Tmp = DAG.getNode(
7021         Op.getOpcode() == ISD::FP_TO_SINT
7022             ? PPCISD::FCTIWZ
7023             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7024         dl, MVT::f64, Src);
7025     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7026     break;
7027   case MVT::i64:
7028     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7029            "i64 FP_TO_UINT is supported only with FPCVT");
7030     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7031                                                         PPCISD::FCTIDUZ,
7032                       dl, MVT::f64, Src);
7033     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7034     break;
7035   }
7036   return Tmp;
7037 }
7038 
7039 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7040                                           const SDLoc &dl) const {
7041 
7042   // FP to INT conversions are legal for f128.
7043   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7044     return Op;
7045 
7046   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7047   // PPC (the libcall is not available).
7048   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7049     if (Op.getValueType() == MVT::i32) {
7050       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7051         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7052                                  MVT::f64, Op.getOperand(0),
7053                                  DAG.getIntPtrConstant(0, dl));
7054         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7055                                  MVT::f64, Op.getOperand(0),
7056                                  DAG.getIntPtrConstant(1, dl));
7057 
7058         // Add the two halves of the long double in round-to-zero mode.
7059         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7060 
7061         // Now use a smaller FP_TO_SINT.
7062         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7063       }
7064       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7065         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7066         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7067         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7068         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7069         // FIXME: generated code sucks.
7070         // TODO: Are there fast-math-flags to propagate to this FSUB?
7071         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7072                                    Op.getOperand(0), Tmp);
7073         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7074         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7075                            DAG.getConstant(0x80000000, dl, MVT::i32));
7076         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7077                                     Op.getOperand(0));
7078         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7079                                ISD::SETGE);
7080       }
7081     }
7082 
7083     return SDValue();
7084   }
7085 
7086   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7087     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7088 
7089   ReuseLoadInfo RLI;
7090   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7091 
7092   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7093                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7094 }
7095 
7096 // We're trying to insert a regular store, S, and then a load, L. If the
7097 // incoming value, O, is a load, we might just be able to have our load use the
7098 // address used by O. However, we don't know if anything else will store to
7099 // that address before we can load from it. To prevent this situation, we need
7100 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7101 // the same chain operand as O, we create a token factor from the chain results
7102 // of O and L, and we replace all uses of O's chain result with that token
7103 // factor (see spliceIntoChain below for this last part).
7104 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7105                                             ReuseLoadInfo &RLI,
7106                                             SelectionDAG &DAG,
7107                                             ISD::LoadExtType ET) const {
7108   SDLoc dl(Op);
7109   if (ET == ISD::NON_EXTLOAD &&
7110       (Op.getOpcode() == ISD::FP_TO_UINT ||
7111        Op.getOpcode() == ISD::FP_TO_SINT) &&
7112       isOperationLegalOrCustom(Op.getOpcode(),
7113                                Op.getOperand(0).getValueType())) {
7114 
7115     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7116     return true;
7117   }
7118 
7119   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7120   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7121       LD->isNonTemporal())
7122     return false;
7123   if (LD->getMemoryVT() != MemVT)
7124     return false;
7125 
7126   RLI.Ptr = LD->getBasePtr();
7127   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7128     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7129            "Non-pre-inc AM on PPC?");
7130     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7131                           LD->getOffset());
7132   }
7133 
7134   RLI.Chain = LD->getChain();
7135   RLI.MPI = LD->getPointerInfo();
7136   RLI.IsDereferenceable = LD->isDereferenceable();
7137   RLI.IsInvariant = LD->isInvariant();
7138   RLI.Alignment = LD->getAlignment();
7139   RLI.AAInfo = LD->getAAInfo();
7140   RLI.Ranges = LD->getRanges();
7141 
7142   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7143   return true;
7144 }
7145 
7146 // Given the head of the old chain, ResChain, insert a token factor containing
7147 // it and NewResChain, and make users of ResChain now be users of that token
7148 // factor.
7149 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7150 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7151                                         SDValue NewResChain,
7152                                         SelectionDAG &DAG) const {
7153   if (!ResChain)
7154     return;
7155 
7156   SDLoc dl(NewResChain);
7157 
7158   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7159                            NewResChain, DAG.getUNDEF(MVT::Other));
7160   assert(TF.getNode() != NewResChain.getNode() &&
7161          "A new TF really is required here");
7162 
7163   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7164   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7165 }
7166 
7167 /// Analyze profitability of direct move
7168 /// prefer float load to int load plus direct move
7169 /// when there is no integer use of int load
7170 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7171   SDNode *Origin = Op.getOperand(0).getNode();
7172   if (Origin->getOpcode() != ISD::LOAD)
7173     return true;
7174 
7175   // If there is no LXSIBZX/LXSIHZX, like Power8,
7176   // prefer direct move if the memory size is 1 or 2 bytes.
7177   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7178   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7179     return true;
7180 
7181   for (SDNode::use_iterator UI = Origin->use_begin(),
7182                             UE = Origin->use_end();
7183        UI != UE; ++UI) {
7184 
7185     // Only look at the users of the loaded value.
7186     if (UI.getUse().get().getResNo() != 0)
7187       continue;
7188 
7189     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7190         UI->getOpcode() != ISD::UINT_TO_FP)
7191       return true;
7192   }
7193 
7194   return false;
7195 }
7196 
7197 /// Custom lowers integer to floating point conversions to use
7198 /// the direct move instructions available in ISA 2.07 to avoid the
7199 /// need for load/store combinations.
7200 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7201                                                     SelectionDAG &DAG,
7202                                                     const SDLoc &dl) const {
7203   assert((Op.getValueType() == MVT::f32 ||
7204           Op.getValueType() == MVT::f64) &&
7205          "Invalid floating point type as target of conversion");
7206   assert(Subtarget.hasFPCVT() &&
7207          "Int to FP conversions with direct moves require FPCVT");
7208   SDValue FP;
7209   SDValue Src = Op.getOperand(0);
7210   bool SinglePrec = Op.getValueType() == MVT::f32;
7211   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7212   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7213   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7214                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7215 
7216   if (WordInt) {
7217     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7218                      dl, MVT::f64, Src);
7219     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7220   }
7221   else {
7222     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7223     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7224   }
7225 
7226   return FP;
7227 }
7228 
7229 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7230                                           SelectionDAG &DAG) const {
7231   SDLoc dl(Op);
7232 
7233   // Conversions to f128 are legal.
7234   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7235     return Op;
7236 
7237   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7238     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7239       return SDValue();
7240 
7241     SDValue Value = Op.getOperand(0);
7242     // The values are now known to be -1 (false) or 1 (true). To convert this
7243     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7244     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7245     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7246 
7247     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7248 
7249     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7250 
7251     if (Op.getValueType() != MVT::v4f64)
7252       Value = DAG.getNode(ISD::FP_ROUND, dl,
7253                           Op.getValueType(), Value,
7254                           DAG.getIntPtrConstant(1, dl));
7255     return Value;
7256   }
7257 
7258   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7259   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7260     return SDValue();
7261 
7262   if (Op.getOperand(0).getValueType() == MVT::i1)
7263     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7264                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7265                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7266 
7267   // If we have direct moves, we can do all the conversion, skip the store/load
7268   // however, without FPCVT we can't do most conversions.
7269   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7270       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7271     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7272 
7273   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7274          "UINT_TO_FP is supported only with FPCVT");
7275 
7276   // If we have FCFIDS, then use it when converting to single-precision.
7277   // Otherwise, convert to double-precision and then round.
7278   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7279                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7280                                                             : PPCISD::FCFIDS)
7281                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7282                                                             : PPCISD::FCFID);
7283   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7284                   ? MVT::f32
7285                   : MVT::f64;
7286 
7287   if (Op.getOperand(0).getValueType() == MVT::i64) {
7288     SDValue SINT = Op.getOperand(0);
7289     // When converting to single-precision, we actually need to convert
7290     // to double-precision first and then round to single-precision.
7291     // To avoid double-rounding effects during that operation, we have
7292     // to prepare the input operand.  Bits that might be truncated when
7293     // converting to double-precision are replaced by a bit that won't
7294     // be lost at this stage, but is below the single-precision rounding
7295     // position.
7296     //
7297     // However, if -enable-unsafe-fp-math is in effect, accept double
7298     // rounding to avoid the extra overhead.
7299     if (Op.getValueType() == MVT::f32 &&
7300         !Subtarget.hasFPCVT() &&
7301         !DAG.getTarget().Options.UnsafeFPMath) {
7302 
7303       // Twiddle input to make sure the low 11 bits are zero.  (If this
7304       // is the case, we are guaranteed the value will fit into the 53 bit
7305       // mantissa of an IEEE double-precision value without rounding.)
7306       // If any of those low 11 bits were not zero originally, make sure
7307       // bit 12 (value 2048) is set instead, so that the final rounding
7308       // to single-precision gets the correct result.
7309       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7310                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7311       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7312                           Round, DAG.getConstant(2047, dl, MVT::i64));
7313       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7314       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7315                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7316 
7317       // However, we cannot use that value unconditionally: if the magnitude
7318       // of the input value is small, the bit-twiddling we did above might
7319       // end up visibly changing the output.  Fortunately, in that case, we
7320       // don't need to twiddle bits since the original input will convert
7321       // exactly to double-precision floating-point already.  Therefore,
7322       // construct a conditional to use the original value if the top 11
7323       // bits are all sign-bit copies, and use the rounded value computed
7324       // above otherwise.
7325       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7326                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7327       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7328                          Cond, DAG.getConstant(1, dl, MVT::i64));
7329       Cond = DAG.getSetCC(dl, MVT::i32,
7330                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7331 
7332       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7333     }
7334 
7335     ReuseLoadInfo RLI;
7336     SDValue Bits;
7337 
7338     MachineFunction &MF = DAG.getMachineFunction();
7339     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7340       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7341                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7342       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7343     } else if (Subtarget.hasLFIWAX() &&
7344                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7345       MachineMemOperand *MMO =
7346         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7347                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7348       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7349       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7350                                      DAG.getVTList(MVT::f64, MVT::Other),
7351                                      Ops, MVT::i32, MMO);
7352       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7353     } else if (Subtarget.hasFPCVT() &&
7354                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7355       MachineMemOperand *MMO =
7356         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7357                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7358       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7359       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7360                                      DAG.getVTList(MVT::f64, MVT::Other),
7361                                      Ops, MVT::i32, MMO);
7362       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7363     } else if (((Subtarget.hasLFIWAX() &&
7364                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7365                 (Subtarget.hasFPCVT() &&
7366                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7367                SINT.getOperand(0).getValueType() == MVT::i32) {
7368       MachineFrameInfo &MFI = MF.getFrameInfo();
7369       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7370 
7371       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7372       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7373 
7374       SDValue Store =
7375           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7376                        MachinePointerInfo::getFixedStack(
7377                            DAG.getMachineFunction(), FrameIdx));
7378 
7379       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7380              "Expected an i32 store");
7381 
7382       RLI.Ptr = FIdx;
7383       RLI.Chain = Store;
7384       RLI.MPI =
7385           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7386       RLI.Alignment = 4;
7387 
7388       MachineMemOperand *MMO =
7389         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7390                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7391       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7392       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7393                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7394                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7395                                      Ops, MVT::i32, MMO);
7396     } else
7397       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7398 
7399     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7400 
7401     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7402       FP = DAG.getNode(ISD::FP_ROUND, dl,
7403                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7404     return FP;
7405   }
7406 
7407   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7408          "Unhandled INT_TO_FP type in custom expander!");
7409   // Since we only generate this in 64-bit mode, we can take advantage of
7410   // 64-bit registers.  In particular, sign extend the input value into the
7411   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7412   // then lfd it and fcfid it.
7413   MachineFunction &MF = DAG.getMachineFunction();
7414   MachineFrameInfo &MFI = MF.getFrameInfo();
7415   EVT PtrVT = getPointerTy(MF.getDataLayout());
7416 
7417   SDValue Ld;
7418   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7419     ReuseLoadInfo RLI;
7420     bool ReusingLoad;
7421     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7422                                             DAG))) {
7423       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7424       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7425 
7426       SDValue Store =
7427           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7428                        MachinePointerInfo::getFixedStack(
7429                            DAG.getMachineFunction(), FrameIdx));
7430 
7431       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7432              "Expected an i32 store");
7433 
7434       RLI.Ptr = FIdx;
7435       RLI.Chain = Store;
7436       RLI.MPI =
7437           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7438       RLI.Alignment = 4;
7439     }
7440 
7441     MachineMemOperand *MMO =
7442       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7443                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7444     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7445     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7446                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7447                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7448                                  Ops, MVT::i32, MMO);
7449     if (ReusingLoad)
7450       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7451   } else {
7452     assert(Subtarget.isPPC64() &&
7453            "i32->FP without LFIWAX supported only on PPC64");
7454 
7455     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7456     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7457 
7458     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7459                                 Op.getOperand(0));
7460 
7461     // STD the extended value into the stack slot.
7462     SDValue Store = DAG.getStore(
7463         DAG.getEntryNode(), dl, Ext64, FIdx,
7464         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7465 
7466     // Load the value as a double.
7467     Ld = DAG.getLoad(
7468         MVT::f64, dl, Store, FIdx,
7469         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7470   }
7471 
7472   // FCFID it and return it.
7473   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7474   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7475     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7476                      DAG.getIntPtrConstant(0, dl));
7477   return FP;
7478 }
7479 
7480 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7481                                             SelectionDAG &DAG) const {
7482   SDLoc dl(Op);
7483   /*
7484    The rounding mode is in bits 30:31 of FPSR, and has the following
7485    settings:
7486      00 Round to nearest
7487      01 Round to 0
7488      10 Round to +inf
7489      11 Round to -inf
7490 
7491   FLT_ROUNDS, on the other hand, expects the following:
7492     -1 Undefined
7493      0 Round to 0
7494      1 Round to nearest
7495      2 Round to +inf
7496      3 Round to -inf
7497 
7498   To perform the conversion, we do:
7499     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7500   */
7501 
7502   MachineFunction &MF = DAG.getMachineFunction();
7503   EVT VT = Op.getValueType();
7504   EVT PtrVT = getPointerTy(MF.getDataLayout());
7505 
7506   // Save FP Control Word to register
7507   EVT NodeTys[] = {
7508     MVT::f64,    // return register
7509     MVT::Glue    // unused in this context
7510   };
7511   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7512 
7513   // Save FP register to stack slot
7514   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7515   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7516   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7517                                MachinePointerInfo());
7518 
7519   // Load FP Control Word from low 32 bits of stack slot.
7520   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7521   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7522   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7523 
7524   // Transform as necessary
7525   SDValue CWD1 =
7526     DAG.getNode(ISD::AND, dl, MVT::i32,
7527                 CWD, DAG.getConstant(3, dl, MVT::i32));
7528   SDValue CWD2 =
7529     DAG.getNode(ISD::SRL, dl, MVT::i32,
7530                 DAG.getNode(ISD::AND, dl, MVT::i32,
7531                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7532                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7533                             DAG.getConstant(3, dl, MVT::i32)),
7534                 DAG.getConstant(1, dl, MVT::i32));
7535 
7536   SDValue RetVal =
7537     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7538 
7539   return DAG.getNode((VT.getSizeInBits() < 16 ?
7540                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7541 }
7542 
7543 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7544   EVT VT = Op.getValueType();
7545   unsigned BitWidth = VT.getSizeInBits();
7546   SDLoc dl(Op);
7547   assert(Op.getNumOperands() == 3 &&
7548          VT == Op.getOperand(1).getValueType() &&
7549          "Unexpected SHL!");
7550 
7551   // Expand into a bunch of logical ops.  Note that these ops
7552   // depend on the PPC behavior for oversized shift amounts.
7553   SDValue Lo = Op.getOperand(0);
7554   SDValue Hi = Op.getOperand(1);
7555   SDValue Amt = Op.getOperand(2);
7556   EVT AmtVT = Amt.getValueType();
7557 
7558   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7559                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7560   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7561   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7562   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7563   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7564                              DAG.getConstant(-BitWidth, dl, AmtVT));
7565   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7566   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7567   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7568   SDValue OutOps[] = { OutLo, OutHi };
7569   return DAG.getMergeValues(OutOps, dl);
7570 }
7571 
7572 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7573   EVT VT = Op.getValueType();
7574   SDLoc dl(Op);
7575   unsigned BitWidth = VT.getSizeInBits();
7576   assert(Op.getNumOperands() == 3 &&
7577          VT == Op.getOperand(1).getValueType() &&
7578          "Unexpected SRL!");
7579 
7580   // Expand into a bunch of logical ops.  Note that these ops
7581   // depend on the PPC behavior for oversized shift amounts.
7582   SDValue Lo = Op.getOperand(0);
7583   SDValue Hi = Op.getOperand(1);
7584   SDValue Amt = Op.getOperand(2);
7585   EVT AmtVT = Amt.getValueType();
7586 
7587   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7588                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7589   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7590   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7591   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7592   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7593                              DAG.getConstant(-BitWidth, dl, AmtVT));
7594   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7595   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7596   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7597   SDValue OutOps[] = { OutLo, OutHi };
7598   return DAG.getMergeValues(OutOps, dl);
7599 }
7600 
7601 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7602   SDLoc dl(Op);
7603   EVT VT = Op.getValueType();
7604   unsigned BitWidth = VT.getSizeInBits();
7605   assert(Op.getNumOperands() == 3 &&
7606          VT == Op.getOperand(1).getValueType() &&
7607          "Unexpected SRA!");
7608 
7609   // Expand into a bunch of logical ops, followed by a select_cc.
7610   SDValue Lo = Op.getOperand(0);
7611   SDValue Hi = Op.getOperand(1);
7612   SDValue Amt = Op.getOperand(2);
7613   EVT AmtVT = Amt.getValueType();
7614 
7615   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7616                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7617   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7618   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7619   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7620   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7621                              DAG.getConstant(-BitWidth, dl, AmtVT));
7622   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7623   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7624   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7625                                   Tmp4, Tmp6, ISD::SETLE);
7626   SDValue OutOps[] = { OutLo, OutHi };
7627   return DAG.getMergeValues(OutOps, dl);
7628 }
7629 
7630 //===----------------------------------------------------------------------===//
7631 // Vector related lowering.
7632 //
7633 
7634 /// BuildSplatI - Build a canonical splati of Val with an element size of
7635 /// SplatSize.  Cast the result to VT.
7636 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7637                            SelectionDAG &DAG, const SDLoc &dl) {
7638   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7639 
7640   static const MVT VTys[] = { // canonical VT to use for each size.
7641     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7642   };
7643 
7644   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7645 
7646   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7647   if (Val == -1)
7648     SplatSize = 1;
7649 
7650   EVT CanonicalVT = VTys[SplatSize-1];
7651 
7652   // Build a canonical splat for this value.
7653   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7654 }
7655 
7656 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7657 /// specified intrinsic ID.
7658 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7659                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7660   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7661   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7662                      DAG.getConstant(IID, dl, MVT::i32), Op);
7663 }
7664 
7665 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7666 /// specified intrinsic ID.
7667 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7668                                 SelectionDAG &DAG, const SDLoc &dl,
7669                                 EVT DestVT = MVT::Other) {
7670   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7671   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7672                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7673 }
7674 
7675 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7676 /// specified intrinsic ID.
7677 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7678                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7679                                 EVT DestVT = MVT::Other) {
7680   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7681   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7682                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7683 }
7684 
7685 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7686 /// amount.  The result has the specified value type.
7687 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7688                            SelectionDAG &DAG, const SDLoc &dl) {
7689   // Force LHS/RHS to be the right type.
7690   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7691   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7692 
7693   int Ops[16];
7694   for (unsigned i = 0; i != 16; ++i)
7695     Ops[i] = i + Amt;
7696   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7697   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7698 }
7699 
7700 /// Do we have an efficient pattern in a .td file for this node?
7701 ///
7702 /// \param V - pointer to the BuildVectorSDNode being matched
7703 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7704 ///
7705 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7706 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7707 /// the opposite is true (expansion is beneficial) are:
7708 /// - The node builds a vector out of integers that are not 32 or 64-bits
7709 /// - The node builds a vector out of constants
7710 /// - The node is a "load-and-splat"
7711 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7712 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7713                                             bool HasDirectMove,
7714                                             bool HasP8Vector) {
7715   EVT VecVT = V->getValueType(0);
7716   bool RightType = VecVT == MVT::v2f64 ||
7717     (HasP8Vector && VecVT == MVT::v4f32) ||
7718     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7719   if (!RightType)
7720     return false;
7721 
7722   bool IsSplat = true;
7723   bool IsLoad = false;
7724   SDValue Op0 = V->getOperand(0);
7725 
7726   // This function is called in a block that confirms the node is not a constant
7727   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7728   // different constants.
7729   if (V->isConstant())
7730     return false;
7731   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7732     if (V->getOperand(i).isUndef())
7733       return false;
7734     // We want to expand nodes that represent load-and-splat even if the
7735     // loaded value is a floating point truncation or conversion to int.
7736     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7737         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7738          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7739         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7740          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7741         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7742          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7743       IsLoad = true;
7744     // If the operands are different or the input is not a load and has more
7745     // uses than just this BV node, then it isn't a splat.
7746     if (V->getOperand(i) != Op0 ||
7747         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7748       IsSplat = false;
7749   }
7750   return !(IsSplat && IsLoad);
7751 }
7752 
7753 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
7754 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
7755 
7756   SDLoc dl(Op);
7757   SDValue Op0 = Op->getOperand(0);
7758 
7759   if (!EnableQuadPrecision ||
7760       (Op.getValueType() != MVT::f128 ) ||
7761       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
7762       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
7763       (Op0.getOperand(1).getValueType() != MVT::i64))
7764     return SDValue();
7765 
7766   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
7767                      Op0.getOperand(1));
7768 }
7769 
7770 // If this is a case we can't handle, return null and let the default
7771 // expansion code take care of it.  If we CAN select this case, and if it
7772 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7773 // this case more efficiently than a constant pool load, lower it to the
7774 // sequence of ops that should be used.
7775 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7776                                              SelectionDAG &DAG) const {
7777   SDLoc dl(Op);
7778   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7779   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7780 
7781   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7782     // We first build an i32 vector, load it into a QPX register,
7783     // then convert it to a floating-point vector and compare it
7784     // to a zero vector to get the boolean result.
7785     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7786     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7787     MachinePointerInfo PtrInfo =
7788         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7789     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7790     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7791 
7792     assert(BVN->getNumOperands() == 4 &&
7793       "BUILD_VECTOR for v4i1 does not have 4 operands");
7794 
7795     bool IsConst = true;
7796     for (unsigned i = 0; i < 4; ++i) {
7797       if (BVN->getOperand(i).isUndef()) continue;
7798       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7799         IsConst = false;
7800         break;
7801       }
7802     }
7803 
7804     if (IsConst) {
7805       Constant *One =
7806         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7807       Constant *NegOne =
7808         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7809 
7810       Constant *CV[4];
7811       for (unsigned i = 0; i < 4; ++i) {
7812         if (BVN->getOperand(i).isUndef())
7813           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7814         else if (isNullConstant(BVN->getOperand(i)))
7815           CV[i] = NegOne;
7816         else
7817           CV[i] = One;
7818       }
7819 
7820       Constant *CP = ConstantVector::get(CV);
7821       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7822                                           16 /* alignment */);
7823 
7824       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7825       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7826       return DAG.getMemIntrinsicNode(
7827           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7828           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7829     }
7830 
7831     SmallVector<SDValue, 4> Stores;
7832     for (unsigned i = 0; i < 4; ++i) {
7833       if (BVN->getOperand(i).isUndef()) continue;
7834 
7835       unsigned Offset = 4*i;
7836       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7837       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7838 
7839       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7840       if (StoreSize > 4) {
7841         Stores.push_back(
7842             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7843                               PtrInfo.getWithOffset(Offset), MVT::i32));
7844       } else {
7845         SDValue StoreValue = BVN->getOperand(i);
7846         if (StoreSize < 4)
7847           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7848 
7849         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7850                                       PtrInfo.getWithOffset(Offset)));
7851       }
7852     }
7853 
7854     SDValue StoreChain;
7855     if (!Stores.empty())
7856       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7857     else
7858       StoreChain = DAG.getEntryNode();
7859 
7860     // Now load from v4i32 into the QPX register; this will extend it to
7861     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7862     // is typed as v4f64 because the QPX register integer states are not
7863     // explicitly represented.
7864 
7865     SDValue Ops[] = {StoreChain,
7866                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7867                      FIdx};
7868     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7869 
7870     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7871       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7872     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7873       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7874       LoadedVect);
7875 
7876     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7877 
7878     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7879   }
7880 
7881   // All other QPX vectors are handled by generic code.
7882   if (Subtarget.hasQPX())
7883     return SDValue();
7884 
7885   // Check if this is a splat of a constant value.
7886   APInt APSplatBits, APSplatUndef;
7887   unsigned SplatBitSize;
7888   bool HasAnyUndefs;
7889   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7890                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7891       SplatBitSize > 32) {
7892     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7893     // lowered to VSX instructions under certain conditions.
7894     // Without VSX, there is no pattern more efficient than expanding the node.
7895     if (Subtarget.hasVSX() &&
7896         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7897                                         Subtarget.hasP8Vector()))
7898       return Op;
7899     return SDValue();
7900   }
7901 
7902   unsigned SplatBits = APSplatBits.getZExtValue();
7903   unsigned SplatUndef = APSplatUndef.getZExtValue();
7904   unsigned SplatSize = SplatBitSize / 8;
7905 
7906   // First, handle single instruction cases.
7907 
7908   // All zeros?
7909   if (SplatBits == 0) {
7910     // Canonicalize all zero vectors to be v4i32.
7911     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7912       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7913       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7914     }
7915     return Op;
7916   }
7917 
7918   // We have XXSPLTIB for constant splats one byte wide
7919   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7920     // This is a splat of 1-byte elements with some elements potentially undef.
7921     // Rather than trying to match undef in the SDAG patterns, ensure that all
7922     // elements are the same constant.
7923     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7924       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7925                                                        dl, MVT::i32));
7926       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7927       if (Op.getValueType() != MVT::v16i8)
7928         return DAG.getBitcast(Op.getValueType(), NewBV);
7929       return NewBV;
7930     }
7931 
7932     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7933     // detect that constant splats like v8i16: 0xABAB are really just splats
7934     // of a 1-byte constant. In this case, we need to convert the node to a
7935     // splat of v16i8 and a bitcast.
7936     if (Op.getValueType() != MVT::v16i8)
7937       return DAG.getBitcast(Op.getValueType(),
7938                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
7939 
7940     return Op;
7941   }
7942 
7943   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7944   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7945                     (32-SplatBitSize));
7946   if (SextVal >= -16 && SextVal <= 15)
7947     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7948 
7949   // Two instruction sequences.
7950 
7951   // If this value is in the range [-32,30] and is even, use:
7952   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7953   // If this value is in the range [17,31] and is odd, use:
7954   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7955   // If this value is in the range [-31,-17] and is odd, use:
7956   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7957   // Note the last two are three-instruction sequences.
7958   if (SextVal >= -32 && SextVal <= 31) {
7959     // To avoid having these optimizations undone by constant folding,
7960     // we convert to a pseudo that will be expanded later into one of
7961     // the above forms.
7962     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7963     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7964               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7965     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7966     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7967     if (VT == Op.getValueType())
7968       return RetVal;
7969     else
7970       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7971   }
7972 
7973   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7974   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7975   // for fneg/fabs.
7976   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7977     // Make -1 and vspltisw -1:
7978     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7979 
7980     // Make the VSLW intrinsic, computing 0x8000_0000.
7981     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7982                                    OnesV, DAG, dl);
7983 
7984     // xor by OnesV to invert it.
7985     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7986     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7987   }
7988 
7989   // Check to see if this is a wide variety of vsplti*, binop self cases.
7990   static const signed char SplatCsts[] = {
7991     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7992     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7993   };
7994 
7995   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7996     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7997     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7998     int i = SplatCsts[idx];
7999 
8000     // Figure out what shift amount will be used by altivec if shifted by i in
8001     // this splat size.
8002     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8003 
8004     // vsplti + shl self.
8005     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8006       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8007       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8008         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8009         Intrinsic::ppc_altivec_vslw
8010       };
8011       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8012       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8013     }
8014 
8015     // vsplti + srl self.
8016     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8017       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8018       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8019         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8020         Intrinsic::ppc_altivec_vsrw
8021       };
8022       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8023       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8024     }
8025 
8026     // vsplti + sra self.
8027     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8028       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8029       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8030         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8031         Intrinsic::ppc_altivec_vsraw
8032       };
8033       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8034       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8035     }
8036 
8037     // vsplti + rol self.
8038     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8039                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8040       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8041       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8042         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8043         Intrinsic::ppc_altivec_vrlw
8044       };
8045       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8046       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8047     }
8048 
8049     // t = vsplti c, result = vsldoi t, t, 1
8050     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8051       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8052       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8053       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8054     }
8055     // t = vsplti c, result = vsldoi t, t, 2
8056     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8057       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8058       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8059       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8060     }
8061     // t = vsplti c, result = vsldoi t, t, 3
8062     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8063       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8064       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8065       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8066     }
8067   }
8068 
8069   return SDValue();
8070 }
8071 
8072 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8073 /// the specified operations to build the shuffle.
8074 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8075                                       SDValue RHS, SelectionDAG &DAG,
8076                                       const SDLoc &dl) {
8077   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8078   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8079   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8080 
8081   enum {
8082     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8083     OP_VMRGHW,
8084     OP_VMRGLW,
8085     OP_VSPLTISW0,
8086     OP_VSPLTISW1,
8087     OP_VSPLTISW2,
8088     OP_VSPLTISW3,
8089     OP_VSLDOI4,
8090     OP_VSLDOI8,
8091     OP_VSLDOI12
8092   };
8093 
8094   if (OpNum == OP_COPY) {
8095     if (LHSID == (1*9+2)*9+3) return LHS;
8096     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8097     return RHS;
8098   }
8099 
8100   SDValue OpLHS, OpRHS;
8101   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8102   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8103 
8104   int ShufIdxs[16];
8105   switch (OpNum) {
8106   default: llvm_unreachable("Unknown i32 permute!");
8107   case OP_VMRGHW:
8108     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8109     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8110     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8111     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8112     break;
8113   case OP_VMRGLW:
8114     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8115     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8116     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8117     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8118     break;
8119   case OP_VSPLTISW0:
8120     for (unsigned i = 0; i != 16; ++i)
8121       ShufIdxs[i] = (i&3)+0;
8122     break;
8123   case OP_VSPLTISW1:
8124     for (unsigned i = 0; i != 16; ++i)
8125       ShufIdxs[i] = (i&3)+4;
8126     break;
8127   case OP_VSPLTISW2:
8128     for (unsigned i = 0; i != 16; ++i)
8129       ShufIdxs[i] = (i&3)+8;
8130     break;
8131   case OP_VSPLTISW3:
8132     for (unsigned i = 0; i != 16; ++i)
8133       ShufIdxs[i] = (i&3)+12;
8134     break;
8135   case OP_VSLDOI4:
8136     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8137   case OP_VSLDOI8:
8138     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8139   case OP_VSLDOI12:
8140     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8141   }
8142   EVT VT = OpLHS.getValueType();
8143   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8144   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8145   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8146   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8147 }
8148 
8149 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8150 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8151 /// SDValue.
8152 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8153                                            SelectionDAG &DAG) const {
8154   const unsigned BytesInVector = 16;
8155   bool IsLE = Subtarget.isLittleEndian();
8156   SDLoc dl(N);
8157   SDValue V1 = N->getOperand(0);
8158   SDValue V2 = N->getOperand(1);
8159   unsigned ShiftElts = 0, InsertAtByte = 0;
8160   bool Swap = false;
8161 
8162   // Shifts required to get the byte we want at element 7.
8163   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8164                                    0, 15, 14, 13, 12, 11, 10, 9};
8165   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8166                                 1, 2,  3,  4,  5,  6,  7,  8};
8167 
8168   ArrayRef<int> Mask = N->getMask();
8169   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8170 
8171   // For each mask element, find out if we're just inserting something
8172   // from V2 into V1 or vice versa.
8173   // Possible permutations inserting an element from V2 into V1:
8174   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8175   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8176   //   ...
8177   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8178   // Inserting from V1 into V2 will be similar, except mask range will be
8179   // [16,31].
8180 
8181   bool FoundCandidate = false;
8182   // If both vector operands for the shuffle are the same vector, the mask
8183   // will contain only elements from the first one and the second one will be
8184   // undef.
8185   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8186   // Go through the mask of half-words to find an element that's being moved
8187   // from one vector to the other.
8188   for (unsigned i = 0; i < BytesInVector; ++i) {
8189     unsigned CurrentElement = Mask[i];
8190     // If 2nd operand is undefined, we should only look for element 7 in the
8191     // Mask.
8192     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8193       continue;
8194 
8195     bool OtherElementsInOrder = true;
8196     // Examine the other elements in the Mask to see if they're in original
8197     // order.
8198     for (unsigned j = 0; j < BytesInVector; ++j) {
8199       if (j == i)
8200         continue;
8201       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8202       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8203       // in which we always assume we're always picking from the 1st operand.
8204       int MaskOffset =
8205           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8206       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8207         OtherElementsInOrder = false;
8208         break;
8209       }
8210     }
8211     // If other elements are in original order, we record the number of shifts
8212     // we need to get the element we want into element 7. Also record which byte
8213     // in the vector we should insert into.
8214     if (OtherElementsInOrder) {
8215       // If 2nd operand is undefined, we assume no shifts and no swapping.
8216       if (V2.isUndef()) {
8217         ShiftElts = 0;
8218         Swap = false;
8219       } else {
8220         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8221         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8222                          : BigEndianShifts[CurrentElement & 0xF];
8223         Swap = CurrentElement < BytesInVector;
8224       }
8225       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8226       FoundCandidate = true;
8227       break;
8228     }
8229   }
8230 
8231   if (!FoundCandidate)
8232     return SDValue();
8233 
8234   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8235   // optionally with VECSHL if shift is required.
8236   if (Swap)
8237     std::swap(V1, V2);
8238   if (V2.isUndef())
8239     V2 = V1;
8240   if (ShiftElts) {
8241     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8242                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8243     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8244                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8245   }
8246   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8247                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8248 }
8249 
8250 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8251 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8252 /// SDValue.
8253 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8254                                            SelectionDAG &DAG) const {
8255   const unsigned NumHalfWords = 8;
8256   const unsigned BytesInVector = NumHalfWords * 2;
8257   // Check that the shuffle is on half-words.
8258   if (!isNByteElemShuffleMask(N, 2, 1))
8259     return SDValue();
8260 
8261   bool IsLE = Subtarget.isLittleEndian();
8262   SDLoc dl(N);
8263   SDValue V1 = N->getOperand(0);
8264   SDValue V2 = N->getOperand(1);
8265   unsigned ShiftElts = 0, InsertAtByte = 0;
8266   bool Swap = false;
8267 
8268   // Shifts required to get the half-word we want at element 3.
8269   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8270   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8271 
8272   uint32_t Mask = 0;
8273   uint32_t OriginalOrderLow = 0x1234567;
8274   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8275   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8276   // 32-bit space, only need 4-bit nibbles per element.
8277   for (unsigned i = 0; i < NumHalfWords; ++i) {
8278     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8279     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8280   }
8281 
8282   // For each mask element, find out if we're just inserting something
8283   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8284   // from V2 into V1:
8285   //   X, 1, 2, 3, 4, 5, 6, 7
8286   //   0, X, 2, 3, 4, 5, 6, 7
8287   //   0, 1, X, 3, 4, 5, 6, 7
8288   //   0, 1, 2, X, 4, 5, 6, 7
8289   //   0, 1, 2, 3, X, 5, 6, 7
8290   //   0, 1, 2, 3, 4, X, 6, 7
8291   //   0, 1, 2, 3, 4, 5, X, 7
8292   //   0, 1, 2, 3, 4, 5, 6, X
8293   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8294 
8295   bool FoundCandidate = false;
8296   // Go through the mask of half-words to find an element that's being moved
8297   // from one vector to the other.
8298   for (unsigned i = 0; i < NumHalfWords; ++i) {
8299     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8300     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8301     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8302     uint32_t TargetOrder = 0x0;
8303 
8304     // If both vector operands for the shuffle are the same vector, the mask
8305     // will contain only elements from the first one and the second one will be
8306     // undef.
8307     if (V2.isUndef()) {
8308       ShiftElts = 0;
8309       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8310       TargetOrder = OriginalOrderLow;
8311       Swap = false;
8312       // Skip if not the correct element or mask of other elements don't equal
8313       // to our expected order.
8314       if (MaskOneElt == VINSERTHSrcElem &&
8315           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8316         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8317         FoundCandidate = true;
8318         break;
8319       }
8320     } else { // If both operands are defined.
8321       // Target order is [8,15] if the current mask is between [0,7].
8322       TargetOrder =
8323           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8324       // Skip if mask of other elements don't equal our expected order.
8325       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8326         // We only need the last 3 bits for the number of shifts.
8327         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8328                          : BigEndianShifts[MaskOneElt & 0x7];
8329         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8330         Swap = MaskOneElt < NumHalfWords;
8331         FoundCandidate = true;
8332         break;
8333       }
8334     }
8335   }
8336 
8337   if (!FoundCandidate)
8338     return SDValue();
8339 
8340   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8341   // optionally with VECSHL if shift is required.
8342   if (Swap)
8343     std::swap(V1, V2);
8344   if (V2.isUndef())
8345     V2 = V1;
8346   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8347   if (ShiftElts) {
8348     // Double ShiftElts because we're left shifting on v16i8 type.
8349     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8350                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8351     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8352     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8353                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8354     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8355   }
8356   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8357   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8358                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8359   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8360 }
8361 
8362 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8363 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8364 /// return the code it can be lowered into.  Worst case, it can always be
8365 /// lowered into a vperm.
8366 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8367                                                SelectionDAG &DAG) const {
8368   SDLoc dl(Op);
8369   SDValue V1 = Op.getOperand(0);
8370   SDValue V2 = Op.getOperand(1);
8371   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8372   EVT VT = Op.getValueType();
8373   bool isLittleEndian = Subtarget.isLittleEndian();
8374 
8375   unsigned ShiftElts, InsertAtByte;
8376   bool Swap = false;
8377   if (Subtarget.hasP9Vector() &&
8378       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8379                            isLittleEndian)) {
8380     if (Swap)
8381       std::swap(V1, V2);
8382     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8383     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8384     if (ShiftElts) {
8385       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8386                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8387       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8388                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8389       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8390     }
8391     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8392                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8393     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8394   }
8395 
8396   if (Subtarget.hasP9Altivec()) {
8397     SDValue NewISDNode;
8398     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8399       return NewISDNode;
8400 
8401     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8402       return NewISDNode;
8403   }
8404 
8405   if (Subtarget.hasVSX() &&
8406       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8407     if (Swap)
8408       std::swap(V1, V2);
8409     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8410     SDValue Conv2 =
8411         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8412 
8413     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8414                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8415     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8416   }
8417 
8418   if (Subtarget.hasVSX() &&
8419     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8420     if (Swap)
8421       std::swap(V1, V2);
8422     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8423     SDValue Conv2 =
8424         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8425 
8426     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8427                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8428     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8429   }
8430 
8431   if (Subtarget.hasP9Vector()) {
8432      if (PPC::isXXBRHShuffleMask(SVOp)) {
8433       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8434       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8435       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8436     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8437       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8438       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8439       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8440     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8441       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8442       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8443       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8444     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8445       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8446       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8447       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8448     }
8449   }
8450 
8451   if (Subtarget.hasVSX()) {
8452     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8453       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8454 
8455       // If the source for the shuffle is a scalar_to_vector that came from a
8456       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
8457       if (Subtarget.hasP9Vector() &&
8458           ((isLittleEndian && SplatIdx == 3) ||
8459            (!isLittleEndian && SplatIdx == 0))) {
8460         SDValue Src = V1.getOperand(0);
8461         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8462             Src.getOperand(0).getOpcode() == ISD::LOAD &&
8463             Src.getOperand(0).hasOneUse())
8464           return V1;
8465       }
8466       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8467       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8468                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8469       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8470     }
8471 
8472     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8473     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8474       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8475       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8476       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8477     }
8478   }
8479 
8480   if (Subtarget.hasQPX()) {
8481     if (VT.getVectorNumElements() != 4)
8482       return SDValue();
8483 
8484     if (V2.isUndef()) V2 = V1;
8485 
8486     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8487     if (AlignIdx != -1) {
8488       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8489                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8490     } else if (SVOp->isSplat()) {
8491       int SplatIdx = SVOp->getSplatIndex();
8492       if (SplatIdx >= 4) {
8493         std::swap(V1, V2);
8494         SplatIdx -= 4;
8495       }
8496 
8497       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8498                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8499     }
8500 
8501     // Lower this into a qvgpci/qvfperm pair.
8502 
8503     // Compute the qvgpci literal
8504     unsigned idx = 0;
8505     for (unsigned i = 0; i < 4; ++i) {
8506       int m = SVOp->getMaskElt(i);
8507       unsigned mm = m >= 0 ? (unsigned) m : i;
8508       idx |= mm << (3-i)*3;
8509     }
8510 
8511     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8512                              DAG.getConstant(idx, dl, MVT::i32));
8513     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8514   }
8515 
8516   // Cases that are handled by instructions that take permute immediates
8517   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8518   // selected by the instruction selector.
8519   if (V2.isUndef()) {
8520     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8521         PPC::isSplatShuffleMask(SVOp, 2) ||
8522         PPC::isSplatShuffleMask(SVOp, 4) ||
8523         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8524         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8525         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8526         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8527         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8528         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8529         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8530         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8531         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8532         (Subtarget.hasP8Altivec() && (
8533          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8534          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8535          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8536       return Op;
8537     }
8538   }
8539 
8540   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8541   // and produce a fixed permutation.  If any of these match, do not lower to
8542   // VPERM.
8543   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8544   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8545       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8546       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8547       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8548       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8549       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8550       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8551       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8552       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8553       (Subtarget.hasP8Altivec() && (
8554        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8555        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8556        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8557     return Op;
8558 
8559   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8560   // perfect shuffle table to emit an optimal matching sequence.
8561   ArrayRef<int> PermMask = SVOp->getMask();
8562 
8563   unsigned PFIndexes[4];
8564   bool isFourElementShuffle = true;
8565   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8566     unsigned EltNo = 8;   // Start out undef.
8567     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8568       if (PermMask[i*4+j] < 0)
8569         continue;   // Undef, ignore it.
8570 
8571       unsigned ByteSource = PermMask[i*4+j];
8572       if ((ByteSource & 3) != j) {
8573         isFourElementShuffle = false;
8574         break;
8575       }
8576 
8577       if (EltNo == 8) {
8578         EltNo = ByteSource/4;
8579       } else if (EltNo != ByteSource/4) {
8580         isFourElementShuffle = false;
8581         break;
8582       }
8583     }
8584     PFIndexes[i] = EltNo;
8585   }
8586 
8587   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8588   // perfect shuffle vector to determine if it is cost effective to do this as
8589   // discrete instructions, or whether we should use a vperm.
8590   // For now, we skip this for little endian until such time as we have a
8591   // little-endian perfect shuffle table.
8592   if (isFourElementShuffle && !isLittleEndian) {
8593     // Compute the index in the perfect shuffle table.
8594     unsigned PFTableIndex =
8595       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8596 
8597     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8598     unsigned Cost  = (PFEntry >> 30);
8599 
8600     // Determining when to avoid vperm is tricky.  Many things affect the cost
8601     // of vperm, particularly how many times the perm mask needs to be computed.
8602     // For example, if the perm mask can be hoisted out of a loop or is already
8603     // used (perhaps because there are multiple permutes with the same shuffle
8604     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8605     // the loop requires an extra register.
8606     //
8607     // As a compromise, we only emit discrete instructions if the shuffle can be
8608     // generated in 3 or fewer operations.  When we have loop information
8609     // available, if this block is within a loop, we should avoid using vperm
8610     // for 3-operation perms and use a constant pool load instead.
8611     if (Cost < 3)
8612       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8613   }
8614 
8615   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8616   // vector that will get spilled to the constant pool.
8617   if (V2.isUndef()) V2 = V1;
8618 
8619   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8620   // that it is in input element units, not in bytes.  Convert now.
8621 
8622   // For little endian, the order of the input vectors is reversed, and
8623   // the permutation mask is complemented with respect to 31.  This is
8624   // necessary to produce proper semantics with the big-endian-biased vperm
8625   // instruction.
8626   EVT EltVT = V1.getValueType().getVectorElementType();
8627   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8628 
8629   SmallVector<SDValue, 16> ResultMask;
8630   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8631     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8632 
8633     for (unsigned j = 0; j != BytesPerElement; ++j)
8634       if (isLittleEndian)
8635         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8636                                              dl, MVT::i32));
8637       else
8638         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8639                                              MVT::i32));
8640   }
8641 
8642   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8643   if (isLittleEndian)
8644     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8645                        V2, V1, VPermMask);
8646   else
8647     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8648                        V1, V2, VPermMask);
8649 }
8650 
8651 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8652 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8653 /// information about the intrinsic.
8654 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8655                                  bool &isDot, const PPCSubtarget &Subtarget) {
8656   unsigned IntrinsicID =
8657       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8658   CompareOpc = -1;
8659   isDot = false;
8660   switch (IntrinsicID) {
8661   default:
8662     return false;
8663   // Comparison predicates.
8664   case Intrinsic::ppc_altivec_vcmpbfp_p:
8665     CompareOpc = 966;
8666     isDot = true;
8667     break;
8668   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8669     CompareOpc = 198;
8670     isDot = true;
8671     break;
8672   case Intrinsic::ppc_altivec_vcmpequb_p:
8673     CompareOpc = 6;
8674     isDot = true;
8675     break;
8676   case Intrinsic::ppc_altivec_vcmpequh_p:
8677     CompareOpc = 70;
8678     isDot = true;
8679     break;
8680   case Intrinsic::ppc_altivec_vcmpequw_p:
8681     CompareOpc = 134;
8682     isDot = true;
8683     break;
8684   case Intrinsic::ppc_altivec_vcmpequd_p:
8685     if (Subtarget.hasP8Altivec()) {
8686       CompareOpc = 199;
8687       isDot = true;
8688     } else
8689       return false;
8690     break;
8691   case Intrinsic::ppc_altivec_vcmpneb_p:
8692   case Intrinsic::ppc_altivec_vcmpneh_p:
8693   case Intrinsic::ppc_altivec_vcmpnew_p:
8694   case Intrinsic::ppc_altivec_vcmpnezb_p:
8695   case Intrinsic::ppc_altivec_vcmpnezh_p:
8696   case Intrinsic::ppc_altivec_vcmpnezw_p:
8697     if (Subtarget.hasP9Altivec()) {
8698       switch (IntrinsicID) {
8699       default:
8700         llvm_unreachable("Unknown comparison intrinsic.");
8701       case Intrinsic::ppc_altivec_vcmpneb_p:
8702         CompareOpc = 7;
8703         break;
8704       case Intrinsic::ppc_altivec_vcmpneh_p:
8705         CompareOpc = 71;
8706         break;
8707       case Intrinsic::ppc_altivec_vcmpnew_p:
8708         CompareOpc = 135;
8709         break;
8710       case Intrinsic::ppc_altivec_vcmpnezb_p:
8711         CompareOpc = 263;
8712         break;
8713       case Intrinsic::ppc_altivec_vcmpnezh_p:
8714         CompareOpc = 327;
8715         break;
8716       case Intrinsic::ppc_altivec_vcmpnezw_p:
8717         CompareOpc = 391;
8718         break;
8719       }
8720       isDot = true;
8721     } else
8722       return false;
8723     break;
8724   case Intrinsic::ppc_altivec_vcmpgefp_p:
8725     CompareOpc = 454;
8726     isDot = true;
8727     break;
8728   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8729     CompareOpc = 710;
8730     isDot = true;
8731     break;
8732   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8733     CompareOpc = 774;
8734     isDot = true;
8735     break;
8736   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8737     CompareOpc = 838;
8738     isDot = true;
8739     break;
8740   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8741     CompareOpc = 902;
8742     isDot = true;
8743     break;
8744   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8745     if (Subtarget.hasP8Altivec()) {
8746       CompareOpc = 967;
8747       isDot = true;
8748     } else
8749       return false;
8750     break;
8751   case Intrinsic::ppc_altivec_vcmpgtub_p:
8752     CompareOpc = 518;
8753     isDot = true;
8754     break;
8755   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8756     CompareOpc = 582;
8757     isDot = true;
8758     break;
8759   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8760     CompareOpc = 646;
8761     isDot = true;
8762     break;
8763   case Intrinsic::ppc_altivec_vcmpgtud_p:
8764     if (Subtarget.hasP8Altivec()) {
8765       CompareOpc = 711;
8766       isDot = true;
8767     } else
8768       return false;
8769     break;
8770 
8771   // VSX predicate comparisons use the same infrastructure
8772   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8773   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8774   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8775   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8776   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8777   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8778     if (Subtarget.hasVSX()) {
8779       switch (IntrinsicID) {
8780       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8781         CompareOpc = 99;
8782         break;
8783       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8784         CompareOpc = 115;
8785         break;
8786       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8787         CompareOpc = 107;
8788         break;
8789       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8790         CompareOpc = 67;
8791         break;
8792       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8793         CompareOpc = 83;
8794         break;
8795       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8796         CompareOpc = 75;
8797         break;
8798       }
8799       isDot = true;
8800     } else
8801       return false;
8802     break;
8803 
8804   // Normal Comparisons.
8805   case Intrinsic::ppc_altivec_vcmpbfp:
8806     CompareOpc = 966;
8807     break;
8808   case Intrinsic::ppc_altivec_vcmpeqfp:
8809     CompareOpc = 198;
8810     break;
8811   case Intrinsic::ppc_altivec_vcmpequb:
8812     CompareOpc = 6;
8813     break;
8814   case Intrinsic::ppc_altivec_vcmpequh:
8815     CompareOpc = 70;
8816     break;
8817   case Intrinsic::ppc_altivec_vcmpequw:
8818     CompareOpc = 134;
8819     break;
8820   case Intrinsic::ppc_altivec_vcmpequd:
8821     if (Subtarget.hasP8Altivec())
8822       CompareOpc = 199;
8823     else
8824       return false;
8825     break;
8826   case Intrinsic::ppc_altivec_vcmpneb:
8827   case Intrinsic::ppc_altivec_vcmpneh:
8828   case Intrinsic::ppc_altivec_vcmpnew:
8829   case Intrinsic::ppc_altivec_vcmpnezb:
8830   case Intrinsic::ppc_altivec_vcmpnezh:
8831   case Intrinsic::ppc_altivec_vcmpnezw:
8832     if (Subtarget.hasP9Altivec())
8833       switch (IntrinsicID) {
8834       default:
8835         llvm_unreachable("Unknown comparison intrinsic.");
8836       case Intrinsic::ppc_altivec_vcmpneb:
8837         CompareOpc = 7;
8838         break;
8839       case Intrinsic::ppc_altivec_vcmpneh:
8840         CompareOpc = 71;
8841         break;
8842       case Intrinsic::ppc_altivec_vcmpnew:
8843         CompareOpc = 135;
8844         break;
8845       case Intrinsic::ppc_altivec_vcmpnezb:
8846         CompareOpc = 263;
8847         break;
8848       case Intrinsic::ppc_altivec_vcmpnezh:
8849         CompareOpc = 327;
8850         break;
8851       case Intrinsic::ppc_altivec_vcmpnezw:
8852         CompareOpc = 391;
8853         break;
8854       }
8855     else
8856       return false;
8857     break;
8858   case Intrinsic::ppc_altivec_vcmpgefp:
8859     CompareOpc = 454;
8860     break;
8861   case Intrinsic::ppc_altivec_vcmpgtfp:
8862     CompareOpc = 710;
8863     break;
8864   case Intrinsic::ppc_altivec_vcmpgtsb:
8865     CompareOpc = 774;
8866     break;
8867   case Intrinsic::ppc_altivec_vcmpgtsh:
8868     CompareOpc = 838;
8869     break;
8870   case Intrinsic::ppc_altivec_vcmpgtsw:
8871     CompareOpc = 902;
8872     break;
8873   case Intrinsic::ppc_altivec_vcmpgtsd:
8874     if (Subtarget.hasP8Altivec())
8875       CompareOpc = 967;
8876     else
8877       return false;
8878     break;
8879   case Intrinsic::ppc_altivec_vcmpgtub:
8880     CompareOpc = 518;
8881     break;
8882   case Intrinsic::ppc_altivec_vcmpgtuh:
8883     CompareOpc = 582;
8884     break;
8885   case Intrinsic::ppc_altivec_vcmpgtuw:
8886     CompareOpc = 646;
8887     break;
8888   case Intrinsic::ppc_altivec_vcmpgtud:
8889     if (Subtarget.hasP8Altivec())
8890       CompareOpc = 711;
8891     else
8892       return false;
8893     break;
8894   }
8895   return true;
8896 }
8897 
8898 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8899 /// lower, do it, otherwise return null.
8900 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8901                                                    SelectionDAG &DAG) const {
8902   unsigned IntrinsicID =
8903     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8904 
8905   SDLoc dl(Op);
8906 
8907   if (IntrinsicID == Intrinsic::thread_pointer) {
8908     // Reads the thread pointer register, used for __builtin_thread_pointer.
8909     if (Subtarget.isPPC64())
8910       return DAG.getRegister(PPC::X13, MVT::i64);
8911     return DAG.getRegister(PPC::R2, MVT::i32);
8912   }
8913 
8914   // We are looking for absolute values here.
8915   // The idea is to try to fit one of two patterns:
8916   //  max (a, (0-a))  OR  max ((0-a), a)
8917   if (Subtarget.hasP9Vector() &&
8918       (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8919        IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8920        IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8921     SDValue V1 = Op.getOperand(1);
8922     SDValue V2 = Op.getOperand(2);
8923     if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8924         (V1.getSimpleValueType() == MVT::v4i32 ||
8925          V1.getSimpleValueType() == MVT::v8i16 ||
8926          V1.getSimpleValueType() == MVT::v16i8)) {
8927       if ( V1.getOpcode() == ISD::SUB &&
8928            ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8929            V1.getOperand(1) == V2 ) {
8930         // Generate the abs instruction with the operands
8931         return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8932       }
8933 
8934       if ( V2.getOpcode() == ISD::SUB &&
8935            ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8936            V2.getOperand(1) == V1 ) {
8937         // Generate the abs instruction with the operands
8938         return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8939       }
8940     }
8941   }
8942 
8943   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8944   // opcode number of the comparison.
8945   int CompareOpc;
8946   bool isDot;
8947   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8948     return SDValue();    // Don't custom lower most intrinsics.
8949 
8950   // If this is a non-dot comparison, make the VCMP node and we are done.
8951   if (!isDot) {
8952     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8953                               Op.getOperand(1), Op.getOperand(2),
8954                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8955     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8956   }
8957 
8958   // Create the PPCISD altivec 'dot' comparison node.
8959   SDValue Ops[] = {
8960     Op.getOperand(2),  // LHS
8961     Op.getOperand(3),  // RHS
8962     DAG.getConstant(CompareOpc, dl, MVT::i32)
8963   };
8964   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8965   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8966 
8967   // Now that we have the comparison, emit a copy from the CR to a GPR.
8968   // This is flagged to the above dot comparison.
8969   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8970                                 DAG.getRegister(PPC::CR6, MVT::i32),
8971                                 CompNode.getValue(1));
8972 
8973   // Unpack the result based on how the target uses it.
8974   unsigned BitNo;   // Bit # of CR6.
8975   bool InvertBit;   // Invert result?
8976   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8977   default:  // Can't happen, don't crash on invalid number though.
8978   case 0:   // Return the value of the EQ bit of CR6.
8979     BitNo = 0; InvertBit = false;
8980     break;
8981   case 1:   // Return the inverted value of the EQ bit of CR6.
8982     BitNo = 0; InvertBit = true;
8983     break;
8984   case 2:   // Return the value of the LT bit of CR6.
8985     BitNo = 2; InvertBit = false;
8986     break;
8987   case 3:   // Return the inverted value of the LT bit of CR6.
8988     BitNo = 2; InvertBit = true;
8989     break;
8990   }
8991 
8992   // Shift the bit into the low position.
8993   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8994                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8995   // Isolate the bit.
8996   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8997                       DAG.getConstant(1, dl, MVT::i32));
8998 
8999   // If we are supposed to, toggle the bit.
9000   if (InvertBit)
9001     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9002                         DAG.getConstant(1, dl, MVT::i32));
9003   return Flags;
9004 }
9005 
9006 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9007                                                SelectionDAG &DAG) const {
9008   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9009   // the beginning of the argument list.
9010   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9011   SDLoc DL(Op);
9012   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9013   case Intrinsic::ppc_cfence: {
9014     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9015     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9016     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9017                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9018                                                   Op.getOperand(ArgStart + 1)),
9019                                       Op.getOperand(0)),
9020                    0);
9021   }
9022   default:
9023     break;
9024   }
9025   return SDValue();
9026 }
9027 
9028 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9029   // Check for a DIV with the same operands as this REM.
9030   for (auto UI : Op.getOperand(1)->uses()) {
9031     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9032         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9033       if (UI->getOperand(0) == Op.getOperand(0) &&
9034           UI->getOperand(1) == Op.getOperand(1))
9035         return SDValue();
9036   }
9037   return Op;
9038 }
9039 
9040 // Lower scalar BSWAP64 to xxbrd.
9041 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9042   SDLoc dl(Op);
9043   // MTVSRDD
9044   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9045                    Op.getOperand(0));
9046   // XXBRD
9047   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9048   // MFVSRD
9049   int VectorIndex = 0;
9050   if (Subtarget.isLittleEndian())
9051     VectorIndex = 1;
9052   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9053                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9054   return Op;
9055 }
9056 
9057 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9058 // compared to a value that is atomically loaded (atomic loads zero-extend).
9059 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9060                                                 SelectionDAG &DAG) const {
9061   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9062          "Expecting an atomic compare-and-swap here.");
9063   SDLoc dl(Op);
9064   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9065   EVT MemVT = AtomicNode->getMemoryVT();
9066   if (MemVT.getSizeInBits() >= 32)
9067     return Op;
9068 
9069   SDValue CmpOp = Op.getOperand(2);
9070   // If this is already correctly zero-extended, leave it alone.
9071   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9072   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9073     return Op;
9074 
9075   // Clear the high bits of the compare operand.
9076   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9077   SDValue NewCmpOp =
9078     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9079                 DAG.getConstant(MaskVal, dl, MVT::i32));
9080 
9081   // Replace the existing compare operand with the properly zero-extended one.
9082   SmallVector<SDValue, 4> Ops;
9083   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9084     Ops.push_back(AtomicNode->getOperand(i));
9085   Ops[2] = NewCmpOp;
9086   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9087   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9088   auto NodeTy =
9089     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9090   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9091 }
9092 
9093 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
9094                                                   SelectionDAG &DAG) const {
9095   SDLoc dl(Op);
9096   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
9097   // instructions), but for smaller types, we need to first extend up to v2i32
9098   // before doing going farther.
9099   if (Op.getValueType() == MVT::v2i64) {
9100     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
9101     if (ExtVT != MVT::v2i32) {
9102       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
9103       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
9104                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
9105                                         ExtVT.getVectorElementType(), 4)));
9106       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
9107       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
9108                        DAG.getValueType(MVT::v2i32));
9109     }
9110 
9111     return Op;
9112   }
9113 
9114   return SDValue();
9115 }
9116 
9117 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9118                                                  SelectionDAG &DAG) const {
9119   SDLoc dl(Op);
9120   // Create a stack slot that is 16-byte aligned.
9121   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9122   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9123   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9124   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9125 
9126   // Store the input value into Value#0 of the stack slot.
9127   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9128                                MachinePointerInfo());
9129   // Load it out.
9130   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9131 }
9132 
9133 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9134                                                   SelectionDAG &DAG) const {
9135   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9136          "Should only be called for ISD::INSERT_VECTOR_ELT");
9137 
9138   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9139   // We have legal lowering for constant indices but not for variable ones.
9140   if (!C)
9141     return SDValue();
9142 
9143   EVT VT = Op.getValueType();
9144   SDLoc dl(Op);
9145   SDValue V1 = Op.getOperand(0);
9146   SDValue V2 = Op.getOperand(1);
9147   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9148   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9149     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9150     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9151     unsigned InsertAtElement = C->getZExtValue();
9152     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9153     if (Subtarget.isLittleEndian()) {
9154       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9155     }
9156     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9157                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9158   }
9159   return Op;
9160 }
9161 
9162 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9163                                                    SelectionDAG &DAG) const {
9164   SDLoc dl(Op);
9165   SDNode *N = Op.getNode();
9166 
9167   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9168          "Unknown extract_vector_elt type");
9169 
9170   SDValue Value = N->getOperand(0);
9171 
9172   // The first part of this is like the store lowering except that we don't
9173   // need to track the chain.
9174 
9175   // The values are now known to be -1 (false) or 1 (true). To convert this
9176   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9177   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9178   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9179 
9180   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9181   // understand how to form the extending load.
9182   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9183 
9184   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9185 
9186   // Now convert to an integer and store.
9187   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9188     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9189     Value);
9190 
9191   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9192   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9193   MachinePointerInfo PtrInfo =
9194       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9195   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9196   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9197 
9198   SDValue StoreChain = DAG.getEntryNode();
9199   SDValue Ops[] = {StoreChain,
9200                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9201                    Value, FIdx};
9202   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9203 
9204   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9205     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9206 
9207   // Extract the value requested.
9208   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9209   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9210   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9211 
9212   SDValue IntVal =
9213       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9214 
9215   if (!Subtarget.useCRBits())
9216     return IntVal;
9217 
9218   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9219 }
9220 
9221 /// Lowering for QPX v4i1 loads
9222 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9223                                            SelectionDAG &DAG) const {
9224   SDLoc dl(Op);
9225   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9226   SDValue LoadChain = LN->getChain();
9227   SDValue BasePtr = LN->getBasePtr();
9228 
9229   if (Op.getValueType() == MVT::v4f64 ||
9230       Op.getValueType() == MVT::v4f32) {
9231     EVT MemVT = LN->getMemoryVT();
9232     unsigned Alignment = LN->getAlignment();
9233 
9234     // If this load is properly aligned, then it is legal.
9235     if (Alignment >= MemVT.getStoreSize())
9236       return Op;
9237 
9238     EVT ScalarVT = Op.getValueType().getScalarType(),
9239         ScalarMemVT = MemVT.getScalarType();
9240     unsigned Stride = ScalarMemVT.getStoreSize();
9241 
9242     SDValue Vals[4], LoadChains[4];
9243     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9244       SDValue Load;
9245       if (ScalarVT != ScalarMemVT)
9246         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9247                               BasePtr,
9248                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9249                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9250                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9251       else
9252         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9253                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9254                            MinAlign(Alignment, Idx * Stride),
9255                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9256 
9257       if (Idx == 0 && LN->isIndexed()) {
9258         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9259                "Unknown addressing mode on vector load");
9260         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9261                                   LN->getAddressingMode());
9262       }
9263 
9264       Vals[Idx] = Load;
9265       LoadChains[Idx] = Load.getValue(1);
9266 
9267       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9268                             DAG.getConstant(Stride, dl,
9269                                             BasePtr.getValueType()));
9270     }
9271 
9272     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9273     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9274 
9275     if (LN->isIndexed()) {
9276       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9277       return DAG.getMergeValues(RetOps, dl);
9278     }
9279 
9280     SDValue RetOps[] = { Value, TF };
9281     return DAG.getMergeValues(RetOps, dl);
9282   }
9283 
9284   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9285   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9286 
9287   // To lower v4i1 from a byte array, we load the byte elements of the
9288   // vector and then reuse the BUILD_VECTOR logic.
9289 
9290   SDValue VectElmts[4], VectElmtChains[4];
9291   for (unsigned i = 0; i < 4; ++i) {
9292     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9293     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9294 
9295     VectElmts[i] = DAG.getExtLoad(
9296         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9297         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9298         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9299     VectElmtChains[i] = VectElmts[i].getValue(1);
9300   }
9301 
9302   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9303   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9304 
9305   SDValue RVals[] = { Value, LoadChain };
9306   return DAG.getMergeValues(RVals, dl);
9307 }
9308 
9309 /// Lowering for QPX v4i1 stores
9310 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9311                                             SelectionDAG &DAG) const {
9312   SDLoc dl(Op);
9313   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9314   SDValue StoreChain = SN->getChain();
9315   SDValue BasePtr = SN->getBasePtr();
9316   SDValue Value = SN->getValue();
9317 
9318   if (Value.getValueType() == MVT::v4f64 ||
9319       Value.getValueType() == MVT::v4f32) {
9320     EVT MemVT = SN->getMemoryVT();
9321     unsigned Alignment = SN->getAlignment();
9322 
9323     // If this store is properly aligned, then it is legal.
9324     if (Alignment >= MemVT.getStoreSize())
9325       return Op;
9326 
9327     EVT ScalarVT = Value.getValueType().getScalarType(),
9328         ScalarMemVT = MemVT.getScalarType();
9329     unsigned Stride = ScalarMemVT.getStoreSize();
9330 
9331     SDValue Stores[4];
9332     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9333       SDValue Ex = DAG.getNode(
9334           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9335           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9336       SDValue Store;
9337       if (ScalarVT != ScalarMemVT)
9338         Store =
9339             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9340                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9341                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9342                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9343       else
9344         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9345                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9346                              MinAlign(Alignment, Idx * Stride),
9347                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9348 
9349       if (Idx == 0 && SN->isIndexed()) {
9350         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9351                "Unknown addressing mode on vector store");
9352         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9353                                     SN->getAddressingMode());
9354       }
9355 
9356       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9357                             DAG.getConstant(Stride, dl,
9358                                             BasePtr.getValueType()));
9359       Stores[Idx] = Store;
9360     }
9361 
9362     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9363 
9364     if (SN->isIndexed()) {
9365       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9366       return DAG.getMergeValues(RetOps, dl);
9367     }
9368 
9369     return TF;
9370   }
9371 
9372   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9373   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9374 
9375   // The values are now known to be -1 (false) or 1 (true). To convert this
9376   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9377   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9378   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9379 
9380   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9381   // understand how to form the extending load.
9382   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9383 
9384   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9385 
9386   // Now convert to an integer and store.
9387   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9388     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9389     Value);
9390 
9391   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9392   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9393   MachinePointerInfo PtrInfo =
9394       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9395   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9396   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9397 
9398   SDValue Ops[] = {StoreChain,
9399                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9400                    Value, FIdx};
9401   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9402 
9403   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9404     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9405 
9406   // Move data into the byte array.
9407   SDValue Loads[4], LoadChains[4];
9408   for (unsigned i = 0; i < 4; ++i) {
9409     unsigned Offset = 4*i;
9410     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9411     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9412 
9413     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9414                            PtrInfo.getWithOffset(Offset));
9415     LoadChains[i] = Loads[i].getValue(1);
9416   }
9417 
9418   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9419 
9420   SDValue Stores[4];
9421   for (unsigned i = 0; i < 4; ++i) {
9422     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9423     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9424 
9425     Stores[i] = DAG.getTruncStore(
9426         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9427         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9428         SN->getAAInfo());
9429   }
9430 
9431   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9432 
9433   return StoreChain;
9434 }
9435 
9436 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9437   SDLoc dl(Op);
9438   if (Op.getValueType() == MVT::v4i32) {
9439     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9440 
9441     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9442     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9443 
9444     SDValue RHSSwap =   // = vrlw RHS, 16
9445       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9446 
9447     // Shrinkify inputs to v8i16.
9448     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9449     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9450     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9451 
9452     // Low parts multiplied together, generating 32-bit results (we ignore the
9453     // top parts).
9454     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9455                                         LHS, RHS, DAG, dl, MVT::v4i32);
9456 
9457     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9458                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9459     // Shift the high parts up 16 bits.
9460     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9461                               Neg16, DAG, dl);
9462     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9463   } else if (Op.getValueType() == MVT::v8i16) {
9464     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9465 
9466     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9467 
9468     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9469                             LHS, RHS, Zero, DAG, dl);
9470   } else if (Op.getValueType() == MVT::v16i8) {
9471     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9472     bool isLittleEndian = Subtarget.isLittleEndian();
9473 
9474     // Multiply the even 8-bit parts, producing 16-bit sums.
9475     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9476                                            LHS, RHS, DAG, dl, MVT::v8i16);
9477     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9478 
9479     // Multiply the odd 8-bit parts, producing 16-bit sums.
9480     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9481                                           LHS, RHS, DAG, dl, MVT::v8i16);
9482     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9483 
9484     // Merge the results together.  Because vmuleub and vmuloub are
9485     // instructions with a big-endian bias, we must reverse the
9486     // element numbering and reverse the meaning of "odd" and "even"
9487     // when generating little endian code.
9488     int Ops[16];
9489     for (unsigned i = 0; i != 8; ++i) {
9490       if (isLittleEndian) {
9491         Ops[i*2  ] = 2*i;
9492         Ops[i*2+1] = 2*i+16;
9493       } else {
9494         Ops[i*2  ] = 2*i+1;
9495         Ops[i*2+1] = 2*i+1+16;
9496       }
9497     }
9498     if (isLittleEndian)
9499       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9500     else
9501       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9502   } else {
9503     llvm_unreachable("Unknown mul to lower!");
9504   }
9505 }
9506 
9507 /// LowerOperation - Provide custom lowering hooks for some operations.
9508 ///
9509 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9510   switch (Op.getOpcode()) {
9511   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9512   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9513   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9514   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9515   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9516   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9517   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9518   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9519   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9520 
9521   // Variable argument lowering.
9522   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9523   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9524   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9525 
9526   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9527   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9528   case ISD::GET_DYNAMIC_AREA_OFFSET:
9529     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9530 
9531   // Exception handling lowering.
9532   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9533   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9534   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9535 
9536   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9537   case ISD::STORE:              return LowerSTORE(Op, DAG);
9538   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9539   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9540   case ISD::FP_TO_UINT:
9541   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9542   case ISD::UINT_TO_FP:
9543   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9544   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9545 
9546   // Lower 64-bit shifts.
9547   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9548   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9549   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9550 
9551   // Vector-related lowering.
9552   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9553   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9554   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9555   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9556   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
9557   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9558   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9559   case ISD::MUL:                return LowerMUL(Op, DAG);
9560 
9561   // For counter-based loop handling.
9562   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9563 
9564   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9565 
9566   // Frame & Return address.
9567   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9568   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9569 
9570   case ISD::INTRINSIC_VOID:
9571     return LowerINTRINSIC_VOID(Op, DAG);
9572   case ISD::SREM:
9573   case ISD::UREM:
9574     return LowerREM(Op, DAG);
9575   case ISD::BSWAP:
9576     return LowerBSWAP(Op, DAG);
9577   case ISD::ATOMIC_CMP_SWAP:
9578     return LowerATOMIC_CMP_SWAP(Op, DAG);
9579   }
9580 }
9581 
9582 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9583                                            SmallVectorImpl<SDValue>&Results,
9584                                            SelectionDAG &DAG) const {
9585   SDLoc dl(N);
9586   switch (N->getOpcode()) {
9587   default:
9588     llvm_unreachable("Do not know how to custom type legalize this operation!");
9589   case ISD::READCYCLECOUNTER: {
9590     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9591     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9592 
9593     Results.push_back(RTB);
9594     Results.push_back(RTB.getValue(1));
9595     Results.push_back(RTB.getValue(2));
9596     break;
9597   }
9598   case ISD::INTRINSIC_W_CHAIN: {
9599     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9600         Intrinsic::ppc_is_decremented_ctr_nonzero)
9601       break;
9602 
9603     assert(N->getValueType(0) == MVT::i1 &&
9604            "Unexpected result type for CTR decrement intrinsic");
9605     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9606                                  N->getValueType(0));
9607     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9608     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9609                                  N->getOperand(1));
9610 
9611     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9612     Results.push_back(NewInt.getValue(1));
9613     break;
9614   }
9615   case ISD::VAARG: {
9616     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9617       return;
9618 
9619     EVT VT = N->getValueType(0);
9620 
9621     if (VT == MVT::i64) {
9622       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9623 
9624       Results.push_back(NewNode);
9625       Results.push_back(NewNode.getValue(1));
9626     }
9627     return;
9628   }
9629   case ISD::FP_TO_SINT:
9630   case ISD::FP_TO_UINT:
9631     // LowerFP_TO_INT() can only handle f32 and f64.
9632     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9633       return;
9634     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9635     return;
9636   }
9637 }
9638 
9639 //===----------------------------------------------------------------------===//
9640 //  Other Lowering Code
9641 //===----------------------------------------------------------------------===//
9642 
9643 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9644   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9645   Function *Func = Intrinsic::getDeclaration(M, Id);
9646   return Builder.CreateCall(Func, {});
9647 }
9648 
9649 // The mappings for emitLeading/TrailingFence is taken from
9650 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9651 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9652                                                  Instruction *Inst,
9653                                                  AtomicOrdering Ord) const {
9654   if (Ord == AtomicOrdering::SequentiallyConsistent)
9655     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9656   if (isReleaseOrStronger(Ord))
9657     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9658   return nullptr;
9659 }
9660 
9661 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9662                                                   Instruction *Inst,
9663                                                   AtomicOrdering Ord) const {
9664   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9665     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9666     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9667     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9668     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9669       return Builder.CreateCall(
9670           Intrinsic::getDeclaration(
9671               Builder.GetInsertBlock()->getParent()->getParent(),
9672               Intrinsic::ppc_cfence, {Inst->getType()}),
9673           {Inst});
9674     // FIXME: Can use isync for rmw operation.
9675     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9676   }
9677   return nullptr;
9678 }
9679 
9680 MachineBasicBlock *
9681 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9682                                     unsigned AtomicSize,
9683                                     unsigned BinOpcode,
9684                                     unsigned CmpOpcode,
9685                                     unsigned CmpPred) const {
9686   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9687   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9688 
9689   auto LoadMnemonic = PPC::LDARX;
9690   auto StoreMnemonic = PPC::STDCX;
9691   switch (AtomicSize) {
9692   default:
9693     llvm_unreachable("Unexpected size of atomic entity");
9694   case 1:
9695     LoadMnemonic = PPC::LBARX;
9696     StoreMnemonic = PPC::STBCX;
9697     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9698     break;
9699   case 2:
9700     LoadMnemonic = PPC::LHARX;
9701     StoreMnemonic = PPC::STHCX;
9702     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9703     break;
9704   case 4:
9705     LoadMnemonic = PPC::LWARX;
9706     StoreMnemonic = PPC::STWCX;
9707     break;
9708   case 8:
9709     LoadMnemonic = PPC::LDARX;
9710     StoreMnemonic = PPC::STDCX;
9711     break;
9712   }
9713 
9714   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9715   MachineFunction *F = BB->getParent();
9716   MachineFunction::iterator It = ++BB->getIterator();
9717 
9718   unsigned dest = MI.getOperand(0).getReg();
9719   unsigned ptrA = MI.getOperand(1).getReg();
9720   unsigned ptrB = MI.getOperand(2).getReg();
9721   unsigned incr = MI.getOperand(3).getReg();
9722   DebugLoc dl = MI.getDebugLoc();
9723 
9724   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9725   MachineBasicBlock *loop2MBB =
9726     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9727   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9728   F->insert(It, loopMBB);
9729   if (CmpOpcode)
9730     F->insert(It, loop2MBB);
9731   F->insert(It, exitMBB);
9732   exitMBB->splice(exitMBB->begin(), BB,
9733                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9734   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9735 
9736   MachineRegisterInfo &RegInfo = F->getRegInfo();
9737   unsigned TmpReg = (!BinOpcode) ? incr :
9738     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9739                                            : &PPC::GPRCRegClass);
9740 
9741   //  thisMBB:
9742   //   ...
9743   //   fallthrough --> loopMBB
9744   BB->addSuccessor(loopMBB);
9745 
9746   //  loopMBB:
9747   //   l[wd]arx dest, ptr
9748   //   add r0, dest, incr
9749   //   st[wd]cx. r0, ptr
9750   //   bne- loopMBB
9751   //   fallthrough --> exitMBB
9752 
9753   // For max/min...
9754   //  loopMBB:
9755   //   l[wd]arx dest, ptr
9756   //   cmpl?[wd] incr, dest
9757   //   bgt exitMBB
9758   //  loop2MBB:
9759   //   st[wd]cx. dest, ptr
9760   //   bne- loopMBB
9761   //   fallthrough --> exitMBB
9762 
9763   BB = loopMBB;
9764   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9765     .addReg(ptrA).addReg(ptrB);
9766   if (BinOpcode)
9767     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9768   if (CmpOpcode) {
9769     // Signed comparisons of byte or halfword values must be sign-extended.
9770     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9771       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9772       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9773               ExtReg).addReg(dest);
9774       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9775         .addReg(incr).addReg(ExtReg);
9776     } else
9777       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9778         .addReg(incr).addReg(dest);
9779 
9780     BuildMI(BB, dl, TII->get(PPC::BCC))
9781       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9782     BB->addSuccessor(loop2MBB);
9783     BB->addSuccessor(exitMBB);
9784     BB = loop2MBB;
9785   }
9786   BuildMI(BB, dl, TII->get(StoreMnemonic))
9787     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9788   BuildMI(BB, dl, TII->get(PPC::BCC))
9789     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9790   BB->addSuccessor(loopMBB);
9791   BB->addSuccessor(exitMBB);
9792 
9793   //  exitMBB:
9794   //   ...
9795   BB = exitMBB;
9796   return BB;
9797 }
9798 
9799 MachineBasicBlock *
9800 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9801                                             MachineBasicBlock *BB,
9802                                             bool is8bit, // operation
9803                                             unsigned BinOpcode,
9804                                             unsigned CmpOpcode,
9805                                             unsigned CmpPred) const {
9806   // If we support part-word atomic mnemonics, just use them
9807   if (Subtarget.hasPartwordAtomics())
9808     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9809                             CmpOpcode, CmpPred);
9810 
9811   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9812   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9813   // In 64 bit mode we have to use 64 bits for addresses, even though the
9814   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9815   // registers without caring whether they're 32 or 64, but here we're
9816   // doing actual arithmetic on the addresses.
9817   bool is64bit = Subtarget.isPPC64();
9818   bool isLittleEndian = Subtarget.isLittleEndian();
9819   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9820 
9821   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9822   MachineFunction *F = BB->getParent();
9823   MachineFunction::iterator It = ++BB->getIterator();
9824 
9825   unsigned dest = MI.getOperand(0).getReg();
9826   unsigned ptrA = MI.getOperand(1).getReg();
9827   unsigned ptrB = MI.getOperand(2).getReg();
9828   unsigned incr = MI.getOperand(3).getReg();
9829   DebugLoc dl = MI.getDebugLoc();
9830 
9831   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9832   MachineBasicBlock *loop2MBB =
9833     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9834   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9835   F->insert(It, loopMBB);
9836   if (CmpOpcode)
9837     F->insert(It, loop2MBB);
9838   F->insert(It, exitMBB);
9839   exitMBB->splice(exitMBB->begin(), BB,
9840                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9841   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9842 
9843   MachineRegisterInfo &RegInfo = F->getRegInfo();
9844   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9845                                           : &PPC::GPRCRegClass;
9846   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9847   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9848   unsigned ShiftReg =
9849     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9850   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9851   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9852   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9853   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9854   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9855   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9856   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9857   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9858   unsigned Ptr1Reg;
9859   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9860 
9861   //  thisMBB:
9862   //   ...
9863   //   fallthrough --> loopMBB
9864   BB->addSuccessor(loopMBB);
9865 
9866   // The 4-byte load must be aligned, while a char or short may be
9867   // anywhere in the word.  Hence all this nasty bookkeeping code.
9868   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9869   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9870   //   xori shift, shift1, 24 [16]
9871   //   rlwinm ptr, ptr1, 0, 0, 29
9872   //   slw incr2, incr, shift
9873   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9874   //   slw mask, mask2, shift
9875   //  loopMBB:
9876   //   lwarx tmpDest, ptr
9877   //   add tmp, tmpDest, incr2
9878   //   andc tmp2, tmpDest, mask
9879   //   and tmp3, tmp, mask
9880   //   or tmp4, tmp3, tmp2
9881   //   stwcx. tmp4, ptr
9882   //   bne- loopMBB
9883   //   fallthrough --> exitMBB
9884   //   srw dest, tmpDest, shift
9885   if (ptrA != ZeroReg) {
9886     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9887     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9888       .addReg(ptrA).addReg(ptrB);
9889   } else {
9890     Ptr1Reg = ptrB;
9891   }
9892   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9893       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9894   if (!isLittleEndian)
9895     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9896         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9897   if (is64bit)
9898     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9899       .addReg(Ptr1Reg).addImm(0).addImm(61);
9900   else
9901     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9902       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9903   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9904       .addReg(incr).addReg(ShiftReg);
9905   if (is8bit)
9906     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9907   else {
9908     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9909     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9910   }
9911   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9912       .addReg(Mask2Reg).addReg(ShiftReg);
9913 
9914   BB = loopMBB;
9915   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9916     .addReg(ZeroReg).addReg(PtrReg);
9917   if (BinOpcode)
9918     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9919       .addReg(Incr2Reg).addReg(TmpDestReg);
9920   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9921     .addReg(TmpDestReg).addReg(MaskReg);
9922   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9923     .addReg(TmpReg).addReg(MaskReg);
9924   if (CmpOpcode) {
9925     // For unsigned comparisons, we can directly compare the shifted values.
9926     // For signed comparisons we shift and sign extend.
9927     unsigned SReg = RegInfo.createVirtualRegister(RC);
9928     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9929       .addReg(TmpDestReg).addReg(MaskReg);
9930     unsigned ValueReg = SReg;
9931     unsigned CmpReg = Incr2Reg;
9932     if (CmpOpcode == PPC::CMPW) {
9933       ValueReg = RegInfo.createVirtualRegister(RC);
9934       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9935         .addReg(SReg).addReg(ShiftReg);
9936       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9937       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9938         .addReg(ValueReg);
9939       ValueReg = ValueSReg;
9940       CmpReg = incr;
9941     }
9942     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9943       .addReg(CmpReg).addReg(ValueReg);
9944     BuildMI(BB, dl, TII->get(PPC::BCC))
9945       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9946     BB->addSuccessor(loop2MBB);
9947     BB->addSuccessor(exitMBB);
9948     BB = loop2MBB;
9949   }
9950   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9951     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9952   BuildMI(BB, dl, TII->get(PPC::STWCX))
9953     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9954   BuildMI(BB, dl, TII->get(PPC::BCC))
9955     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9956   BB->addSuccessor(loopMBB);
9957   BB->addSuccessor(exitMBB);
9958 
9959   //  exitMBB:
9960   //   ...
9961   BB = exitMBB;
9962   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9963     .addReg(ShiftReg);
9964   return BB;
9965 }
9966 
9967 llvm::MachineBasicBlock *
9968 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9969                                     MachineBasicBlock *MBB) const {
9970   DebugLoc DL = MI.getDebugLoc();
9971   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9972   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9973 
9974   MachineFunction *MF = MBB->getParent();
9975   MachineRegisterInfo &MRI = MF->getRegInfo();
9976 
9977   const BasicBlock *BB = MBB->getBasicBlock();
9978   MachineFunction::iterator I = ++MBB->getIterator();
9979 
9980   // Memory Reference
9981   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9982   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9983 
9984   unsigned DstReg = MI.getOperand(0).getReg();
9985   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9986   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9987   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9988   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9989 
9990   MVT PVT = getPointerTy(MF->getDataLayout());
9991   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9992          "Invalid Pointer Size!");
9993   // For v = setjmp(buf), we generate
9994   //
9995   // thisMBB:
9996   //  SjLjSetup mainMBB
9997   //  bl mainMBB
9998   //  v_restore = 1
9999   //  b sinkMBB
10000   //
10001   // mainMBB:
10002   //  buf[LabelOffset] = LR
10003   //  v_main = 0
10004   //
10005   // sinkMBB:
10006   //  v = phi(main, restore)
10007   //
10008 
10009   MachineBasicBlock *thisMBB = MBB;
10010   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10011   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10012   MF->insert(I, mainMBB);
10013   MF->insert(I, sinkMBB);
10014 
10015   MachineInstrBuilder MIB;
10016 
10017   // Transfer the remainder of BB and its successor edges to sinkMBB.
10018   sinkMBB->splice(sinkMBB->begin(), MBB,
10019                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10020   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10021 
10022   // Note that the structure of the jmp_buf used here is not compatible
10023   // with that used by libc, and is not designed to be. Specifically, it
10024   // stores only those 'reserved' registers that LLVM does not otherwise
10025   // understand how to spill. Also, by convention, by the time this
10026   // intrinsic is called, Clang has already stored the frame address in the
10027   // first slot of the buffer and stack address in the third. Following the
10028   // X86 target code, we'll store the jump address in the second slot. We also
10029   // need to save the TOC pointer (R2) to handle jumps between shared
10030   // libraries, and that will be stored in the fourth slot. The thread
10031   // identifier (R13) is not affected.
10032 
10033   // thisMBB:
10034   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10035   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10036   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10037 
10038   // Prepare IP either in reg.
10039   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10040   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10041   unsigned BufReg = MI.getOperand(1).getReg();
10042 
10043   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10044     setUsesTOCBasePtr(*MBB->getParent());
10045     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10046             .addReg(PPC::X2)
10047             .addImm(TOCOffset)
10048             .addReg(BufReg);
10049     MIB.setMemRefs(MMOBegin, MMOEnd);
10050   }
10051 
10052   // Naked functions never have a base pointer, and so we use r1. For all
10053   // other functions, this decision must be delayed until during PEI.
10054   unsigned BaseReg;
10055   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10056     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10057   else
10058     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10059 
10060   MIB = BuildMI(*thisMBB, MI, DL,
10061                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10062             .addReg(BaseReg)
10063             .addImm(BPOffset)
10064             .addReg(BufReg);
10065   MIB.setMemRefs(MMOBegin, MMOEnd);
10066 
10067   // Setup
10068   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10069   MIB.addRegMask(TRI->getNoPreservedMask());
10070 
10071   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10072 
10073   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10074           .addMBB(mainMBB);
10075   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10076 
10077   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10078   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10079 
10080   // mainMBB:
10081   //  mainDstReg = 0
10082   MIB =
10083       BuildMI(mainMBB, DL,
10084               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10085 
10086   // Store IP
10087   if (Subtarget.isPPC64()) {
10088     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10089             .addReg(LabelReg)
10090             .addImm(LabelOffset)
10091             .addReg(BufReg);
10092   } else {
10093     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10094             .addReg(LabelReg)
10095             .addImm(LabelOffset)
10096             .addReg(BufReg);
10097   }
10098 
10099   MIB.setMemRefs(MMOBegin, MMOEnd);
10100 
10101   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10102   mainMBB->addSuccessor(sinkMBB);
10103 
10104   // sinkMBB:
10105   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10106           TII->get(PPC::PHI), DstReg)
10107     .addReg(mainDstReg).addMBB(mainMBB)
10108     .addReg(restoreDstReg).addMBB(thisMBB);
10109 
10110   MI.eraseFromParent();
10111   return sinkMBB;
10112 }
10113 
10114 MachineBasicBlock *
10115 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10116                                      MachineBasicBlock *MBB) const {
10117   DebugLoc DL = MI.getDebugLoc();
10118   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10119 
10120   MachineFunction *MF = MBB->getParent();
10121   MachineRegisterInfo &MRI = MF->getRegInfo();
10122 
10123   // Memory Reference
10124   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
10125   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
10126 
10127   MVT PVT = getPointerTy(MF->getDataLayout());
10128   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10129          "Invalid Pointer Size!");
10130 
10131   const TargetRegisterClass *RC =
10132     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10133   unsigned Tmp = MRI.createVirtualRegister(RC);
10134   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10135   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10136   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10137   unsigned BP =
10138       (PVT == MVT::i64)
10139           ? PPC::X30
10140           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10141                                                               : PPC::R30);
10142 
10143   MachineInstrBuilder MIB;
10144 
10145   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10146   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10147   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10148   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10149 
10150   unsigned BufReg = MI.getOperand(0).getReg();
10151 
10152   // Reload FP (the jumped-to function may not have had a
10153   // frame pointer, and if so, then its r31 will be restored
10154   // as necessary).
10155   if (PVT == MVT::i64) {
10156     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10157             .addImm(0)
10158             .addReg(BufReg);
10159   } else {
10160     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10161             .addImm(0)
10162             .addReg(BufReg);
10163   }
10164   MIB.setMemRefs(MMOBegin, MMOEnd);
10165 
10166   // Reload IP
10167   if (PVT == MVT::i64) {
10168     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10169             .addImm(LabelOffset)
10170             .addReg(BufReg);
10171   } else {
10172     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10173             .addImm(LabelOffset)
10174             .addReg(BufReg);
10175   }
10176   MIB.setMemRefs(MMOBegin, MMOEnd);
10177 
10178   // Reload SP
10179   if (PVT == MVT::i64) {
10180     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10181             .addImm(SPOffset)
10182             .addReg(BufReg);
10183   } else {
10184     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10185             .addImm(SPOffset)
10186             .addReg(BufReg);
10187   }
10188   MIB.setMemRefs(MMOBegin, MMOEnd);
10189 
10190   // Reload BP
10191   if (PVT == MVT::i64) {
10192     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10193             .addImm(BPOffset)
10194             .addReg(BufReg);
10195   } else {
10196     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10197             .addImm(BPOffset)
10198             .addReg(BufReg);
10199   }
10200   MIB.setMemRefs(MMOBegin, MMOEnd);
10201 
10202   // Reload TOC
10203   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10204     setUsesTOCBasePtr(*MBB->getParent());
10205     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10206             .addImm(TOCOffset)
10207             .addReg(BufReg);
10208 
10209     MIB.setMemRefs(MMOBegin, MMOEnd);
10210   }
10211 
10212   // Jump
10213   BuildMI(*MBB, MI, DL,
10214           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10215   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10216 
10217   MI.eraseFromParent();
10218   return MBB;
10219 }
10220 
10221 MachineBasicBlock *
10222 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10223                                                MachineBasicBlock *BB) const {
10224   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10225       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10226     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10227         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10228       // Call lowering should have added an r2 operand to indicate a dependence
10229       // on the TOC base pointer value. It can't however, because there is no
10230       // way to mark the dependence as implicit there, and so the stackmap code
10231       // will confuse it with a regular operand. Instead, add the dependence
10232       // here.
10233       setUsesTOCBasePtr(*BB->getParent());
10234       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10235     }
10236 
10237     return emitPatchPoint(MI, BB);
10238   }
10239 
10240   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10241       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10242     return emitEHSjLjSetJmp(MI, BB);
10243   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10244              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10245     return emitEHSjLjLongJmp(MI, BB);
10246   }
10247 
10248   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10249 
10250   // To "insert" these instructions we actually have to insert their
10251   // control-flow patterns.
10252   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10253   MachineFunction::iterator It = ++BB->getIterator();
10254 
10255   MachineFunction *F = BB->getParent();
10256 
10257   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10258        MI.getOpcode() == PPC::SELECT_CC_I8 ||
10259        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
10260     SmallVector<MachineOperand, 2> Cond;
10261     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10262         MI.getOpcode() == PPC::SELECT_CC_I8)
10263       Cond.push_back(MI.getOperand(4));
10264     else
10265       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10266     Cond.push_back(MI.getOperand(1));
10267 
10268     DebugLoc dl = MI.getDebugLoc();
10269     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10270                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10271   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10272              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10273              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10274              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10275              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10276              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10277              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10278              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10279              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10280              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10281              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10282              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10283              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10284              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10285              MI.getOpcode() == PPC::SELECT_I4 ||
10286              MI.getOpcode() == PPC::SELECT_I8 ||
10287              MI.getOpcode() == PPC::SELECT_F4 ||
10288              MI.getOpcode() == PPC::SELECT_F8 ||
10289              MI.getOpcode() == PPC::SELECT_F16 ||
10290              MI.getOpcode() == PPC::SELECT_QFRC ||
10291              MI.getOpcode() == PPC::SELECT_QSRC ||
10292              MI.getOpcode() == PPC::SELECT_QBRC ||
10293              MI.getOpcode() == PPC::SELECT_SPE ||
10294              MI.getOpcode() == PPC::SELECT_SPE4 ||
10295              MI.getOpcode() == PPC::SELECT_VRRC ||
10296              MI.getOpcode() == PPC::SELECT_VSFRC ||
10297              MI.getOpcode() == PPC::SELECT_VSSRC ||
10298              MI.getOpcode() == PPC::SELECT_VSRC) {
10299     // The incoming instruction knows the destination vreg to set, the
10300     // condition code register to branch on, the true/false values to
10301     // select between, and a branch opcode to use.
10302 
10303     //  thisMBB:
10304     //  ...
10305     //   TrueVal = ...
10306     //   cmpTY ccX, r1, r2
10307     //   bCC copy1MBB
10308     //   fallthrough --> copy0MBB
10309     MachineBasicBlock *thisMBB = BB;
10310     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10311     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10312     DebugLoc dl = MI.getDebugLoc();
10313     F->insert(It, copy0MBB);
10314     F->insert(It, sinkMBB);
10315 
10316     // Transfer the remainder of BB and its successor edges to sinkMBB.
10317     sinkMBB->splice(sinkMBB->begin(), BB,
10318                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10319     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10320 
10321     // Next, add the true and fallthrough blocks as its successors.
10322     BB->addSuccessor(copy0MBB);
10323     BB->addSuccessor(sinkMBB);
10324 
10325     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10326         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10327         MI.getOpcode() == PPC::SELECT_F16 ||
10328         MI.getOpcode() == PPC::SELECT_SPE4 ||
10329         MI.getOpcode() == PPC::SELECT_SPE ||
10330         MI.getOpcode() == PPC::SELECT_QFRC ||
10331         MI.getOpcode() == PPC::SELECT_QSRC ||
10332         MI.getOpcode() == PPC::SELECT_QBRC ||
10333         MI.getOpcode() == PPC::SELECT_VRRC ||
10334         MI.getOpcode() == PPC::SELECT_VSFRC ||
10335         MI.getOpcode() == PPC::SELECT_VSSRC ||
10336         MI.getOpcode() == PPC::SELECT_VSRC) {
10337       BuildMI(BB, dl, TII->get(PPC::BC))
10338           .addReg(MI.getOperand(1).getReg())
10339           .addMBB(sinkMBB);
10340     } else {
10341       unsigned SelectPred = MI.getOperand(4).getImm();
10342       BuildMI(BB, dl, TII->get(PPC::BCC))
10343           .addImm(SelectPred)
10344           .addReg(MI.getOperand(1).getReg())
10345           .addMBB(sinkMBB);
10346     }
10347 
10348     //  copy0MBB:
10349     //   %FalseValue = ...
10350     //   # fallthrough to sinkMBB
10351     BB = copy0MBB;
10352 
10353     // Update machine-CFG edges
10354     BB->addSuccessor(sinkMBB);
10355 
10356     //  sinkMBB:
10357     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10358     //  ...
10359     BB = sinkMBB;
10360     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10361         .addReg(MI.getOperand(3).getReg())
10362         .addMBB(copy0MBB)
10363         .addReg(MI.getOperand(2).getReg())
10364         .addMBB(thisMBB);
10365   } else if (MI.getOpcode() == PPC::ReadTB) {
10366     // To read the 64-bit time-base register on a 32-bit target, we read the
10367     // two halves. Should the counter have wrapped while it was being read, we
10368     // need to try again.
10369     // ...
10370     // readLoop:
10371     // mfspr Rx,TBU # load from TBU
10372     // mfspr Ry,TB  # load from TB
10373     // mfspr Rz,TBU # load from TBU
10374     // cmpw crX,Rx,Rz # check if 'old'='new'
10375     // bne readLoop   # branch if they're not equal
10376     // ...
10377 
10378     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10379     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10380     DebugLoc dl = MI.getDebugLoc();
10381     F->insert(It, readMBB);
10382     F->insert(It, sinkMBB);
10383 
10384     // Transfer the remainder of BB and its successor edges to sinkMBB.
10385     sinkMBB->splice(sinkMBB->begin(), BB,
10386                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10387     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10388 
10389     BB->addSuccessor(readMBB);
10390     BB = readMBB;
10391 
10392     MachineRegisterInfo &RegInfo = F->getRegInfo();
10393     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10394     unsigned LoReg = MI.getOperand(0).getReg();
10395     unsigned HiReg = MI.getOperand(1).getReg();
10396 
10397     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10398     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10399     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10400 
10401     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10402 
10403     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10404       .addReg(HiReg).addReg(ReadAgainReg);
10405     BuildMI(BB, dl, TII->get(PPC::BCC))
10406       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
10407 
10408     BB->addSuccessor(readMBB);
10409     BB->addSuccessor(sinkMBB);
10410   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10411     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10412   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10413     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10415     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10416   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10417     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10418 
10419   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10420     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10421   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10422     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10423   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10424     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10425   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10426     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10427 
10428   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10429     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10430   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10431     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10432   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10433     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10434   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10435     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10436 
10437   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10438     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10439   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10440     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10441   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10442     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10443   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10444     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10445 
10446   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10447     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10448   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10449     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10450   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10451     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10452   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10453     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10454 
10455   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10456     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10457   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10458     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10459   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10460     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10461   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10462     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10463 
10464   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10465     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10466   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10467     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10468   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10469     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10470   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10471     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10472 
10473   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10474     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10475   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10476     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10477   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10478     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10479   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10480     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10481 
10482   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10483     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10484   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10485     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10486   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10487     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10488   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10489     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10490 
10491   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10492     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10493   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10494     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10495   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10496     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10497   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10498     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10499 
10500   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10501     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10502   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10503     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10504   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10505     BB = EmitAtomicBinary(MI, BB, 4, 0);
10506   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10507     BB = EmitAtomicBinary(MI, BB, 8, 0);
10508   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10509            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10510            (Subtarget.hasPartwordAtomics() &&
10511             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10512            (Subtarget.hasPartwordAtomics() &&
10513             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10514     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10515 
10516     auto LoadMnemonic = PPC::LDARX;
10517     auto StoreMnemonic = PPC::STDCX;
10518     switch (MI.getOpcode()) {
10519     default:
10520       llvm_unreachable("Compare and swap of unknown size");
10521     case PPC::ATOMIC_CMP_SWAP_I8:
10522       LoadMnemonic = PPC::LBARX;
10523       StoreMnemonic = PPC::STBCX;
10524       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10525       break;
10526     case PPC::ATOMIC_CMP_SWAP_I16:
10527       LoadMnemonic = PPC::LHARX;
10528       StoreMnemonic = PPC::STHCX;
10529       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10530       break;
10531     case PPC::ATOMIC_CMP_SWAP_I32:
10532       LoadMnemonic = PPC::LWARX;
10533       StoreMnemonic = PPC::STWCX;
10534       break;
10535     case PPC::ATOMIC_CMP_SWAP_I64:
10536       LoadMnemonic = PPC::LDARX;
10537       StoreMnemonic = PPC::STDCX;
10538       break;
10539     }
10540     unsigned dest = MI.getOperand(0).getReg();
10541     unsigned ptrA = MI.getOperand(1).getReg();
10542     unsigned ptrB = MI.getOperand(2).getReg();
10543     unsigned oldval = MI.getOperand(3).getReg();
10544     unsigned newval = MI.getOperand(4).getReg();
10545     DebugLoc dl = MI.getDebugLoc();
10546 
10547     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10548     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10549     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10550     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10551     F->insert(It, loop1MBB);
10552     F->insert(It, loop2MBB);
10553     F->insert(It, midMBB);
10554     F->insert(It, exitMBB);
10555     exitMBB->splice(exitMBB->begin(), BB,
10556                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10557     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10558 
10559     //  thisMBB:
10560     //   ...
10561     //   fallthrough --> loopMBB
10562     BB->addSuccessor(loop1MBB);
10563 
10564     // loop1MBB:
10565     //   l[bhwd]arx dest, ptr
10566     //   cmp[wd] dest, oldval
10567     //   bne- midMBB
10568     // loop2MBB:
10569     //   st[bhwd]cx. newval, ptr
10570     //   bne- loopMBB
10571     //   b exitBB
10572     // midMBB:
10573     //   st[bhwd]cx. dest, ptr
10574     // exitBB:
10575     BB = loop1MBB;
10576     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10577       .addReg(ptrA).addReg(ptrB);
10578     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10579       .addReg(oldval).addReg(dest);
10580     BuildMI(BB, dl, TII->get(PPC::BCC))
10581       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10582     BB->addSuccessor(loop2MBB);
10583     BB->addSuccessor(midMBB);
10584 
10585     BB = loop2MBB;
10586     BuildMI(BB, dl, TII->get(StoreMnemonic))
10587       .addReg(newval).addReg(ptrA).addReg(ptrB);
10588     BuildMI(BB, dl, TII->get(PPC::BCC))
10589       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10590     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10591     BB->addSuccessor(loop1MBB);
10592     BB->addSuccessor(exitMBB);
10593 
10594     BB = midMBB;
10595     BuildMI(BB, dl, TII->get(StoreMnemonic))
10596       .addReg(dest).addReg(ptrA).addReg(ptrB);
10597     BB->addSuccessor(exitMBB);
10598 
10599     //  exitMBB:
10600     //   ...
10601     BB = exitMBB;
10602   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10603              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10604     // We must use 64-bit registers for addresses when targeting 64-bit,
10605     // since we're actually doing arithmetic on them.  Other registers
10606     // can be 32-bit.
10607     bool is64bit = Subtarget.isPPC64();
10608     bool isLittleEndian = Subtarget.isLittleEndian();
10609     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10610 
10611     unsigned dest = MI.getOperand(0).getReg();
10612     unsigned ptrA = MI.getOperand(1).getReg();
10613     unsigned ptrB = MI.getOperand(2).getReg();
10614     unsigned oldval = MI.getOperand(3).getReg();
10615     unsigned newval = MI.getOperand(4).getReg();
10616     DebugLoc dl = MI.getDebugLoc();
10617 
10618     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10619     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10620     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10621     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10622     F->insert(It, loop1MBB);
10623     F->insert(It, loop2MBB);
10624     F->insert(It, midMBB);
10625     F->insert(It, exitMBB);
10626     exitMBB->splice(exitMBB->begin(), BB,
10627                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10628     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10629 
10630     MachineRegisterInfo &RegInfo = F->getRegInfo();
10631     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10632                                             : &PPC::GPRCRegClass;
10633     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10634     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10635     unsigned ShiftReg =
10636       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10637     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10638     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10639     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10640     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10641     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10642     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10643     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10644     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10645     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10646     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10647     unsigned Ptr1Reg;
10648     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10649     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10650     //  thisMBB:
10651     //   ...
10652     //   fallthrough --> loopMBB
10653     BB->addSuccessor(loop1MBB);
10654 
10655     // The 4-byte load must be aligned, while a char or short may be
10656     // anywhere in the word.  Hence all this nasty bookkeeping code.
10657     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10658     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10659     //   xori shift, shift1, 24 [16]
10660     //   rlwinm ptr, ptr1, 0, 0, 29
10661     //   slw newval2, newval, shift
10662     //   slw oldval2, oldval,shift
10663     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10664     //   slw mask, mask2, shift
10665     //   and newval3, newval2, mask
10666     //   and oldval3, oldval2, mask
10667     // loop1MBB:
10668     //   lwarx tmpDest, ptr
10669     //   and tmp, tmpDest, mask
10670     //   cmpw tmp, oldval3
10671     //   bne- midMBB
10672     // loop2MBB:
10673     //   andc tmp2, tmpDest, mask
10674     //   or tmp4, tmp2, newval3
10675     //   stwcx. tmp4, ptr
10676     //   bne- loop1MBB
10677     //   b exitBB
10678     // midMBB:
10679     //   stwcx. tmpDest, ptr
10680     // exitBB:
10681     //   srw dest, tmpDest, shift
10682     if (ptrA != ZeroReg) {
10683       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10684       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10685         .addReg(ptrA).addReg(ptrB);
10686     } else {
10687       Ptr1Reg = ptrB;
10688     }
10689     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10690         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10691     if (!isLittleEndian)
10692       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10693           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10694     if (is64bit)
10695       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10696         .addReg(Ptr1Reg).addImm(0).addImm(61);
10697     else
10698       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10699         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10700     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10701         .addReg(newval).addReg(ShiftReg);
10702     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10703         .addReg(oldval).addReg(ShiftReg);
10704     if (is8bit)
10705       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10706     else {
10707       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10708       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10709         .addReg(Mask3Reg).addImm(65535);
10710     }
10711     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10712         .addReg(Mask2Reg).addReg(ShiftReg);
10713     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10714         .addReg(NewVal2Reg).addReg(MaskReg);
10715     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10716         .addReg(OldVal2Reg).addReg(MaskReg);
10717 
10718     BB = loop1MBB;
10719     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10720         .addReg(ZeroReg).addReg(PtrReg);
10721     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10722         .addReg(TmpDestReg).addReg(MaskReg);
10723     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10724         .addReg(TmpReg).addReg(OldVal3Reg);
10725     BuildMI(BB, dl, TII->get(PPC::BCC))
10726         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10727     BB->addSuccessor(loop2MBB);
10728     BB->addSuccessor(midMBB);
10729 
10730     BB = loop2MBB;
10731     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10732         .addReg(TmpDestReg).addReg(MaskReg);
10733     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10734         .addReg(Tmp2Reg).addReg(NewVal3Reg);
10735     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10736         .addReg(ZeroReg).addReg(PtrReg);
10737     BuildMI(BB, dl, TII->get(PPC::BCC))
10738       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10739     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10740     BB->addSuccessor(loop1MBB);
10741     BB->addSuccessor(exitMBB);
10742 
10743     BB = midMBB;
10744     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10745       .addReg(ZeroReg).addReg(PtrReg);
10746     BB->addSuccessor(exitMBB);
10747 
10748     //  exitMBB:
10749     //   ...
10750     BB = exitMBB;
10751     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10752       .addReg(ShiftReg);
10753   } else if (MI.getOpcode() == PPC::FADDrtz) {
10754     // This pseudo performs an FADD with rounding mode temporarily forced
10755     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10756     // is not modeled at the SelectionDAG level.
10757     unsigned Dest = MI.getOperand(0).getReg();
10758     unsigned Src1 = MI.getOperand(1).getReg();
10759     unsigned Src2 = MI.getOperand(2).getReg();
10760     DebugLoc dl = MI.getDebugLoc();
10761 
10762     MachineRegisterInfo &RegInfo = F->getRegInfo();
10763     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10764 
10765     // Save FPSCR value.
10766     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10767 
10768     // Set rounding mode to round-to-zero.
10769     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10770     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10771 
10772     // Perform addition.
10773     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10774 
10775     // Restore FPSCR value.
10776     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10777   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10778              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10779              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10780              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10781     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10782                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10783                           ? PPC::ANDIo8
10784                           : PPC::ANDIo;
10785     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10786                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10787 
10788     MachineRegisterInfo &RegInfo = F->getRegInfo();
10789     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10790                                                   &PPC::GPRCRegClass :
10791                                                   &PPC::G8RCRegClass);
10792 
10793     DebugLoc dl = MI.getDebugLoc();
10794     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10795         .addReg(MI.getOperand(1).getReg())
10796         .addImm(1);
10797     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10798             MI.getOperand(0).getReg())
10799         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10800   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10801     DebugLoc Dl = MI.getDebugLoc();
10802     MachineRegisterInfo &RegInfo = F->getRegInfo();
10803     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10804     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10805     return BB;
10806   } else {
10807     llvm_unreachable("Unexpected instr type to insert");
10808   }
10809 
10810   MI.eraseFromParent(); // The pseudo instruction is gone now.
10811   return BB;
10812 }
10813 
10814 //===----------------------------------------------------------------------===//
10815 // Target Optimization Hooks
10816 //===----------------------------------------------------------------------===//
10817 
10818 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10819   // For the estimates, convergence is quadratic, so we essentially double the
10820   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10821   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10822   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10823   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10824   if (VT.getScalarType() == MVT::f64)
10825     RefinementSteps++;
10826   return RefinementSteps;
10827 }
10828 
10829 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10830                                            int Enabled, int &RefinementSteps,
10831                                            bool &UseOneConstNR,
10832                                            bool Reciprocal) const {
10833   EVT VT = Operand.getValueType();
10834   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10835       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10836       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10837       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10838       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10839       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10840     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10841       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10842 
10843     UseOneConstNR = true;
10844     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10845   }
10846   return SDValue();
10847 }
10848 
10849 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10850                                             int Enabled,
10851                                             int &RefinementSteps) const {
10852   EVT VT = Operand.getValueType();
10853   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10854       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10855       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10856       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10857       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10858       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10859     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10860       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10861     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10862   }
10863   return SDValue();
10864 }
10865 
10866 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10867   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10868   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10869   // enabled for division), this functionality is redundant with the default
10870   // combiner logic (once the division -> reciprocal/multiply transformation
10871   // has taken place). As a result, this matters more for older cores than for
10872   // newer ones.
10873 
10874   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10875   // reciprocal if there are two or more FDIVs (for embedded cores with only
10876   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10877   switch (Subtarget.getDarwinDirective()) {
10878   default:
10879     return 3;
10880   case PPC::DIR_440:
10881   case PPC::DIR_A2:
10882   case PPC::DIR_E500:
10883   case PPC::DIR_E500mc:
10884   case PPC::DIR_E5500:
10885     return 2;
10886   }
10887 }
10888 
10889 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10890 // collapsed, and so we need to look through chains of them.
10891 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10892                                      int64_t& Offset, SelectionDAG &DAG) {
10893   if (DAG.isBaseWithConstantOffset(Loc)) {
10894     Base = Loc.getOperand(0);
10895     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10896 
10897     // The base might itself be a base plus an offset, and if so, accumulate
10898     // that as well.
10899     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10900   }
10901 }
10902 
10903 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10904                             unsigned Bytes, int Dist,
10905                             SelectionDAG &DAG) {
10906   if (VT.getSizeInBits() / 8 != Bytes)
10907     return false;
10908 
10909   SDValue BaseLoc = Base->getBasePtr();
10910   if (Loc.getOpcode() == ISD::FrameIndex) {
10911     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10912       return false;
10913     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10914     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10915     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10916     int FS  = MFI.getObjectSize(FI);
10917     int BFS = MFI.getObjectSize(BFI);
10918     if (FS != BFS || FS != (int)Bytes) return false;
10919     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10920   }
10921 
10922   SDValue Base1 = Loc, Base2 = BaseLoc;
10923   int64_t Offset1 = 0, Offset2 = 0;
10924   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10925   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10926   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10927     return true;
10928 
10929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10930   const GlobalValue *GV1 = nullptr;
10931   const GlobalValue *GV2 = nullptr;
10932   Offset1 = 0;
10933   Offset2 = 0;
10934   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10935   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10936   if (isGA1 && isGA2 && GV1 == GV2)
10937     return Offset1 == (Offset2 + Dist*Bytes);
10938   return false;
10939 }
10940 
10941 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10942 // not enforce equality of the chain operands.
10943 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10944                             unsigned Bytes, int Dist,
10945                             SelectionDAG &DAG) {
10946   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10947     EVT VT = LS->getMemoryVT();
10948     SDValue Loc = LS->getBasePtr();
10949     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10950   }
10951 
10952   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10953     EVT VT;
10954     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10955     default: return false;
10956     case Intrinsic::ppc_qpx_qvlfd:
10957     case Intrinsic::ppc_qpx_qvlfda:
10958       VT = MVT::v4f64;
10959       break;
10960     case Intrinsic::ppc_qpx_qvlfs:
10961     case Intrinsic::ppc_qpx_qvlfsa:
10962       VT = MVT::v4f32;
10963       break;
10964     case Intrinsic::ppc_qpx_qvlfcd:
10965     case Intrinsic::ppc_qpx_qvlfcda:
10966       VT = MVT::v2f64;
10967       break;
10968     case Intrinsic::ppc_qpx_qvlfcs:
10969     case Intrinsic::ppc_qpx_qvlfcsa:
10970       VT = MVT::v2f32;
10971       break;
10972     case Intrinsic::ppc_qpx_qvlfiwa:
10973     case Intrinsic::ppc_qpx_qvlfiwz:
10974     case Intrinsic::ppc_altivec_lvx:
10975     case Intrinsic::ppc_altivec_lvxl:
10976     case Intrinsic::ppc_vsx_lxvw4x:
10977     case Intrinsic::ppc_vsx_lxvw4x_be:
10978       VT = MVT::v4i32;
10979       break;
10980     case Intrinsic::ppc_vsx_lxvd2x:
10981     case Intrinsic::ppc_vsx_lxvd2x_be:
10982       VT = MVT::v2f64;
10983       break;
10984     case Intrinsic::ppc_altivec_lvebx:
10985       VT = MVT::i8;
10986       break;
10987     case Intrinsic::ppc_altivec_lvehx:
10988       VT = MVT::i16;
10989       break;
10990     case Intrinsic::ppc_altivec_lvewx:
10991       VT = MVT::i32;
10992       break;
10993     }
10994 
10995     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10996   }
10997 
10998   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10999     EVT VT;
11000     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11001     default: return false;
11002     case Intrinsic::ppc_qpx_qvstfd:
11003     case Intrinsic::ppc_qpx_qvstfda:
11004       VT = MVT::v4f64;
11005       break;
11006     case Intrinsic::ppc_qpx_qvstfs:
11007     case Intrinsic::ppc_qpx_qvstfsa:
11008       VT = MVT::v4f32;
11009       break;
11010     case Intrinsic::ppc_qpx_qvstfcd:
11011     case Intrinsic::ppc_qpx_qvstfcda:
11012       VT = MVT::v2f64;
11013       break;
11014     case Intrinsic::ppc_qpx_qvstfcs:
11015     case Intrinsic::ppc_qpx_qvstfcsa:
11016       VT = MVT::v2f32;
11017       break;
11018     case Intrinsic::ppc_qpx_qvstfiw:
11019     case Intrinsic::ppc_qpx_qvstfiwa:
11020     case Intrinsic::ppc_altivec_stvx:
11021     case Intrinsic::ppc_altivec_stvxl:
11022     case Intrinsic::ppc_vsx_stxvw4x:
11023       VT = MVT::v4i32;
11024       break;
11025     case Intrinsic::ppc_vsx_stxvd2x:
11026       VT = MVT::v2f64;
11027       break;
11028     case Intrinsic::ppc_vsx_stxvw4x_be:
11029       VT = MVT::v4i32;
11030       break;
11031     case Intrinsic::ppc_vsx_stxvd2x_be:
11032       VT = MVT::v2f64;
11033       break;
11034     case Intrinsic::ppc_altivec_stvebx:
11035       VT = MVT::i8;
11036       break;
11037     case Intrinsic::ppc_altivec_stvehx:
11038       VT = MVT::i16;
11039       break;
11040     case Intrinsic::ppc_altivec_stvewx:
11041       VT = MVT::i32;
11042       break;
11043     }
11044 
11045     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11046   }
11047 
11048   return false;
11049 }
11050 
11051 // Return true is there is a nearyby consecutive load to the one provided
11052 // (regardless of alignment). We search up and down the chain, looking though
11053 // token factors and other loads (but nothing else). As a result, a true result
11054 // indicates that it is safe to create a new consecutive load adjacent to the
11055 // load provided.
11056 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11057   SDValue Chain = LD->getChain();
11058   EVT VT = LD->getMemoryVT();
11059 
11060   SmallSet<SDNode *, 16> LoadRoots;
11061   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11062   SmallSet<SDNode *, 16> Visited;
11063 
11064   // First, search up the chain, branching to follow all token-factor operands.
11065   // If we find a consecutive load, then we're done, otherwise, record all
11066   // nodes just above the top-level loads and token factors.
11067   while (!Queue.empty()) {
11068     SDNode *ChainNext = Queue.pop_back_val();
11069     if (!Visited.insert(ChainNext).second)
11070       continue;
11071 
11072     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11073       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11074         return true;
11075 
11076       if (!Visited.count(ChainLD->getChain().getNode()))
11077         Queue.push_back(ChainLD->getChain().getNode());
11078     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11079       for (const SDUse &O : ChainNext->ops())
11080         if (!Visited.count(O.getNode()))
11081           Queue.push_back(O.getNode());
11082     } else
11083       LoadRoots.insert(ChainNext);
11084   }
11085 
11086   // Second, search down the chain, starting from the top-level nodes recorded
11087   // in the first phase. These top-level nodes are the nodes just above all
11088   // loads and token factors. Starting with their uses, recursively look though
11089   // all loads (just the chain uses) and token factors to find a consecutive
11090   // load.
11091   Visited.clear();
11092   Queue.clear();
11093 
11094   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11095        IE = LoadRoots.end(); I != IE; ++I) {
11096     Queue.push_back(*I);
11097 
11098     while (!Queue.empty()) {
11099       SDNode *LoadRoot = Queue.pop_back_val();
11100       if (!Visited.insert(LoadRoot).second)
11101         continue;
11102 
11103       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11104         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11105           return true;
11106 
11107       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11108            UE = LoadRoot->use_end(); UI != UE; ++UI)
11109         if (((isa<MemSDNode>(*UI) &&
11110             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11111             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11112           Queue.push_back(*UI);
11113     }
11114   }
11115 
11116   return false;
11117 }
11118 
11119 /// This function is called when we have proved that a SETCC node can be replaced
11120 /// by subtraction (and other supporting instructions) so that the result of
11121 /// comparison is kept in a GPR instead of CR. This function is purely for
11122 /// codegen purposes and has some flags to guide the codegen process.
11123 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11124                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11125   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11126 
11127   // Zero extend the operands to the largest legal integer. Originally, they
11128   // must be of a strictly smaller size.
11129   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11130                          DAG.getConstant(Size, DL, MVT::i32));
11131   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11132                          DAG.getConstant(Size, DL, MVT::i32));
11133 
11134   // Swap if needed. Depends on the condition code.
11135   if (Swap)
11136     std::swap(Op0, Op1);
11137 
11138   // Subtract extended integers.
11139   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11140 
11141   // Move the sign bit to the least significant position and zero out the rest.
11142   // Now the least significant bit carries the result of original comparison.
11143   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11144                              DAG.getConstant(Size - 1, DL, MVT::i32));
11145   auto Final = Shifted;
11146 
11147   // Complement the result if needed. Based on the condition code.
11148   if (Complement)
11149     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11150                         DAG.getConstant(1, DL, MVT::i64));
11151 
11152   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11153 }
11154 
11155 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11156                                                   DAGCombinerInfo &DCI) const {
11157   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11158 
11159   SelectionDAG &DAG = DCI.DAG;
11160   SDLoc DL(N);
11161 
11162   // Size of integers being compared has a critical role in the following
11163   // analysis, so we prefer to do this when all types are legal.
11164   if (!DCI.isAfterLegalizeDAG())
11165     return SDValue();
11166 
11167   // If all users of SETCC extend its value to a legal integer type
11168   // then we replace SETCC with a subtraction
11169   for (SDNode::use_iterator UI = N->use_begin(),
11170        UE = N->use_end(); UI != UE; ++UI) {
11171     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11172       return SDValue();
11173   }
11174 
11175   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11176   auto OpSize = N->getOperand(0).getValueSizeInBits();
11177 
11178   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11179 
11180   if (OpSize < Size) {
11181     switch (CC) {
11182     default: break;
11183     case ISD::SETULT:
11184       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11185     case ISD::SETULE:
11186       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11187     case ISD::SETUGT:
11188       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11189     case ISD::SETUGE:
11190       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11191     }
11192   }
11193 
11194   return SDValue();
11195 }
11196 
11197 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11198                                                   DAGCombinerInfo &DCI) const {
11199   SelectionDAG &DAG = DCI.DAG;
11200   SDLoc dl(N);
11201 
11202   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11203   // If we're tracking CR bits, we need to be careful that we don't have:
11204   //   trunc(binary-ops(zext(x), zext(y)))
11205   // or
11206   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11207   // such that we're unnecessarily moving things into GPRs when it would be
11208   // better to keep them in CR bits.
11209 
11210   // Note that trunc here can be an actual i1 trunc, or can be the effective
11211   // truncation that comes from a setcc or select_cc.
11212   if (N->getOpcode() == ISD::TRUNCATE &&
11213       N->getValueType(0) != MVT::i1)
11214     return SDValue();
11215 
11216   if (N->getOperand(0).getValueType() != MVT::i32 &&
11217       N->getOperand(0).getValueType() != MVT::i64)
11218     return SDValue();
11219 
11220   if (N->getOpcode() == ISD::SETCC ||
11221       N->getOpcode() == ISD::SELECT_CC) {
11222     // If we're looking at a comparison, then we need to make sure that the
11223     // high bits (all except for the first) don't matter the result.
11224     ISD::CondCode CC =
11225       cast<CondCodeSDNode>(N->getOperand(
11226         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11227     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11228 
11229     if (ISD::isSignedIntSetCC(CC)) {
11230       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11231           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11232         return SDValue();
11233     } else if (ISD::isUnsignedIntSetCC(CC)) {
11234       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11235                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11236           !DAG.MaskedValueIsZero(N->getOperand(1),
11237                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11238         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11239                                              : SDValue());
11240     } else {
11241       // This is neither a signed nor an unsigned comparison, just make sure
11242       // that the high bits are equal.
11243       KnownBits Op1Known, Op2Known;
11244       DAG.computeKnownBits(N->getOperand(0), Op1Known);
11245       DAG.computeKnownBits(N->getOperand(1), Op2Known);
11246 
11247       // We don't really care about what is known about the first bit (if
11248       // anything), so clear it in all masks prior to comparing them.
11249       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11250       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11251 
11252       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11253         return SDValue();
11254     }
11255   }
11256 
11257   // We now know that the higher-order bits are irrelevant, we just need to
11258   // make sure that all of the intermediate operations are bit operations, and
11259   // all inputs are extensions.
11260   if (N->getOperand(0).getOpcode() != ISD::AND &&
11261       N->getOperand(0).getOpcode() != ISD::OR  &&
11262       N->getOperand(0).getOpcode() != ISD::XOR &&
11263       N->getOperand(0).getOpcode() != ISD::SELECT &&
11264       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11265       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11266       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11267       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11268       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11269     return SDValue();
11270 
11271   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11272       N->getOperand(1).getOpcode() != ISD::AND &&
11273       N->getOperand(1).getOpcode() != ISD::OR  &&
11274       N->getOperand(1).getOpcode() != ISD::XOR &&
11275       N->getOperand(1).getOpcode() != ISD::SELECT &&
11276       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11277       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11278       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11279       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11280       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11281     return SDValue();
11282 
11283   SmallVector<SDValue, 4> Inputs;
11284   SmallVector<SDValue, 8> BinOps, PromOps;
11285   SmallPtrSet<SDNode *, 16> Visited;
11286 
11287   for (unsigned i = 0; i < 2; ++i) {
11288     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11289           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11290           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11291           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11292         isa<ConstantSDNode>(N->getOperand(i)))
11293       Inputs.push_back(N->getOperand(i));
11294     else
11295       BinOps.push_back(N->getOperand(i));
11296 
11297     if (N->getOpcode() == ISD::TRUNCATE)
11298       break;
11299   }
11300 
11301   // Visit all inputs, collect all binary operations (and, or, xor and
11302   // select) that are all fed by extensions.
11303   while (!BinOps.empty()) {
11304     SDValue BinOp = BinOps.back();
11305     BinOps.pop_back();
11306 
11307     if (!Visited.insert(BinOp.getNode()).second)
11308       continue;
11309 
11310     PromOps.push_back(BinOp);
11311 
11312     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11313       // The condition of the select is not promoted.
11314       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11315         continue;
11316       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11317         continue;
11318 
11319       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11320             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11321             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11322            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11323           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11324         Inputs.push_back(BinOp.getOperand(i));
11325       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11326                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11327                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11328                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11329                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11330                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11331                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11332                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11333                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11334         BinOps.push_back(BinOp.getOperand(i));
11335       } else {
11336         // We have an input that is not an extension or another binary
11337         // operation; we'll abort this transformation.
11338         return SDValue();
11339       }
11340     }
11341   }
11342 
11343   // Make sure that this is a self-contained cluster of operations (which
11344   // is not quite the same thing as saying that everything has only one
11345   // use).
11346   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11347     if (isa<ConstantSDNode>(Inputs[i]))
11348       continue;
11349 
11350     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11351                               UE = Inputs[i].getNode()->use_end();
11352          UI != UE; ++UI) {
11353       SDNode *User = *UI;
11354       if (User != N && !Visited.count(User))
11355         return SDValue();
11356 
11357       // Make sure that we're not going to promote the non-output-value
11358       // operand(s) or SELECT or SELECT_CC.
11359       // FIXME: Although we could sometimes handle this, and it does occur in
11360       // practice that one of the condition inputs to the select is also one of
11361       // the outputs, we currently can't deal with this.
11362       if (User->getOpcode() == ISD::SELECT) {
11363         if (User->getOperand(0) == Inputs[i])
11364           return SDValue();
11365       } else if (User->getOpcode() == ISD::SELECT_CC) {
11366         if (User->getOperand(0) == Inputs[i] ||
11367             User->getOperand(1) == Inputs[i])
11368           return SDValue();
11369       }
11370     }
11371   }
11372 
11373   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11374     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11375                               UE = PromOps[i].getNode()->use_end();
11376          UI != UE; ++UI) {
11377       SDNode *User = *UI;
11378       if (User != N && !Visited.count(User))
11379         return SDValue();
11380 
11381       // Make sure that we're not going to promote the non-output-value
11382       // operand(s) or SELECT or SELECT_CC.
11383       // FIXME: Although we could sometimes handle this, and it does occur in
11384       // practice that one of the condition inputs to the select is also one of
11385       // the outputs, we currently can't deal with this.
11386       if (User->getOpcode() == ISD::SELECT) {
11387         if (User->getOperand(0) == PromOps[i])
11388           return SDValue();
11389       } else if (User->getOpcode() == ISD::SELECT_CC) {
11390         if (User->getOperand(0) == PromOps[i] ||
11391             User->getOperand(1) == PromOps[i])
11392           return SDValue();
11393       }
11394     }
11395   }
11396 
11397   // Replace all inputs with the extension operand.
11398   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11399     // Constants may have users outside the cluster of to-be-promoted nodes,
11400     // and so we need to replace those as we do the promotions.
11401     if (isa<ConstantSDNode>(Inputs[i]))
11402       continue;
11403     else
11404       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11405   }
11406 
11407   std::list<HandleSDNode> PromOpHandles;
11408   for (auto &PromOp : PromOps)
11409     PromOpHandles.emplace_back(PromOp);
11410 
11411   // Replace all operations (these are all the same, but have a different
11412   // (i1) return type). DAG.getNode will validate that the types of
11413   // a binary operator match, so go through the list in reverse so that
11414   // we've likely promoted both operands first. Any intermediate truncations or
11415   // extensions disappear.
11416   while (!PromOpHandles.empty()) {
11417     SDValue PromOp = PromOpHandles.back().getValue();
11418     PromOpHandles.pop_back();
11419 
11420     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11421         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11422         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11423         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11424       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11425           PromOp.getOperand(0).getValueType() != MVT::i1) {
11426         // The operand is not yet ready (see comment below).
11427         PromOpHandles.emplace_front(PromOp);
11428         continue;
11429       }
11430 
11431       SDValue RepValue = PromOp.getOperand(0);
11432       if (isa<ConstantSDNode>(RepValue))
11433         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11434 
11435       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11436       continue;
11437     }
11438 
11439     unsigned C;
11440     switch (PromOp.getOpcode()) {
11441     default:             C = 0; break;
11442     case ISD::SELECT:    C = 1; break;
11443     case ISD::SELECT_CC: C = 2; break;
11444     }
11445 
11446     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11447          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11448         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11449          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11450       // The to-be-promoted operands of this node have not yet been
11451       // promoted (this should be rare because we're going through the
11452       // list backward, but if one of the operands has several users in
11453       // this cluster of to-be-promoted nodes, it is possible).
11454       PromOpHandles.emplace_front(PromOp);
11455       continue;
11456     }
11457 
11458     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11459                                 PromOp.getNode()->op_end());
11460 
11461     // If there are any constant inputs, make sure they're replaced now.
11462     for (unsigned i = 0; i < 2; ++i)
11463       if (isa<ConstantSDNode>(Ops[C+i]))
11464         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11465 
11466     DAG.ReplaceAllUsesOfValueWith(PromOp,
11467       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11468   }
11469 
11470   // Now we're left with the initial truncation itself.
11471   if (N->getOpcode() == ISD::TRUNCATE)
11472     return N->getOperand(0);
11473 
11474   // Otherwise, this is a comparison. The operands to be compared have just
11475   // changed type (to i1), but everything else is the same.
11476   return SDValue(N, 0);
11477 }
11478 
11479 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11480                                                   DAGCombinerInfo &DCI) const {
11481   SelectionDAG &DAG = DCI.DAG;
11482   SDLoc dl(N);
11483 
11484   // If we're tracking CR bits, we need to be careful that we don't have:
11485   //   zext(binary-ops(trunc(x), trunc(y)))
11486   // or
11487   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11488   // such that we're unnecessarily moving things into CR bits that can more
11489   // efficiently stay in GPRs. Note that if we're not certain that the high
11490   // bits are set as required by the final extension, we still may need to do
11491   // some masking to get the proper behavior.
11492 
11493   // This same functionality is important on PPC64 when dealing with
11494   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11495   // the return values of functions. Because it is so similar, it is handled
11496   // here as well.
11497 
11498   if (N->getValueType(0) != MVT::i32 &&
11499       N->getValueType(0) != MVT::i64)
11500     return SDValue();
11501 
11502   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11503         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11504     return SDValue();
11505 
11506   if (N->getOperand(0).getOpcode() != ISD::AND &&
11507       N->getOperand(0).getOpcode() != ISD::OR  &&
11508       N->getOperand(0).getOpcode() != ISD::XOR &&
11509       N->getOperand(0).getOpcode() != ISD::SELECT &&
11510       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11511     return SDValue();
11512 
11513   SmallVector<SDValue, 4> Inputs;
11514   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11515   SmallPtrSet<SDNode *, 16> Visited;
11516 
11517   // Visit all inputs, collect all binary operations (and, or, xor and
11518   // select) that are all fed by truncations.
11519   while (!BinOps.empty()) {
11520     SDValue BinOp = BinOps.back();
11521     BinOps.pop_back();
11522 
11523     if (!Visited.insert(BinOp.getNode()).second)
11524       continue;
11525 
11526     PromOps.push_back(BinOp);
11527 
11528     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11529       // The condition of the select is not promoted.
11530       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11531         continue;
11532       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11533         continue;
11534 
11535       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11536           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11537         Inputs.push_back(BinOp.getOperand(i));
11538       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11539                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11540                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11541                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11542                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11543         BinOps.push_back(BinOp.getOperand(i));
11544       } else {
11545         // We have an input that is not a truncation or another binary
11546         // operation; we'll abort this transformation.
11547         return SDValue();
11548       }
11549     }
11550   }
11551 
11552   // The operands of a select that must be truncated when the select is
11553   // promoted because the operand is actually part of the to-be-promoted set.
11554   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11555 
11556   // Make sure that this is a self-contained cluster of operations (which
11557   // is not quite the same thing as saying that everything has only one
11558   // use).
11559   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11560     if (isa<ConstantSDNode>(Inputs[i]))
11561       continue;
11562 
11563     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11564                               UE = Inputs[i].getNode()->use_end();
11565          UI != UE; ++UI) {
11566       SDNode *User = *UI;
11567       if (User != N && !Visited.count(User))
11568         return SDValue();
11569 
11570       // If we're going to promote the non-output-value operand(s) or SELECT or
11571       // SELECT_CC, record them for truncation.
11572       if (User->getOpcode() == ISD::SELECT) {
11573         if (User->getOperand(0) == Inputs[i])
11574           SelectTruncOp[0].insert(std::make_pair(User,
11575                                     User->getOperand(0).getValueType()));
11576       } else if (User->getOpcode() == ISD::SELECT_CC) {
11577         if (User->getOperand(0) == Inputs[i])
11578           SelectTruncOp[0].insert(std::make_pair(User,
11579                                     User->getOperand(0).getValueType()));
11580         if (User->getOperand(1) == Inputs[i])
11581           SelectTruncOp[1].insert(std::make_pair(User,
11582                                     User->getOperand(1).getValueType()));
11583       }
11584     }
11585   }
11586 
11587   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11588     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11589                               UE = PromOps[i].getNode()->use_end();
11590          UI != UE; ++UI) {
11591       SDNode *User = *UI;
11592       if (User != N && !Visited.count(User))
11593         return SDValue();
11594 
11595       // If we're going to promote the non-output-value operand(s) or SELECT or
11596       // SELECT_CC, record them for truncation.
11597       if (User->getOpcode() == ISD::SELECT) {
11598         if (User->getOperand(0) == PromOps[i])
11599           SelectTruncOp[0].insert(std::make_pair(User,
11600                                     User->getOperand(0).getValueType()));
11601       } else if (User->getOpcode() == ISD::SELECT_CC) {
11602         if (User->getOperand(0) == PromOps[i])
11603           SelectTruncOp[0].insert(std::make_pair(User,
11604                                     User->getOperand(0).getValueType()));
11605         if (User->getOperand(1) == PromOps[i])
11606           SelectTruncOp[1].insert(std::make_pair(User,
11607                                     User->getOperand(1).getValueType()));
11608       }
11609     }
11610   }
11611 
11612   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11613   bool ReallyNeedsExt = false;
11614   if (N->getOpcode() != ISD::ANY_EXTEND) {
11615     // If all of the inputs are not already sign/zero extended, then
11616     // we'll still need to do that at the end.
11617     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11618       if (isa<ConstantSDNode>(Inputs[i]))
11619         continue;
11620 
11621       unsigned OpBits =
11622         Inputs[i].getOperand(0).getValueSizeInBits();
11623       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11624 
11625       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11626            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11627                                   APInt::getHighBitsSet(OpBits,
11628                                                         OpBits-PromBits))) ||
11629           (N->getOpcode() == ISD::SIGN_EXTEND &&
11630            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11631              (OpBits-(PromBits-1)))) {
11632         ReallyNeedsExt = true;
11633         break;
11634       }
11635     }
11636   }
11637 
11638   // Replace all inputs, either with the truncation operand, or a
11639   // truncation or extension to the final output type.
11640   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11641     // Constant inputs need to be replaced with the to-be-promoted nodes that
11642     // use them because they might have users outside of the cluster of
11643     // promoted nodes.
11644     if (isa<ConstantSDNode>(Inputs[i]))
11645       continue;
11646 
11647     SDValue InSrc = Inputs[i].getOperand(0);
11648     if (Inputs[i].getValueType() == N->getValueType(0))
11649       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11650     else if (N->getOpcode() == ISD::SIGN_EXTEND)
11651       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11652         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11653     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11654       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11655         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11656     else
11657       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11658         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11659   }
11660 
11661   std::list<HandleSDNode> PromOpHandles;
11662   for (auto &PromOp : PromOps)
11663     PromOpHandles.emplace_back(PromOp);
11664 
11665   // Replace all operations (these are all the same, but have a different
11666   // (promoted) return type). DAG.getNode will validate that the types of
11667   // a binary operator match, so go through the list in reverse so that
11668   // we've likely promoted both operands first.
11669   while (!PromOpHandles.empty()) {
11670     SDValue PromOp = PromOpHandles.back().getValue();
11671     PromOpHandles.pop_back();
11672 
11673     unsigned C;
11674     switch (PromOp.getOpcode()) {
11675     default:             C = 0; break;
11676     case ISD::SELECT:    C = 1; break;
11677     case ISD::SELECT_CC: C = 2; break;
11678     }
11679 
11680     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11681          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11682         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11683          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11684       // The to-be-promoted operands of this node have not yet been
11685       // promoted (this should be rare because we're going through the
11686       // list backward, but if one of the operands has several users in
11687       // this cluster of to-be-promoted nodes, it is possible).
11688       PromOpHandles.emplace_front(PromOp);
11689       continue;
11690     }
11691 
11692     // For SELECT and SELECT_CC nodes, we do a similar check for any
11693     // to-be-promoted comparison inputs.
11694     if (PromOp.getOpcode() == ISD::SELECT ||
11695         PromOp.getOpcode() == ISD::SELECT_CC) {
11696       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11697            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11698           (SelectTruncOp[1].count(PromOp.getNode()) &&
11699            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11700         PromOpHandles.emplace_front(PromOp);
11701         continue;
11702       }
11703     }
11704 
11705     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11706                                 PromOp.getNode()->op_end());
11707 
11708     // If this node has constant inputs, then they'll need to be promoted here.
11709     for (unsigned i = 0; i < 2; ++i) {
11710       if (!isa<ConstantSDNode>(Ops[C+i]))
11711         continue;
11712       if (Ops[C+i].getValueType() == N->getValueType(0))
11713         continue;
11714 
11715       if (N->getOpcode() == ISD::SIGN_EXTEND)
11716         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11717       else if (N->getOpcode() == ISD::ZERO_EXTEND)
11718         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11719       else
11720         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11721     }
11722 
11723     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11724     // truncate them again to the original value type.
11725     if (PromOp.getOpcode() == ISD::SELECT ||
11726         PromOp.getOpcode() == ISD::SELECT_CC) {
11727       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11728       if (SI0 != SelectTruncOp[0].end())
11729         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11730       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11731       if (SI1 != SelectTruncOp[1].end())
11732         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11733     }
11734 
11735     DAG.ReplaceAllUsesOfValueWith(PromOp,
11736       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11737   }
11738 
11739   // Now we're left with the initial extension itself.
11740   if (!ReallyNeedsExt)
11741     return N->getOperand(0);
11742 
11743   // To zero extend, just mask off everything except for the first bit (in the
11744   // i1 case).
11745   if (N->getOpcode() == ISD::ZERO_EXTEND)
11746     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11747                        DAG.getConstant(APInt::getLowBitsSet(
11748                                          N->getValueSizeInBits(0), PromBits),
11749                                        dl, N->getValueType(0)));
11750 
11751   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11752          "Invalid extension type");
11753   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11754   SDValue ShiftCst =
11755       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11756   return DAG.getNode(
11757       ISD::SRA, dl, N->getValueType(0),
11758       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11759       ShiftCst);
11760 }
11761 
11762 /// Reduces the number of fp-to-int conversion when building a vector.
11763 ///
11764 /// If this vector is built out of floating to integer conversions,
11765 /// transform it to a vector built out of floating point values followed by a
11766 /// single floating to integer conversion of the vector.
11767 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
11768 /// becomes (fptosi (build_vector ($A, $B, ...)))
11769 SDValue PPCTargetLowering::
11770 combineElementTruncationToVectorTruncation(SDNode *N,
11771                                            DAGCombinerInfo &DCI) const {
11772   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11773          "Should be called with a BUILD_VECTOR node");
11774 
11775   SelectionDAG &DAG = DCI.DAG;
11776   SDLoc dl(N);
11777 
11778   SDValue FirstInput = N->getOperand(0);
11779   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11780          "The input operand must be an fp-to-int conversion.");
11781 
11782   // This combine happens after legalization so the fp_to_[su]i nodes are
11783   // already converted to PPCSISD nodes.
11784   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11785   if (FirstConversion == PPCISD::FCTIDZ ||
11786       FirstConversion == PPCISD::FCTIDUZ ||
11787       FirstConversion == PPCISD::FCTIWZ ||
11788       FirstConversion == PPCISD::FCTIWUZ) {
11789     bool IsSplat = true;
11790     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11791       FirstConversion == PPCISD::FCTIWUZ;
11792     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11793     SmallVector<SDValue, 4> Ops;
11794     EVT TargetVT = N->getValueType(0);
11795     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11796       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11797         return SDValue();
11798       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11799       if (NextConversion != FirstConversion)
11800         return SDValue();
11801       if (N->getOperand(i) != FirstInput)
11802         IsSplat = false;
11803     }
11804 
11805     // If this is a splat, we leave it as-is since there will be only a single
11806     // fp-to-int conversion followed by a splat of the integer. This is better
11807     // for 32-bit and smaller ints and neutral for 64-bit ints.
11808     if (IsSplat)
11809       return SDValue();
11810 
11811     // Now that we know we have the right type of node, get its operands
11812     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11813       SDValue In = N->getOperand(i).getOperand(0);
11814       // For 32-bit values, we need to add an FP_ROUND node.
11815       if (Is32Bit) {
11816         if (In.isUndef())
11817           Ops.push_back(DAG.getUNDEF(SrcVT));
11818         else {
11819           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11820                                       MVT::f32, In.getOperand(0),
11821                                       DAG.getIntPtrConstant(1, dl));
11822           Ops.push_back(Trunc);
11823         }
11824       } else
11825         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11826     }
11827 
11828     unsigned Opcode;
11829     if (FirstConversion == PPCISD::FCTIDZ ||
11830         FirstConversion == PPCISD::FCTIWZ)
11831       Opcode = ISD::FP_TO_SINT;
11832     else
11833       Opcode = ISD::FP_TO_UINT;
11834 
11835     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11836     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11837     return DAG.getNode(Opcode, dl, TargetVT, BV);
11838   }
11839   return SDValue();
11840 }
11841 
11842 /// Reduce the number of loads when building a vector.
11843 ///
11844 /// Building a vector out of multiple loads can be converted to a load
11845 /// of the vector type if the loads are consecutive. If the loads are
11846 /// consecutive but in descending order, a shuffle is added at the end
11847 /// to reorder the vector.
11848 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11849   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11850          "Should be called with a BUILD_VECTOR node");
11851 
11852   SDLoc dl(N);
11853   bool InputsAreConsecutiveLoads = true;
11854   bool InputsAreReverseConsecutive = true;
11855   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11856   SDValue FirstInput = N->getOperand(0);
11857   bool IsRoundOfExtLoad = false;
11858 
11859   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11860       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11861     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11862     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11863   }
11864   // Not a build vector of (possibly fp_rounded) loads.
11865   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11866     return SDValue();
11867 
11868   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11869     // If any inputs are fp_round(extload), they all must be.
11870     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11871       return SDValue();
11872 
11873     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11874       N->getOperand(i);
11875     if (NextInput.getOpcode() != ISD::LOAD)
11876       return SDValue();
11877 
11878     SDValue PreviousInput =
11879       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11880     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11881     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11882 
11883     // If any inputs are fp_round(extload), they all must be.
11884     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11885       return SDValue();
11886 
11887     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11888       InputsAreConsecutiveLoads = false;
11889     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11890       InputsAreReverseConsecutive = false;
11891 
11892     // Exit early if the loads are neither consecutive nor reverse consecutive.
11893     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11894       return SDValue();
11895   }
11896 
11897   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11898          "The loads cannot be both consecutive and reverse consecutive.");
11899 
11900   SDValue FirstLoadOp =
11901     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11902   SDValue LastLoadOp =
11903     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11904                        N->getOperand(N->getNumOperands()-1);
11905 
11906   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11907   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11908   if (InputsAreConsecutiveLoads) {
11909     assert(LD1 && "Input needs to be a LoadSDNode.");
11910     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11911                        LD1->getBasePtr(), LD1->getPointerInfo(),
11912                        LD1->getAlignment());
11913   }
11914   if (InputsAreReverseConsecutive) {
11915     assert(LDL && "Input needs to be a LoadSDNode.");
11916     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11917                                LDL->getBasePtr(), LDL->getPointerInfo(),
11918                                LDL->getAlignment());
11919     SmallVector<int, 16> Ops;
11920     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11921       Ops.push_back(i);
11922 
11923     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11924                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11925   }
11926   return SDValue();
11927 }
11928 
11929 // This function adds the required vector_shuffle needed to get
11930 // the elements of the vector extract in the correct position
11931 // as specified by the CorrectElems encoding.
11932 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11933                                       SDValue Input, uint64_t Elems,
11934                                       uint64_t CorrectElems) {
11935   SDLoc dl(N);
11936 
11937   unsigned NumElems = Input.getValueType().getVectorNumElements();
11938   SmallVector<int, 16> ShuffleMask(NumElems, -1);
11939 
11940   // Knowing the element indices being extracted from the original
11941   // vector and the order in which they're being inserted, just put
11942   // them at element indices required for the instruction.
11943   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11944     if (DAG.getDataLayout().isLittleEndian())
11945       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11946     else
11947       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11948     CorrectElems = CorrectElems >> 8;
11949     Elems = Elems >> 8;
11950   }
11951 
11952   SDValue Shuffle =
11953       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11954                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11955 
11956   EVT Ty = N->getValueType(0);
11957   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11958   return BV;
11959 }
11960 
11961 // Look for build vector patterns where input operands come from sign
11962 // extended vector_extract elements of specific indices. If the correct indices
11963 // aren't used, add a vector shuffle to fix up the indices and create a new
11964 // PPCISD:SExtVElems node which selects the vector sign extend instructions
11965 // during instruction selection.
11966 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
11967   // This array encodes the indices that the vector sign extend instructions
11968   // extract from when extending from one type to another for both BE and LE.
11969   // The right nibble of each byte corresponds to the LE incides.
11970   // and the left nibble of each byte corresponds to the BE incides.
11971   // For example: 0x3074B8FC  byte->word
11972   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
11973   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
11974   // For example: 0x000070F8  byte->double word
11975   // For LE: the allowed indices are: 0x0,0x8
11976   // For BE: the allowed indices are: 0x7,0xF
11977   uint64_t TargetElems[] = {
11978       0x3074B8FC, // b->w
11979       0x000070F8, // b->d
11980       0x10325476, // h->w
11981       0x00003074, // h->d
11982       0x00001032, // w->d
11983   };
11984 
11985   uint64_t Elems = 0;
11986   int Index;
11987   SDValue Input;
11988 
11989   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
11990     if (!Op)
11991       return false;
11992     if (Op.getOpcode() != ISD::SIGN_EXTEND)
11993       return false;
11994 
11995     SDValue Extract = Op.getOperand(0);
11996     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11997       return false;
11998 
11999     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12000     if (!ExtOp)
12001       return false;
12002 
12003     Index = ExtOp->getZExtValue();
12004     if (Input && Input != Extract.getOperand(0))
12005       return false;
12006 
12007     if (!Input)
12008       Input = Extract.getOperand(0);
12009 
12010     Elems = Elems << 8;
12011     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12012     Elems |= Index;
12013 
12014     return true;
12015   };
12016 
12017   // If the build vector operands aren't sign extended vector extracts,
12018   // of the same input vector, then return.
12019   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12020     if (!isSExtOfVecExtract(N->getOperand(i))) {
12021       return SDValue();
12022     }
12023   }
12024 
12025   // If the vector extract indicies are not correct, add the appropriate
12026   // vector_shuffle.
12027   int TgtElemArrayIdx;
12028   int InputSize = Input.getValueType().getScalarSizeInBits();
12029   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12030   if (InputSize + OutputSize == 40)
12031     TgtElemArrayIdx = 0;
12032   else if (InputSize + OutputSize == 72)
12033     TgtElemArrayIdx = 1;
12034   else if (InputSize + OutputSize == 48)
12035     TgtElemArrayIdx = 2;
12036   else if (InputSize + OutputSize == 80)
12037     TgtElemArrayIdx = 3;
12038   else if (InputSize + OutputSize == 96)
12039     TgtElemArrayIdx = 4;
12040   else
12041     return SDValue();
12042 
12043   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12044   CorrectElems = DAG.getDataLayout().isLittleEndian()
12045                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12046                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12047   if (Elems != CorrectElems) {
12048     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12049   }
12050 
12051   // Regular lowering will catch cases where a shuffle is not needed.
12052   return SDValue();
12053 }
12054 
12055 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12056                                                  DAGCombinerInfo &DCI) const {
12057   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12058          "Should be called with a BUILD_VECTOR node");
12059 
12060   SelectionDAG &DAG = DCI.DAG;
12061   SDLoc dl(N);
12062 
12063   if (!Subtarget.hasVSX())
12064     return SDValue();
12065 
12066   // The target independent DAG combiner will leave a build_vector of
12067   // float-to-int conversions intact. We can generate MUCH better code for
12068   // a float-to-int conversion of a vector of floats.
12069   SDValue FirstInput = N->getOperand(0);
12070   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12071     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12072     if (Reduced)
12073       return Reduced;
12074   }
12075 
12076   // If we're building a vector out of consecutive loads, just load that
12077   // vector type.
12078   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12079   if (Reduced)
12080     return Reduced;
12081 
12082   // If we're building a vector out of extended elements from another vector
12083   // we have P9 vector integer extend instructions.
12084   if (Subtarget.hasP9Altivec()) {
12085     Reduced = combineBVOfVecSExt(N, DAG);
12086     if (Reduced)
12087       return Reduced;
12088   }
12089 
12090 
12091   if (N->getValueType(0) != MVT::v2f64)
12092     return SDValue();
12093 
12094   // Looking for:
12095   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12096   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12097       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12098     return SDValue();
12099   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12100       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12101     return SDValue();
12102   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12103     return SDValue();
12104 
12105   SDValue Ext1 = FirstInput.getOperand(0);
12106   SDValue Ext2 = N->getOperand(1).getOperand(0);
12107   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12108      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12109     return SDValue();
12110 
12111   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12112   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12113   if (!Ext1Op || !Ext2Op)
12114     return SDValue();
12115   if (Ext1.getValueType() != MVT::i32 ||
12116       Ext2.getValueType() != MVT::i32)
12117   if (Ext1.getOperand(0) != Ext2.getOperand(0))
12118     return SDValue();
12119 
12120   int FirstElem = Ext1Op->getZExtValue();
12121   int SecondElem = Ext2Op->getZExtValue();
12122   int SubvecIdx;
12123   if (FirstElem == 0 && SecondElem == 1)
12124     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12125   else if (FirstElem == 2 && SecondElem == 3)
12126     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12127   else
12128     return SDValue();
12129 
12130   SDValue SrcVec = Ext1.getOperand(0);
12131   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12132     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12133   return DAG.getNode(NodeType, dl, MVT::v2f64,
12134                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12135 }
12136 
12137 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12138                                               DAGCombinerInfo &DCI) const {
12139   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12140           N->getOpcode() == ISD::UINT_TO_FP) &&
12141          "Need an int -> FP conversion node here");
12142 
12143   if (useSoftFloat() || !Subtarget.has64BitSupport())
12144     return SDValue();
12145 
12146   SelectionDAG &DAG = DCI.DAG;
12147   SDLoc dl(N);
12148   SDValue Op(N, 0);
12149 
12150   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12151   // from the hardware.
12152   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12153     return SDValue();
12154   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12155       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12156     return SDValue();
12157 
12158   SDValue FirstOperand(Op.getOperand(0));
12159   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12160     (FirstOperand.getValueType() == MVT::i8 ||
12161      FirstOperand.getValueType() == MVT::i16);
12162   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12163     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12164     bool DstDouble = Op.getValueType() == MVT::f64;
12165     unsigned ConvOp = Signed ?
12166       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12167       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12168     SDValue WidthConst =
12169       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12170                             dl, false);
12171     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12172     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12173     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12174                                          DAG.getVTList(MVT::f64, MVT::Other),
12175                                          Ops, MVT::i8, LDN->getMemOperand());
12176 
12177     // For signed conversion, we need to sign-extend the value in the VSR
12178     if (Signed) {
12179       SDValue ExtOps[] = { Ld, WidthConst };
12180       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12181       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12182     } else
12183       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12184   }
12185 
12186 
12187   // For i32 intermediate values, unfortunately, the conversion functions
12188   // leave the upper 32 bits of the value are undefined. Within the set of
12189   // scalar instructions, we have no method for zero- or sign-extending the
12190   // value. Thus, we cannot handle i32 intermediate values here.
12191   if (Op.getOperand(0).getValueType() == MVT::i32)
12192     return SDValue();
12193 
12194   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12195          "UINT_TO_FP is supported only with FPCVT");
12196 
12197   // If we have FCFIDS, then use it when converting to single-precision.
12198   // Otherwise, convert to double-precision and then round.
12199   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12200                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12201                                                             : PPCISD::FCFIDS)
12202                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12203                                                             : PPCISD::FCFID);
12204   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12205                   ? MVT::f32
12206                   : MVT::f64;
12207 
12208   // If we're converting from a float, to an int, and back to a float again,
12209   // then we don't need the store/load pair at all.
12210   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12211        Subtarget.hasFPCVT()) ||
12212       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12213     SDValue Src = Op.getOperand(0).getOperand(0);
12214     if (Src.getValueType() == MVT::f32) {
12215       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12216       DCI.AddToWorklist(Src.getNode());
12217     } else if (Src.getValueType() != MVT::f64) {
12218       // Make sure that we don't pick up a ppc_fp128 source value.
12219       return SDValue();
12220     }
12221 
12222     unsigned FCTOp =
12223       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12224                                                         PPCISD::FCTIDUZ;
12225 
12226     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12227     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12228 
12229     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12230       FP = DAG.getNode(ISD::FP_ROUND, dl,
12231                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12232       DCI.AddToWorklist(FP.getNode());
12233     }
12234 
12235     return FP;
12236   }
12237 
12238   return SDValue();
12239 }
12240 
12241 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12242 // builtins) into loads with swaps.
12243 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12244                                               DAGCombinerInfo &DCI) const {
12245   SelectionDAG &DAG = DCI.DAG;
12246   SDLoc dl(N);
12247   SDValue Chain;
12248   SDValue Base;
12249   MachineMemOperand *MMO;
12250 
12251   switch (N->getOpcode()) {
12252   default:
12253     llvm_unreachable("Unexpected opcode for little endian VSX load");
12254   case ISD::LOAD: {
12255     LoadSDNode *LD = cast<LoadSDNode>(N);
12256     Chain = LD->getChain();
12257     Base = LD->getBasePtr();
12258     MMO = LD->getMemOperand();
12259     // If the MMO suggests this isn't a load of a full vector, leave
12260     // things alone.  For a built-in, we have to make the change for
12261     // correctness, so if there is a size problem that will be a bug.
12262     if (MMO->getSize() < 16)
12263       return SDValue();
12264     break;
12265   }
12266   case ISD::INTRINSIC_W_CHAIN: {
12267     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12268     Chain = Intrin->getChain();
12269     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12270     // us what we want. Get operand 2 instead.
12271     Base = Intrin->getOperand(2);
12272     MMO = Intrin->getMemOperand();
12273     break;
12274   }
12275   }
12276 
12277   MVT VecTy = N->getValueType(0).getSimpleVT();
12278 
12279   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12280   // aligned and the type is a vector with elements up to 4 bytes
12281   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12282       && VecTy.getScalarSizeInBits() <= 32 ) {
12283     return SDValue();
12284   }
12285 
12286   SDValue LoadOps[] = { Chain, Base };
12287   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12288                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12289                                          LoadOps, MVT::v2f64, MMO);
12290 
12291   DCI.AddToWorklist(Load.getNode());
12292   Chain = Load.getValue(1);
12293   SDValue Swap = DAG.getNode(
12294       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12295   DCI.AddToWorklist(Swap.getNode());
12296 
12297   // Add a bitcast if the resulting load type doesn't match v2f64.
12298   if (VecTy != MVT::v2f64) {
12299     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12300     DCI.AddToWorklist(N.getNode());
12301     // Package {bitcast value, swap's chain} to match Load's shape.
12302     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12303                        N, Swap.getValue(1));
12304   }
12305 
12306   return Swap;
12307 }
12308 
12309 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12310 // builtins) into stores with swaps.
12311 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12312                                                DAGCombinerInfo &DCI) const {
12313   SelectionDAG &DAG = DCI.DAG;
12314   SDLoc dl(N);
12315   SDValue Chain;
12316   SDValue Base;
12317   unsigned SrcOpnd;
12318   MachineMemOperand *MMO;
12319 
12320   switch (N->getOpcode()) {
12321   default:
12322     llvm_unreachable("Unexpected opcode for little endian VSX store");
12323   case ISD::STORE: {
12324     StoreSDNode *ST = cast<StoreSDNode>(N);
12325     Chain = ST->getChain();
12326     Base = ST->getBasePtr();
12327     MMO = ST->getMemOperand();
12328     SrcOpnd = 1;
12329     // If the MMO suggests this isn't a store of a full vector, leave
12330     // things alone.  For a built-in, we have to make the change for
12331     // correctness, so if there is a size problem that will be a bug.
12332     if (MMO->getSize() < 16)
12333       return SDValue();
12334     break;
12335   }
12336   case ISD::INTRINSIC_VOID: {
12337     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12338     Chain = Intrin->getChain();
12339     // Intrin->getBasePtr() oddly does not get what we want.
12340     Base = Intrin->getOperand(3);
12341     MMO = Intrin->getMemOperand();
12342     SrcOpnd = 2;
12343     break;
12344   }
12345   }
12346 
12347   SDValue Src = N->getOperand(SrcOpnd);
12348   MVT VecTy = Src.getValueType().getSimpleVT();
12349 
12350   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12351   // aligned and the type is a vector with elements up to 4 bytes
12352   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12353       && VecTy.getScalarSizeInBits() <= 32 ) {
12354     return SDValue();
12355   }
12356 
12357   // All stores are done as v2f64 and possible bit cast.
12358   if (VecTy != MVT::v2f64) {
12359     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12360     DCI.AddToWorklist(Src.getNode());
12361   }
12362 
12363   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12364                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12365   DCI.AddToWorklist(Swap.getNode());
12366   Chain = Swap.getValue(1);
12367   SDValue StoreOps[] = { Chain, Swap, Base };
12368   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12369                                           DAG.getVTList(MVT::Other),
12370                                           StoreOps, VecTy, MMO);
12371   DCI.AddToWorklist(Store.getNode());
12372   return Store;
12373 }
12374 
12375 // Handle DAG combine for STORE (FP_TO_INT F).
12376 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12377                                                DAGCombinerInfo &DCI) const {
12378 
12379   SelectionDAG &DAG = DCI.DAG;
12380   SDLoc dl(N);
12381   unsigned Opcode = N->getOperand(1).getOpcode();
12382 
12383   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12384          && "Not a FP_TO_INT Instruction!");
12385 
12386   SDValue Val = N->getOperand(1).getOperand(0);
12387   EVT Op1VT = N->getOperand(1).getValueType();
12388   EVT ResVT = Val.getValueType();
12389 
12390   // Floating point types smaller than 32 bits are not legal on Power.
12391   if (ResVT.getScalarSizeInBits() < 32)
12392     return SDValue();
12393 
12394   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
12395   bool ValidTypeForStoreFltAsInt =
12396         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
12397          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
12398 
12399   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
12400       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
12401     return SDValue();
12402 
12403   // Extend f32 values to f64
12404   if (ResVT.getScalarSizeInBits() == 32) {
12405     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12406     DCI.AddToWorklist(Val.getNode());
12407   }
12408 
12409   // Set signed or unsigned conversion opcode.
12410   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
12411                           PPCISD::FP_TO_SINT_IN_VSR :
12412                           PPCISD::FP_TO_UINT_IN_VSR;
12413 
12414   Val = DAG.getNode(ConvOpcode,
12415                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
12416   DCI.AddToWorklist(Val.getNode());
12417 
12418   // Set number of bytes being converted.
12419   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
12420   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
12421                     DAG.getIntPtrConstant(ByteSize, dl, false),
12422                     DAG.getValueType(Op1VT) };
12423 
12424   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
12425           DAG.getVTList(MVT::Other), Ops,
12426           cast<StoreSDNode>(N)->getMemoryVT(),
12427           cast<StoreSDNode>(N)->getMemOperand());
12428 
12429   DCI.AddToWorklist(Val.getNode());
12430   return Val;
12431 }
12432 
12433 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12434                                              DAGCombinerInfo &DCI) const {
12435   SelectionDAG &DAG = DCI.DAG;
12436   SDLoc dl(N);
12437   switch (N->getOpcode()) {
12438   default: break;
12439   case ISD::SHL:
12440     return combineSHL(N, DCI);
12441   case ISD::SRA:
12442     return combineSRA(N, DCI);
12443   case ISD::SRL:
12444     return combineSRL(N, DCI);
12445   case PPCISD::SHL:
12446     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12447         return N->getOperand(0);
12448     break;
12449   case PPCISD::SRL:
12450     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12451         return N->getOperand(0);
12452     break;
12453   case PPCISD::SRA:
12454     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12455       if (C->isNullValue() ||   //  0 >>s V -> 0.
12456           C->isAllOnesValue())    // -1 >>s V -> -1.
12457         return N->getOperand(0);
12458     }
12459     break;
12460   case ISD::SIGN_EXTEND:
12461   case ISD::ZERO_EXTEND:
12462   case ISD::ANY_EXTEND:
12463     return DAGCombineExtBoolTrunc(N, DCI);
12464   case ISD::TRUNCATE:
12465   case ISD::SETCC:
12466   case ISD::SELECT_CC:
12467     return DAGCombineTruncBoolExt(N, DCI);
12468   case ISD::SINT_TO_FP:
12469   case ISD::UINT_TO_FP:
12470     return combineFPToIntToFP(N, DCI);
12471   case ISD::STORE: {
12472 
12473     EVT Op1VT = N->getOperand(1).getValueType();
12474     unsigned Opcode = N->getOperand(1).getOpcode();
12475 
12476     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
12477       SDValue Val= combineStoreFPToInt(N, DCI);
12478       if (Val)
12479         return Val;
12480     }
12481 
12482     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12483     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
12484         N->getOperand(1).getNode()->hasOneUse() &&
12485         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
12486          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
12487 
12488       // STBRX can only handle simple types.
12489       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12490       if (mVT.isExtended())
12491         break;
12492 
12493       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12494       // Do an any-extend to 32-bits if this is a half-word input.
12495       if (BSwapOp.getValueType() == MVT::i16)
12496         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12497 
12498       // If the type of BSWAP operand is wider than stored memory width
12499       // it need to be shifted to the right side before STBRX.
12500       if (Op1VT.bitsGT(mVT)) {
12501         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12502         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12503                               DAG.getConstant(Shift, dl, MVT::i32));
12504         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12505         if (Op1VT == MVT::i64)
12506           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12507       }
12508 
12509       SDValue Ops[] = {
12510         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12511       };
12512       return
12513         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12514                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12515                                 cast<StoreSDNode>(N)->getMemOperand());
12516     }
12517 
12518     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
12519     // So it can increase the chance of CSE constant construction.
12520     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
12521         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
12522       // Need to sign-extended to 64-bits to handle negative values.
12523       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
12524       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
12525                                     MemVT.getSizeInBits());
12526       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
12527 
12528       // DAG.getTruncStore() can't be used here because it doesn't accept
12529       // the general (base + offset) addressing mode.
12530       // So we use UpdateNodeOperands and setTruncatingStore instead.
12531       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
12532                              N->getOperand(3));
12533       cast<StoreSDNode>(N)->setTruncatingStore(true);
12534       return SDValue(N, 0);
12535     }
12536 
12537     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12538     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12539     if (Op1VT.isSimple()) {
12540       MVT StoreVT = Op1VT.getSimpleVT();
12541       if (Subtarget.needsSwapsForVSXMemOps() &&
12542           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12543            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12544         return expandVSXStoreForLE(N, DCI);
12545     }
12546     break;
12547   }
12548   case ISD::LOAD: {
12549     LoadSDNode *LD = cast<LoadSDNode>(N);
12550     EVT VT = LD->getValueType(0);
12551 
12552     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12553     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12554     if (VT.isSimple()) {
12555       MVT LoadVT = VT.getSimpleVT();
12556       if (Subtarget.needsSwapsForVSXMemOps() &&
12557           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12558            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12559         return expandVSXLoadForLE(N, DCI);
12560     }
12561 
12562     // We sometimes end up with a 64-bit integer load, from which we extract
12563     // two single-precision floating-point numbers. This happens with
12564     // std::complex<float>, and other similar structures, because of the way we
12565     // canonicalize structure copies. However, if we lack direct moves,
12566     // then the final bitcasts from the extracted integer values to the
12567     // floating-point numbers turn into store/load pairs. Even with direct moves,
12568     // just loading the two floating-point numbers is likely better.
12569     auto ReplaceTwoFloatLoad = [&]() {
12570       if (VT != MVT::i64)
12571         return false;
12572 
12573       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12574           LD->isVolatile())
12575         return false;
12576 
12577       //  We're looking for a sequence like this:
12578       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12579       //      t16: i64 = srl t13, Constant:i32<32>
12580       //    t17: i32 = truncate t16
12581       //  t18: f32 = bitcast t17
12582       //    t19: i32 = truncate t13
12583       //  t20: f32 = bitcast t19
12584 
12585       if (!LD->hasNUsesOfValue(2, 0))
12586         return false;
12587 
12588       auto UI = LD->use_begin();
12589       while (UI.getUse().getResNo() != 0) ++UI;
12590       SDNode *Trunc = *UI++;
12591       while (UI.getUse().getResNo() != 0) ++UI;
12592       SDNode *RightShift = *UI;
12593       if (Trunc->getOpcode() != ISD::TRUNCATE)
12594         std::swap(Trunc, RightShift);
12595 
12596       if (Trunc->getOpcode() != ISD::TRUNCATE ||
12597           Trunc->getValueType(0) != MVT::i32 ||
12598           !Trunc->hasOneUse())
12599         return false;
12600       if (RightShift->getOpcode() != ISD::SRL ||
12601           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12602           RightShift->getConstantOperandVal(1) != 32 ||
12603           !RightShift->hasOneUse())
12604         return false;
12605 
12606       SDNode *Trunc2 = *RightShift->use_begin();
12607       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12608           Trunc2->getValueType(0) != MVT::i32 ||
12609           !Trunc2->hasOneUse())
12610         return false;
12611 
12612       SDNode *Bitcast = *Trunc->use_begin();
12613       SDNode *Bitcast2 = *Trunc2->use_begin();
12614 
12615       if (Bitcast->getOpcode() != ISD::BITCAST ||
12616           Bitcast->getValueType(0) != MVT::f32)
12617         return false;
12618       if (Bitcast2->getOpcode() != ISD::BITCAST ||
12619           Bitcast2->getValueType(0) != MVT::f32)
12620         return false;
12621 
12622       if (Subtarget.isLittleEndian())
12623         std::swap(Bitcast, Bitcast2);
12624 
12625       // Bitcast has the second float (in memory-layout order) and Bitcast2
12626       // has the first one.
12627 
12628       SDValue BasePtr = LD->getBasePtr();
12629       if (LD->isIndexed()) {
12630         assert(LD->getAddressingMode() == ISD::PRE_INC &&
12631                "Non-pre-inc AM on PPC?");
12632         BasePtr =
12633           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12634                       LD->getOffset());
12635       }
12636 
12637       auto MMOFlags =
12638           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12639       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12640                                       LD->getPointerInfo(), LD->getAlignment(),
12641                                       MMOFlags, LD->getAAInfo());
12642       SDValue AddPtr =
12643         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12644                     BasePtr, DAG.getIntPtrConstant(4, dl));
12645       SDValue FloatLoad2 = DAG.getLoad(
12646           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12647           LD->getPointerInfo().getWithOffset(4),
12648           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12649 
12650       if (LD->isIndexed()) {
12651         // Note that DAGCombine should re-form any pre-increment load(s) from
12652         // what is produced here if that makes sense.
12653         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12654       }
12655 
12656       DCI.CombineTo(Bitcast2, FloatLoad);
12657       DCI.CombineTo(Bitcast, FloatLoad2);
12658 
12659       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12660                                     SDValue(FloatLoad2.getNode(), 1));
12661       return true;
12662     };
12663 
12664     if (ReplaceTwoFloatLoad())
12665       return SDValue(N, 0);
12666 
12667     EVT MemVT = LD->getMemoryVT();
12668     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12669     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12670     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12671     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12672     if (LD->isUnindexed() && VT.isVector() &&
12673         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12674           // P8 and later hardware should just use LOAD.
12675           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12676                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12677          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12678           LD->getAlignment() >= ScalarABIAlignment)) &&
12679         LD->getAlignment() < ABIAlignment) {
12680       // This is a type-legal unaligned Altivec or QPX load.
12681       SDValue Chain = LD->getChain();
12682       SDValue Ptr = LD->getBasePtr();
12683       bool isLittleEndian = Subtarget.isLittleEndian();
12684 
12685       // This implements the loading of unaligned vectors as described in
12686       // the venerable Apple Velocity Engine overview. Specifically:
12687       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12688       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12689       //
12690       // The general idea is to expand a sequence of one or more unaligned
12691       // loads into an alignment-based permutation-control instruction (lvsl
12692       // or lvsr), a series of regular vector loads (which always truncate
12693       // their input address to an aligned address), and a series of
12694       // permutations.  The results of these permutations are the requested
12695       // loaded values.  The trick is that the last "extra" load is not taken
12696       // from the address you might suspect (sizeof(vector) bytes after the
12697       // last requested load), but rather sizeof(vector) - 1 bytes after the
12698       // last requested vector. The point of this is to avoid a page fault if
12699       // the base address happened to be aligned. This works because if the
12700       // base address is aligned, then adding less than a full vector length
12701       // will cause the last vector in the sequence to be (re)loaded.
12702       // Otherwise, the next vector will be fetched as you might suspect was
12703       // necessary.
12704 
12705       // We might be able to reuse the permutation generation from
12706       // a different base address offset from this one by an aligned amount.
12707       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12708       // optimization later.
12709       Intrinsic::ID Intr, IntrLD, IntrPerm;
12710       MVT PermCntlTy, PermTy, LDTy;
12711       if (Subtarget.hasAltivec()) {
12712         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
12713                                  Intrinsic::ppc_altivec_lvsl;
12714         IntrLD = Intrinsic::ppc_altivec_lvx;
12715         IntrPerm = Intrinsic::ppc_altivec_vperm;
12716         PermCntlTy = MVT::v16i8;
12717         PermTy = MVT::v4i32;
12718         LDTy = MVT::v4i32;
12719       } else {
12720         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12721                                        Intrinsic::ppc_qpx_qvlpcls;
12722         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12723                                        Intrinsic::ppc_qpx_qvlfs;
12724         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12725         PermCntlTy = MVT::v4f64;
12726         PermTy = MVT::v4f64;
12727         LDTy = MemVT.getSimpleVT();
12728       }
12729 
12730       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12731 
12732       // Create the new MMO for the new base load. It is like the original MMO,
12733       // but represents an area in memory almost twice the vector size centered
12734       // on the original address. If the address is unaligned, we might start
12735       // reading up to (sizeof(vector)-1) bytes below the address of the
12736       // original unaligned load.
12737       MachineFunction &MF = DAG.getMachineFunction();
12738       MachineMemOperand *BaseMMO =
12739         MF.getMachineMemOperand(LD->getMemOperand(),
12740                                 -(long)MemVT.getStoreSize()+1,
12741                                 2*MemVT.getStoreSize()-1);
12742 
12743       // Create the new base load.
12744       SDValue LDXIntID =
12745           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12746       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12747       SDValue BaseLoad =
12748         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12749                                 DAG.getVTList(PermTy, MVT::Other),
12750                                 BaseLoadOps, LDTy, BaseMMO);
12751 
12752       // Note that the value of IncOffset (which is provided to the next
12753       // load's pointer info offset value, and thus used to calculate the
12754       // alignment), and the value of IncValue (which is actually used to
12755       // increment the pointer value) are different! This is because we
12756       // require the next load to appear to be aligned, even though it
12757       // is actually offset from the base pointer by a lesser amount.
12758       int IncOffset = VT.getSizeInBits() / 8;
12759       int IncValue = IncOffset;
12760 
12761       // Walk (both up and down) the chain looking for another load at the real
12762       // (aligned) offset (the alignment of the other load does not matter in
12763       // this case). If found, then do not use the offset reduction trick, as
12764       // that will prevent the loads from being later combined (as they would
12765       // otherwise be duplicates).
12766       if (!findConsecutiveLoad(LD, DAG))
12767         --IncValue;
12768 
12769       SDValue Increment =
12770           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12771       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12772 
12773       MachineMemOperand *ExtraMMO =
12774         MF.getMachineMemOperand(LD->getMemOperand(),
12775                                 1, 2*MemVT.getStoreSize()-1);
12776       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12777       SDValue ExtraLoad =
12778         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12779                                 DAG.getVTList(PermTy, MVT::Other),
12780                                 ExtraLoadOps, LDTy, ExtraMMO);
12781 
12782       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12783         BaseLoad.getValue(1), ExtraLoad.getValue(1));
12784 
12785       // Because vperm has a big-endian bias, we must reverse the order
12786       // of the input vectors and complement the permute control vector
12787       // when generating little endian code.  We have already handled the
12788       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12789       // and ExtraLoad here.
12790       SDValue Perm;
12791       if (isLittleEndian)
12792         Perm = BuildIntrinsicOp(IntrPerm,
12793                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12794       else
12795         Perm = BuildIntrinsicOp(IntrPerm,
12796                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12797 
12798       if (VT != PermTy)
12799         Perm = Subtarget.hasAltivec() ?
12800                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12801                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12802                                DAG.getTargetConstant(1, dl, MVT::i64));
12803                                // second argument is 1 because this rounding
12804                                // is always exact.
12805 
12806       // The output of the permutation is our loaded result, the TokenFactor is
12807       // our new chain.
12808       DCI.CombineTo(N, Perm, TF);
12809       return SDValue(N, 0);
12810     }
12811     }
12812     break;
12813     case ISD::INTRINSIC_WO_CHAIN: {
12814       bool isLittleEndian = Subtarget.isLittleEndian();
12815       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12816       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12817                                            : Intrinsic::ppc_altivec_lvsl);
12818       if ((IID == Intr ||
12819            IID == Intrinsic::ppc_qpx_qvlpcld  ||
12820            IID == Intrinsic::ppc_qpx_qvlpcls) &&
12821         N->getOperand(1)->getOpcode() == ISD::ADD) {
12822         SDValue Add = N->getOperand(1);
12823 
12824         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12825                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12826 
12827         if (DAG.MaskedValueIsZero(Add->getOperand(1),
12828                                   APInt::getAllOnesValue(Bits /* alignment */)
12829                                       .zext(Add.getScalarValueSizeInBits()))) {
12830           SDNode *BasePtr = Add->getOperand(0).getNode();
12831           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12832                                     UE = BasePtr->use_end();
12833                UI != UE; ++UI) {
12834             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12835                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12836               // We've found another LVSL/LVSR, and this address is an aligned
12837               // multiple of that one. The results will be the same, so use the
12838               // one we've just found instead.
12839 
12840               return SDValue(*UI, 0);
12841             }
12842           }
12843         }
12844 
12845         if (isa<ConstantSDNode>(Add->getOperand(1))) {
12846           SDNode *BasePtr = Add->getOperand(0).getNode();
12847           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12848                UE = BasePtr->use_end(); UI != UE; ++UI) {
12849             if (UI->getOpcode() == ISD::ADD &&
12850                 isa<ConstantSDNode>(UI->getOperand(1)) &&
12851                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12852                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12853                 (1ULL << Bits) == 0) {
12854               SDNode *OtherAdd = *UI;
12855               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12856                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
12857                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12858                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12859                   return SDValue(*VI, 0);
12860                 }
12861               }
12862             }
12863           }
12864         }
12865       }
12866     }
12867 
12868     break;
12869   case ISD::INTRINSIC_W_CHAIN:
12870     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12871     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12872     if (Subtarget.needsSwapsForVSXMemOps()) {
12873       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12874       default:
12875         break;
12876       case Intrinsic::ppc_vsx_lxvw4x:
12877       case Intrinsic::ppc_vsx_lxvd2x:
12878         return expandVSXLoadForLE(N, DCI);
12879       }
12880     }
12881     break;
12882   case ISD::INTRINSIC_VOID:
12883     // For little endian, VSX stores require generating xxswapd/stxvd2x.
12884     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12885     if (Subtarget.needsSwapsForVSXMemOps()) {
12886       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12887       default:
12888         break;
12889       case Intrinsic::ppc_vsx_stxvw4x:
12890       case Intrinsic::ppc_vsx_stxvd2x:
12891         return expandVSXStoreForLE(N, DCI);
12892       }
12893     }
12894     break;
12895   case ISD::BSWAP:
12896     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12897     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12898         N->getOperand(0).hasOneUse() &&
12899         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12900          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12901           N->getValueType(0) == MVT::i64))) {
12902       SDValue Load = N->getOperand(0);
12903       LoadSDNode *LD = cast<LoadSDNode>(Load);
12904       // Create the byte-swapping load.
12905       SDValue Ops[] = {
12906         LD->getChain(),    // Chain
12907         LD->getBasePtr(),  // Ptr
12908         DAG.getValueType(N->getValueType(0)) // VT
12909       };
12910       SDValue BSLoad =
12911         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12912                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12913                                               MVT::i64 : MVT::i32, MVT::Other),
12914                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
12915 
12916       // If this is an i16 load, insert the truncate.
12917       SDValue ResVal = BSLoad;
12918       if (N->getValueType(0) == MVT::i16)
12919         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12920 
12921       // First, combine the bswap away.  This makes the value produced by the
12922       // load dead.
12923       DCI.CombineTo(N, ResVal);
12924 
12925       // Next, combine the load away, we give it a bogus result value but a real
12926       // chain result.  The result value is dead because the bswap is dead.
12927       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12928 
12929       // Return N so it doesn't get rechecked!
12930       return SDValue(N, 0);
12931     }
12932     break;
12933   case PPCISD::VCMP:
12934     // If a VCMPo node already exists with exactly the same operands as this
12935     // node, use its result instead of this node (VCMPo computes both a CR6 and
12936     // a normal output).
12937     //
12938     if (!N->getOperand(0).hasOneUse() &&
12939         !N->getOperand(1).hasOneUse() &&
12940         !N->getOperand(2).hasOneUse()) {
12941 
12942       // Scan all of the users of the LHS, looking for VCMPo's that match.
12943       SDNode *VCMPoNode = nullptr;
12944 
12945       SDNode *LHSN = N->getOperand(0).getNode();
12946       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12947            UI != E; ++UI)
12948         if (UI->getOpcode() == PPCISD::VCMPo &&
12949             UI->getOperand(1) == N->getOperand(1) &&
12950             UI->getOperand(2) == N->getOperand(2) &&
12951             UI->getOperand(0) == N->getOperand(0)) {
12952           VCMPoNode = *UI;
12953           break;
12954         }
12955 
12956       // If there is no VCMPo node, or if the flag value has a single use, don't
12957       // transform this.
12958       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
12959         break;
12960 
12961       // Look at the (necessarily single) use of the flag value.  If it has a
12962       // chain, this transformation is more complex.  Note that multiple things
12963       // could use the value result, which we should ignore.
12964       SDNode *FlagUser = nullptr;
12965       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
12966            FlagUser == nullptr; ++UI) {
12967         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
12968         SDNode *User = *UI;
12969         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
12970           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12971             FlagUser = User;
12972             break;
12973           }
12974         }
12975       }
12976 
12977       // If the user is a MFOCRF instruction, we know this is safe.
12978       // Otherwise we give up for right now.
12979       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12980         return SDValue(VCMPoNode, 0);
12981     }
12982     break;
12983   case ISD::BRCOND: {
12984     SDValue Cond = N->getOperand(1);
12985     SDValue Target = N->getOperand(2);
12986 
12987     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12988         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12989           Intrinsic::ppc_is_decremented_ctr_nonzero) {
12990 
12991       // We now need to make the intrinsic dead (it cannot be instruction
12992       // selected).
12993       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12994       assert(Cond.getNode()->hasOneUse() &&
12995              "Counter decrement has more than one use");
12996 
12997       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12998                          N->getOperand(0), Target);
12999     }
13000   }
13001   break;
13002   case ISD::BR_CC: {
13003     // If this is a branch on an altivec predicate comparison, lower this so
13004     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13005     // lowering is done pre-legalize, because the legalizer lowers the predicate
13006     // compare down to code that is difficult to reassemble.
13007     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13008     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13009 
13010     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13011     // value. If so, pass-through the AND to get to the intrinsic.
13012     if (LHS.getOpcode() == ISD::AND &&
13013         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13014         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13015           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13016         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13017         !isNullConstant(LHS.getOperand(1)))
13018       LHS = LHS.getOperand(0);
13019 
13020     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13021         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13022           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13023         isa<ConstantSDNode>(RHS)) {
13024       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13025              "Counter decrement comparison is not EQ or NE");
13026 
13027       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13028       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13029                     (CC == ISD::SETNE && !Val);
13030 
13031       // We now need to make the intrinsic dead (it cannot be instruction
13032       // selected).
13033       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13034       assert(LHS.getNode()->hasOneUse() &&
13035              "Counter decrement has more than one use");
13036 
13037       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13038                          N->getOperand(0), N->getOperand(4));
13039     }
13040 
13041     int CompareOpc;
13042     bool isDot;
13043 
13044     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13045         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13046         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13047       assert(isDot && "Can't compare against a vector result!");
13048 
13049       // If this is a comparison against something other than 0/1, then we know
13050       // that the condition is never/always true.
13051       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13052       if (Val != 0 && Val != 1) {
13053         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13054           return N->getOperand(0);
13055         // Always !=, turn it into an unconditional branch.
13056         return DAG.getNode(ISD::BR, dl, MVT::Other,
13057                            N->getOperand(0), N->getOperand(4));
13058       }
13059 
13060       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13061 
13062       // Create the PPCISD altivec 'dot' comparison node.
13063       SDValue Ops[] = {
13064         LHS.getOperand(2),  // LHS of compare
13065         LHS.getOperand(3),  // RHS of compare
13066         DAG.getConstant(CompareOpc, dl, MVT::i32)
13067       };
13068       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13069       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13070 
13071       // Unpack the result based on how the target uses it.
13072       PPC::Predicate CompOpc;
13073       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13074       default:  // Can't happen, don't crash on invalid number though.
13075       case 0:   // Branch on the value of the EQ bit of CR6.
13076         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13077         break;
13078       case 1:   // Branch on the inverted value of the EQ bit of CR6.
13079         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13080         break;
13081       case 2:   // Branch on the value of the LT bit of CR6.
13082         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13083         break;
13084       case 3:   // Branch on the inverted value of the LT bit of CR6.
13085         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13086         break;
13087       }
13088 
13089       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13090                          DAG.getConstant(CompOpc, dl, MVT::i32),
13091                          DAG.getRegister(PPC::CR6, MVT::i32),
13092                          N->getOperand(4), CompNode.getValue(1));
13093     }
13094     break;
13095   }
13096   case ISD::BUILD_VECTOR:
13097     return DAGCombineBuildVector(N, DCI);
13098   }
13099 
13100   return SDValue();
13101 }
13102 
13103 SDValue
13104 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13105                                   SelectionDAG &DAG,
13106                                   std::vector<SDNode *> *Created) const {
13107   // fold (sdiv X, pow2)
13108   EVT VT = N->getValueType(0);
13109   if (VT == MVT::i64 && !Subtarget.isPPC64())
13110     return SDValue();
13111   if ((VT != MVT::i32 && VT != MVT::i64) ||
13112       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13113     return SDValue();
13114 
13115   SDLoc DL(N);
13116   SDValue N0 = N->getOperand(0);
13117 
13118   bool IsNegPow2 = (-Divisor).isPowerOf2();
13119   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13120   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13121 
13122   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13123   if (Created)
13124     Created->push_back(Op.getNode());
13125 
13126   if (IsNegPow2) {
13127     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13128     if (Created)
13129       Created->push_back(Op.getNode());
13130   }
13131 
13132   return Op;
13133 }
13134 
13135 //===----------------------------------------------------------------------===//
13136 // Inline Assembly Support
13137 //===----------------------------------------------------------------------===//
13138 
13139 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13140                                                       KnownBits &Known,
13141                                                       const APInt &DemandedElts,
13142                                                       const SelectionDAG &DAG,
13143                                                       unsigned Depth) const {
13144   Known.resetAll();
13145   switch (Op.getOpcode()) {
13146   default: break;
13147   case PPCISD::LBRX: {
13148     // lhbrx is known to have the top bits cleared out.
13149     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13150       Known.Zero = 0xFFFF0000;
13151     break;
13152   }
13153   case ISD::INTRINSIC_WO_CHAIN: {
13154     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13155     default: break;
13156     case Intrinsic::ppc_altivec_vcmpbfp_p:
13157     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13158     case Intrinsic::ppc_altivec_vcmpequb_p:
13159     case Intrinsic::ppc_altivec_vcmpequh_p:
13160     case Intrinsic::ppc_altivec_vcmpequw_p:
13161     case Intrinsic::ppc_altivec_vcmpequd_p:
13162     case Intrinsic::ppc_altivec_vcmpgefp_p:
13163     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13164     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13165     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13166     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13167     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13168     case Intrinsic::ppc_altivec_vcmpgtub_p:
13169     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13170     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13171     case Intrinsic::ppc_altivec_vcmpgtud_p:
13172       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13173       break;
13174     }
13175   }
13176   }
13177 }
13178 
13179 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13180   switch (Subtarget.getDarwinDirective()) {
13181   default: break;
13182   case PPC::DIR_970:
13183   case PPC::DIR_PWR4:
13184   case PPC::DIR_PWR5:
13185   case PPC::DIR_PWR5X:
13186   case PPC::DIR_PWR6:
13187   case PPC::DIR_PWR6X:
13188   case PPC::DIR_PWR7:
13189   case PPC::DIR_PWR8:
13190   case PPC::DIR_PWR9: {
13191     if (!ML)
13192       break;
13193 
13194     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13195 
13196     // For small loops (between 5 and 8 instructions), align to a 32-byte
13197     // boundary so that the entire loop fits in one instruction-cache line.
13198     uint64_t LoopSize = 0;
13199     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13200       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13201         LoopSize += TII->getInstSizeInBytes(*J);
13202         if (LoopSize > 32)
13203           break;
13204       }
13205 
13206     if (LoopSize > 16 && LoopSize <= 32)
13207       return 5;
13208 
13209     break;
13210   }
13211   }
13212 
13213   return TargetLowering::getPrefLoopAlignment(ML);
13214 }
13215 
13216 /// getConstraintType - Given a constraint, return the type of
13217 /// constraint it is for this target.
13218 PPCTargetLowering::ConstraintType
13219 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13220   if (Constraint.size() == 1) {
13221     switch (Constraint[0]) {
13222     default: break;
13223     case 'b':
13224     case 'r':
13225     case 'f':
13226     case 'd':
13227     case 'v':
13228     case 'y':
13229       return C_RegisterClass;
13230     case 'Z':
13231       // FIXME: While Z does indicate a memory constraint, it specifically
13232       // indicates an r+r address (used in conjunction with the 'y' modifier
13233       // in the replacement string). Currently, we're forcing the base
13234       // register to be r0 in the asm printer (which is interpreted as zero)
13235       // and forming the complete address in the second register. This is
13236       // suboptimal.
13237       return C_Memory;
13238     }
13239   } else if (Constraint == "wc") { // individual CR bits.
13240     return C_RegisterClass;
13241   } else if (Constraint == "wa" || Constraint == "wd" ||
13242              Constraint == "wf" || Constraint == "ws") {
13243     return C_RegisterClass; // VSX registers.
13244   }
13245   return TargetLowering::getConstraintType(Constraint);
13246 }
13247 
13248 /// Examine constraint type and operand type and determine a weight value.
13249 /// This object must already have been set up with the operand type
13250 /// and the current alternative constraint selected.
13251 TargetLowering::ConstraintWeight
13252 PPCTargetLowering::getSingleConstraintMatchWeight(
13253     AsmOperandInfo &info, const char *constraint) const {
13254   ConstraintWeight weight = CW_Invalid;
13255   Value *CallOperandVal = info.CallOperandVal;
13256     // If we don't have a value, we can't do a match,
13257     // but allow it at the lowest weight.
13258   if (!CallOperandVal)
13259     return CW_Default;
13260   Type *type = CallOperandVal->getType();
13261 
13262   // Look at the constraint type.
13263   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13264     return CW_Register; // an individual CR bit.
13265   else if ((StringRef(constraint) == "wa" ||
13266             StringRef(constraint) == "wd" ||
13267             StringRef(constraint) == "wf") &&
13268            type->isVectorTy())
13269     return CW_Register;
13270   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13271     return CW_Register;
13272 
13273   switch (*constraint) {
13274   default:
13275     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13276     break;
13277   case 'b':
13278     if (type->isIntegerTy())
13279       weight = CW_Register;
13280     break;
13281   case 'f':
13282     if (type->isFloatTy())
13283       weight = CW_Register;
13284     break;
13285   case 'd':
13286     if (type->isDoubleTy())
13287       weight = CW_Register;
13288     break;
13289   case 'v':
13290     if (type->isVectorTy())
13291       weight = CW_Register;
13292     break;
13293   case 'y':
13294     weight = CW_Register;
13295     break;
13296   case 'Z':
13297     weight = CW_Memory;
13298     break;
13299   }
13300   return weight;
13301 }
13302 
13303 std::pair<unsigned, const TargetRegisterClass *>
13304 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13305                                                 StringRef Constraint,
13306                                                 MVT VT) const {
13307   if (Constraint.size() == 1) {
13308     // GCC RS6000 Constraint Letters
13309     switch (Constraint[0]) {
13310     case 'b':   // R1-R31
13311       if (VT == MVT::i64 && Subtarget.isPPC64())
13312         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13313       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13314     case 'r':   // R0-R31
13315       if (VT == MVT::i64 && Subtarget.isPPC64())
13316         return std::make_pair(0U, &PPC::G8RCRegClass);
13317       return std::make_pair(0U, &PPC::GPRCRegClass);
13318     // 'd' and 'f' constraints are both defined to be "the floating point
13319     // registers", where one is for 32-bit and the other for 64-bit. We don't
13320     // really care overly much here so just give them all the same reg classes.
13321     case 'd':
13322     case 'f':
13323       if (Subtarget.hasSPE()) {
13324         if (VT == MVT::f32 || VT == MVT::i32)
13325           return std::make_pair(0U, &PPC::SPE4RCRegClass);
13326         if (VT == MVT::f64 || VT == MVT::i64)
13327           return std::make_pair(0U, &PPC::SPERCRegClass);
13328       } else {
13329         if (VT == MVT::f32 || VT == MVT::i32)
13330           return std::make_pair(0U, &PPC::F4RCRegClass);
13331         if (VT == MVT::f64 || VT == MVT::i64)
13332           return std::make_pair(0U, &PPC::F8RCRegClass);
13333         if (VT == MVT::v4f64 && Subtarget.hasQPX())
13334           return std::make_pair(0U, &PPC::QFRCRegClass);
13335         if (VT == MVT::v4f32 && Subtarget.hasQPX())
13336           return std::make_pair(0U, &PPC::QSRCRegClass);
13337       }
13338       break;
13339     case 'v':
13340       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13341         return std::make_pair(0U, &PPC::QFRCRegClass);
13342       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13343         return std::make_pair(0U, &PPC::QSRCRegClass);
13344       if (Subtarget.hasAltivec())
13345         return std::make_pair(0U, &PPC::VRRCRegClass);
13346       break;
13347     case 'y':   // crrc
13348       return std::make_pair(0U, &PPC::CRRCRegClass);
13349     }
13350   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13351     // An individual CR bit.
13352     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13353   } else if ((Constraint == "wa" || Constraint == "wd" ||
13354              Constraint == "wf") && Subtarget.hasVSX()) {
13355     return std::make_pair(0U, &PPC::VSRCRegClass);
13356   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13357     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13358       return std::make_pair(0U, &PPC::VSSRCRegClass);
13359     else
13360       return std::make_pair(0U, &PPC::VSFRCRegClass);
13361   }
13362 
13363   std::pair<unsigned, const TargetRegisterClass *> R =
13364       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13365 
13366   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13367   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13368   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13369   // register.
13370   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13371   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13372   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13373       PPC::GPRCRegClass.contains(R.first))
13374     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13375                             PPC::sub_32, &PPC::G8RCRegClass),
13376                           &PPC::G8RCRegClass);
13377 
13378   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13379   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13380     R.first = PPC::CR0;
13381     R.second = &PPC::CRRCRegClass;
13382   }
13383 
13384   return R;
13385 }
13386 
13387 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13388 /// vector.  If it is invalid, don't add anything to Ops.
13389 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13390                                                      std::string &Constraint,
13391                                                      std::vector<SDValue>&Ops,
13392                                                      SelectionDAG &DAG) const {
13393   SDValue Result;
13394 
13395   // Only support length 1 constraints.
13396   if (Constraint.length() > 1) return;
13397 
13398   char Letter = Constraint[0];
13399   switch (Letter) {
13400   default: break;
13401   case 'I':
13402   case 'J':
13403   case 'K':
13404   case 'L':
13405   case 'M':
13406   case 'N':
13407   case 'O':
13408   case 'P': {
13409     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13410     if (!CST) return; // Must be an immediate to match.
13411     SDLoc dl(Op);
13412     int64_t Value = CST->getSExtValue();
13413     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13414                          // numbers are printed as such.
13415     switch (Letter) {
13416     default: llvm_unreachable("Unknown constraint letter!");
13417     case 'I':  // "I" is a signed 16-bit constant.
13418       if (isInt<16>(Value))
13419         Result = DAG.getTargetConstant(Value, dl, TCVT);
13420       break;
13421     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13422       if (isShiftedUInt<16, 16>(Value))
13423         Result = DAG.getTargetConstant(Value, dl, TCVT);
13424       break;
13425     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13426       if (isShiftedInt<16, 16>(Value))
13427         Result = DAG.getTargetConstant(Value, dl, TCVT);
13428       break;
13429     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13430       if (isUInt<16>(Value))
13431         Result = DAG.getTargetConstant(Value, dl, TCVT);
13432       break;
13433     case 'M':  // "M" is a constant that is greater than 31.
13434       if (Value > 31)
13435         Result = DAG.getTargetConstant(Value, dl, TCVT);
13436       break;
13437     case 'N':  // "N" is a positive constant that is an exact power of two.
13438       if (Value > 0 && isPowerOf2_64(Value))
13439         Result = DAG.getTargetConstant(Value, dl, TCVT);
13440       break;
13441     case 'O':  // "O" is the constant zero.
13442       if (Value == 0)
13443         Result = DAG.getTargetConstant(Value, dl, TCVT);
13444       break;
13445     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13446       if (isInt<16>(-Value))
13447         Result = DAG.getTargetConstant(Value, dl, TCVT);
13448       break;
13449     }
13450     break;
13451   }
13452   }
13453 
13454   if (Result.getNode()) {
13455     Ops.push_back(Result);
13456     return;
13457   }
13458 
13459   // Handle standard constraint letters.
13460   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13461 }
13462 
13463 // isLegalAddressingMode - Return true if the addressing mode represented
13464 // by AM is legal for this target, for a load/store of the specified type.
13465 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13466                                               const AddrMode &AM, Type *Ty,
13467                                               unsigned AS, Instruction *I) const {
13468   // PPC does not allow r+i addressing modes for vectors!
13469   if (Ty->isVectorTy() && AM.BaseOffs != 0)
13470     return false;
13471 
13472   // PPC allows a sign-extended 16-bit immediate field.
13473   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13474     return false;
13475 
13476   // No global is ever allowed as a base.
13477   if (AM.BaseGV)
13478     return false;
13479 
13480   // PPC only support r+r,
13481   switch (AM.Scale) {
13482   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13483     break;
13484   case 1:
13485     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13486       return false;
13487     // Otherwise we have r+r or r+i.
13488     break;
13489   case 2:
13490     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13491       return false;
13492     // Allow 2*r as r+r.
13493     break;
13494   default:
13495     // No other scales are supported.
13496     return false;
13497   }
13498 
13499   return true;
13500 }
13501 
13502 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13503                                            SelectionDAG &DAG) const {
13504   MachineFunction &MF = DAG.getMachineFunction();
13505   MachineFrameInfo &MFI = MF.getFrameInfo();
13506   MFI.setReturnAddressIsTaken(true);
13507 
13508   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13509     return SDValue();
13510 
13511   SDLoc dl(Op);
13512   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13513 
13514   // Make sure the function does not optimize away the store of the RA to
13515   // the stack.
13516   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13517   FuncInfo->setLRStoreRequired();
13518   bool isPPC64 = Subtarget.isPPC64();
13519   auto PtrVT = getPointerTy(MF.getDataLayout());
13520 
13521   if (Depth > 0) {
13522     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13523     SDValue Offset =
13524         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13525                         isPPC64 ? MVT::i64 : MVT::i32);
13526     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13527                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13528                        MachinePointerInfo());
13529   }
13530 
13531   // Just load the return address off the stack.
13532   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13533   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13534                      MachinePointerInfo());
13535 }
13536 
13537 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13538                                           SelectionDAG &DAG) const {
13539   SDLoc dl(Op);
13540   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13541 
13542   MachineFunction &MF = DAG.getMachineFunction();
13543   MachineFrameInfo &MFI = MF.getFrameInfo();
13544   MFI.setFrameAddressIsTaken(true);
13545 
13546   EVT PtrVT = getPointerTy(MF.getDataLayout());
13547   bool isPPC64 = PtrVT == MVT::i64;
13548 
13549   // Naked functions never have a frame pointer, and so we use r1. For all
13550   // other functions, this decision must be delayed until during PEI.
13551   unsigned FrameReg;
13552   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
13553     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13554   else
13555     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13556 
13557   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13558                                          PtrVT);
13559   while (Depth--)
13560     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13561                             FrameAddr, MachinePointerInfo());
13562   return FrameAddr;
13563 }
13564 
13565 // FIXME? Maybe this could be a TableGen attribute on some registers and
13566 // this table could be generated automatically from RegInfo.
13567 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13568                                               SelectionDAG &DAG) const {
13569   bool isPPC64 = Subtarget.isPPC64();
13570   bool isDarwinABI = Subtarget.isDarwinABI();
13571 
13572   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13573       (!isPPC64 && VT != MVT::i32))
13574     report_fatal_error("Invalid register global variable type");
13575 
13576   bool is64Bit = isPPC64 && VT == MVT::i64;
13577   unsigned Reg = StringSwitch<unsigned>(RegName)
13578                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13579                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13580                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13581                                   (is64Bit ? PPC::X13 : PPC::R13))
13582                    .Default(0);
13583 
13584   if (Reg)
13585     return Reg;
13586   report_fatal_error("Invalid register name global variable");
13587 }
13588 
13589 bool
13590 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13591   // The PowerPC target isn't yet aware of offsets.
13592   return false;
13593 }
13594 
13595 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13596                                            const CallInst &I,
13597                                            MachineFunction &MF,
13598                                            unsigned Intrinsic) const {
13599   switch (Intrinsic) {
13600   case Intrinsic::ppc_qpx_qvlfd:
13601   case Intrinsic::ppc_qpx_qvlfs:
13602   case Intrinsic::ppc_qpx_qvlfcd:
13603   case Intrinsic::ppc_qpx_qvlfcs:
13604   case Intrinsic::ppc_qpx_qvlfiwa:
13605   case Intrinsic::ppc_qpx_qvlfiwz:
13606   case Intrinsic::ppc_altivec_lvx:
13607   case Intrinsic::ppc_altivec_lvxl:
13608   case Intrinsic::ppc_altivec_lvebx:
13609   case Intrinsic::ppc_altivec_lvehx:
13610   case Intrinsic::ppc_altivec_lvewx:
13611   case Intrinsic::ppc_vsx_lxvd2x:
13612   case Intrinsic::ppc_vsx_lxvw4x: {
13613     EVT VT;
13614     switch (Intrinsic) {
13615     case Intrinsic::ppc_altivec_lvebx:
13616       VT = MVT::i8;
13617       break;
13618     case Intrinsic::ppc_altivec_lvehx:
13619       VT = MVT::i16;
13620       break;
13621     case Intrinsic::ppc_altivec_lvewx:
13622       VT = MVT::i32;
13623       break;
13624     case Intrinsic::ppc_vsx_lxvd2x:
13625       VT = MVT::v2f64;
13626       break;
13627     case Intrinsic::ppc_qpx_qvlfd:
13628       VT = MVT::v4f64;
13629       break;
13630     case Intrinsic::ppc_qpx_qvlfs:
13631       VT = MVT::v4f32;
13632       break;
13633     case Intrinsic::ppc_qpx_qvlfcd:
13634       VT = MVT::v2f64;
13635       break;
13636     case Intrinsic::ppc_qpx_qvlfcs:
13637       VT = MVT::v2f32;
13638       break;
13639     default:
13640       VT = MVT::v4i32;
13641       break;
13642     }
13643 
13644     Info.opc = ISD::INTRINSIC_W_CHAIN;
13645     Info.memVT = VT;
13646     Info.ptrVal = I.getArgOperand(0);
13647     Info.offset = -VT.getStoreSize()+1;
13648     Info.size = 2*VT.getStoreSize()-1;
13649     Info.align = 1;
13650     Info.flags = MachineMemOperand::MOLoad;
13651     return true;
13652   }
13653   case Intrinsic::ppc_qpx_qvlfda:
13654   case Intrinsic::ppc_qpx_qvlfsa:
13655   case Intrinsic::ppc_qpx_qvlfcda:
13656   case Intrinsic::ppc_qpx_qvlfcsa:
13657   case Intrinsic::ppc_qpx_qvlfiwaa:
13658   case Intrinsic::ppc_qpx_qvlfiwza: {
13659     EVT VT;
13660     switch (Intrinsic) {
13661     case Intrinsic::ppc_qpx_qvlfda:
13662       VT = MVT::v4f64;
13663       break;
13664     case Intrinsic::ppc_qpx_qvlfsa:
13665       VT = MVT::v4f32;
13666       break;
13667     case Intrinsic::ppc_qpx_qvlfcda:
13668       VT = MVT::v2f64;
13669       break;
13670     case Intrinsic::ppc_qpx_qvlfcsa:
13671       VT = MVT::v2f32;
13672       break;
13673     default:
13674       VT = MVT::v4i32;
13675       break;
13676     }
13677 
13678     Info.opc = ISD::INTRINSIC_W_CHAIN;
13679     Info.memVT = VT;
13680     Info.ptrVal = I.getArgOperand(0);
13681     Info.offset = 0;
13682     Info.size = VT.getStoreSize();
13683     Info.align = 1;
13684     Info.flags = MachineMemOperand::MOLoad;
13685     return true;
13686   }
13687   case Intrinsic::ppc_qpx_qvstfd:
13688   case Intrinsic::ppc_qpx_qvstfs:
13689   case Intrinsic::ppc_qpx_qvstfcd:
13690   case Intrinsic::ppc_qpx_qvstfcs:
13691   case Intrinsic::ppc_qpx_qvstfiw:
13692   case Intrinsic::ppc_altivec_stvx:
13693   case Intrinsic::ppc_altivec_stvxl:
13694   case Intrinsic::ppc_altivec_stvebx:
13695   case Intrinsic::ppc_altivec_stvehx:
13696   case Intrinsic::ppc_altivec_stvewx:
13697   case Intrinsic::ppc_vsx_stxvd2x:
13698   case Intrinsic::ppc_vsx_stxvw4x: {
13699     EVT VT;
13700     switch (Intrinsic) {
13701     case Intrinsic::ppc_altivec_stvebx:
13702       VT = MVT::i8;
13703       break;
13704     case Intrinsic::ppc_altivec_stvehx:
13705       VT = MVT::i16;
13706       break;
13707     case Intrinsic::ppc_altivec_stvewx:
13708       VT = MVT::i32;
13709       break;
13710     case Intrinsic::ppc_vsx_stxvd2x:
13711       VT = MVT::v2f64;
13712       break;
13713     case Intrinsic::ppc_qpx_qvstfd:
13714       VT = MVT::v4f64;
13715       break;
13716     case Intrinsic::ppc_qpx_qvstfs:
13717       VT = MVT::v4f32;
13718       break;
13719     case Intrinsic::ppc_qpx_qvstfcd:
13720       VT = MVT::v2f64;
13721       break;
13722     case Intrinsic::ppc_qpx_qvstfcs:
13723       VT = MVT::v2f32;
13724       break;
13725     default:
13726       VT = MVT::v4i32;
13727       break;
13728     }
13729 
13730     Info.opc = ISD::INTRINSIC_VOID;
13731     Info.memVT = VT;
13732     Info.ptrVal = I.getArgOperand(1);
13733     Info.offset = -VT.getStoreSize()+1;
13734     Info.size = 2*VT.getStoreSize()-1;
13735     Info.align = 1;
13736     Info.flags = MachineMemOperand::MOStore;
13737     return true;
13738   }
13739   case Intrinsic::ppc_qpx_qvstfda:
13740   case Intrinsic::ppc_qpx_qvstfsa:
13741   case Intrinsic::ppc_qpx_qvstfcda:
13742   case Intrinsic::ppc_qpx_qvstfcsa:
13743   case Intrinsic::ppc_qpx_qvstfiwa: {
13744     EVT VT;
13745     switch (Intrinsic) {
13746     case Intrinsic::ppc_qpx_qvstfda:
13747       VT = MVT::v4f64;
13748       break;
13749     case Intrinsic::ppc_qpx_qvstfsa:
13750       VT = MVT::v4f32;
13751       break;
13752     case Intrinsic::ppc_qpx_qvstfcda:
13753       VT = MVT::v2f64;
13754       break;
13755     case Intrinsic::ppc_qpx_qvstfcsa:
13756       VT = MVT::v2f32;
13757       break;
13758     default:
13759       VT = MVT::v4i32;
13760       break;
13761     }
13762 
13763     Info.opc = ISD::INTRINSIC_VOID;
13764     Info.memVT = VT;
13765     Info.ptrVal = I.getArgOperand(1);
13766     Info.offset = 0;
13767     Info.size = VT.getStoreSize();
13768     Info.align = 1;
13769     Info.flags = MachineMemOperand::MOStore;
13770     return true;
13771   }
13772   default:
13773     break;
13774   }
13775 
13776   return false;
13777 }
13778 
13779 /// getOptimalMemOpType - Returns the target specific optimal type for load
13780 /// and store operations as a result of memset, memcpy, and memmove
13781 /// lowering. If DstAlign is zero that means it's safe to destination
13782 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13783 /// means there isn't a need to check it against alignment requirement,
13784 /// probably because the source does not need to be loaded. If 'IsMemset' is
13785 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13786 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13787 /// source is constant so it does not need to be loaded.
13788 /// It returns EVT::Other if the type should be determined using generic
13789 /// target-independent logic.
13790 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13791                                            unsigned DstAlign, unsigned SrcAlign,
13792                                            bool IsMemset, bool ZeroMemset,
13793                                            bool MemcpyStrSrc,
13794                                            MachineFunction &MF) const {
13795   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13796     const Function &F = MF.getFunction();
13797     // When expanding a memset, require at least two QPX instructions to cover
13798     // the cost of loading the value to be stored from the constant pool.
13799     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13800        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13801         !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
13802       return MVT::v4f64;
13803     }
13804 
13805     // We should use Altivec/VSX loads and stores when available. For unaligned
13806     // addresses, unaligned VSX loads are only fast starting with the P8.
13807     if (Subtarget.hasAltivec() && Size >= 16 &&
13808         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13809          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13810       return MVT::v4i32;
13811   }
13812 
13813   if (Subtarget.isPPC64()) {
13814     return MVT::i64;
13815   }
13816 
13817   return MVT::i32;
13818 }
13819 
13820 /// Returns true if it is beneficial to convert a load of a constant
13821 /// to just the constant itself.
13822 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13823                                                           Type *Ty) const {
13824   assert(Ty->isIntegerTy());
13825 
13826   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13827   return !(BitSize == 0 || BitSize > 64);
13828 }
13829 
13830 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13831   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13832     return false;
13833   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13834   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13835   return NumBits1 == 64 && NumBits2 == 32;
13836 }
13837 
13838 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13839   if (!VT1.isInteger() || !VT2.isInteger())
13840     return false;
13841   unsigned NumBits1 = VT1.getSizeInBits();
13842   unsigned NumBits2 = VT2.getSizeInBits();
13843   return NumBits1 == 64 && NumBits2 == 32;
13844 }
13845 
13846 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13847   // Generally speaking, zexts are not free, but they are free when they can be
13848   // folded with other operations.
13849   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13850     EVT MemVT = LD->getMemoryVT();
13851     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13852          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13853         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13854          LD->getExtensionType() == ISD::ZEXTLOAD))
13855       return true;
13856   }
13857 
13858   // FIXME: Add other cases...
13859   //  - 32-bit shifts with a zext to i64
13860   //  - zext after ctlz, bswap, etc.
13861   //  - zext after and by a constant mask
13862 
13863   return TargetLowering::isZExtFree(Val, VT2);
13864 }
13865 
13866 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13867   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13868          "invalid fpext types");
13869   // Extending to float128 is not free.
13870   if (DestVT == MVT::f128)
13871     return false;
13872   return true;
13873 }
13874 
13875 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13876   return isInt<16>(Imm) || isUInt<16>(Imm);
13877 }
13878 
13879 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13880   return isInt<16>(Imm) || isUInt<16>(Imm);
13881 }
13882 
13883 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13884                                                        unsigned,
13885                                                        unsigned,
13886                                                        bool *Fast) const {
13887   if (DisablePPCUnaligned)
13888     return false;
13889 
13890   // PowerPC supports unaligned memory access for simple non-vector types.
13891   // Although accessing unaligned addresses is not as efficient as accessing
13892   // aligned addresses, it is generally more efficient than manual expansion,
13893   // and generally only traps for software emulation when crossing page
13894   // boundaries.
13895 
13896   if (!VT.isSimple())
13897     return false;
13898 
13899   if (VT.getSimpleVT().isVector()) {
13900     if (Subtarget.hasVSX()) {
13901       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13902           VT != MVT::v4f32 && VT != MVT::v4i32)
13903         return false;
13904     } else {
13905       return false;
13906     }
13907   }
13908 
13909   if (VT == MVT::ppcf128)
13910     return false;
13911 
13912   if (Fast)
13913     *Fast = true;
13914 
13915   return true;
13916 }
13917 
13918 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13919   VT = VT.getScalarType();
13920 
13921   if (!VT.isSimple())
13922     return false;
13923 
13924   switch (VT.getSimpleVT().SimpleTy) {
13925   case MVT::f32:
13926   case MVT::f64:
13927     return true;
13928   case MVT::f128:
13929     return (EnableQuadPrecision && Subtarget.hasP9Vector());
13930   default:
13931     break;
13932   }
13933 
13934   return false;
13935 }
13936 
13937 const MCPhysReg *
13938 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13939   // LR is a callee-save register, but we must treat it as clobbered by any call
13940   // site. Hence we include LR in the scratch registers, which are in turn added
13941   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13942   // to CTR, which is used by any indirect call.
13943   static const MCPhysReg ScratchRegs[] = {
13944     PPC::X12, PPC::LR8, PPC::CTR8, 0
13945   };
13946 
13947   return ScratchRegs;
13948 }
13949 
13950 unsigned PPCTargetLowering::getExceptionPointerRegister(
13951     const Constant *PersonalityFn) const {
13952   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
13953 }
13954 
13955 unsigned PPCTargetLowering::getExceptionSelectorRegister(
13956     const Constant *PersonalityFn) const {
13957   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
13958 }
13959 
13960 bool
13961 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
13962                      EVT VT , unsigned DefinedValues) const {
13963   if (VT == MVT::v2i64)
13964     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
13965 
13966   if (Subtarget.hasVSX() || Subtarget.hasQPX())
13967     return true;
13968 
13969   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
13970 }
13971 
13972 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
13973   if (DisableILPPref || Subtarget.enableMachineScheduler())
13974     return TargetLowering::getSchedulingPreference(N);
13975 
13976   return Sched::ILP;
13977 }
13978 
13979 // Create a fast isel object.
13980 FastISel *
13981 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13982                                   const TargetLibraryInfo *LibInfo) const {
13983   return PPC::createFastISel(FuncInfo, LibInfo);
13984 }
13985 
13986 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13987   if (Subtarget.isDarwinABI()) return;
13988   if (!Subtarget.isPPC64()) return;
13989 
13990   // Update IsSplitCSR in PPCFunctionInfo
13991   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13992   PFI->setIsSplitCSR(true);
13993 }
13994 
13995 void PPCTargetLowering::insertCopiesSplitCSR(
13996   MachineBasicBlock *Entry,
13997   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13998   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13999   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14000   if (!IStart)
14001     return;
14002 
14003   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14004   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14005   MachineBasicBlock::iterator MBBI = Entry->begin();
14006   for (const MCPhysReg *I = IStart; *I; ++I) {
14007     const TargetRegisterClass *RC = nullptr;
14008     if (PPC::G8RCRegClass.contains(*I))
14009       RC = &PPC::G8RCRegClass;
14010     else if (PPC::F8RCRegClass.contains(*I))
14011       RC = &PPC::F8RCRegClass;
14012     else if (PPC::CRRCRegClass.contains(*I))
14013       RC = &PPC::CRRCRegClass;
14014     else if (PPC::VRRCRegClass.contains(*I))
14015       RC = &PPC::VRRCRegClass;
14016     else
14017       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14018 
14019     unsigned NewVR = MRI->createVirtualRegister(RC);
14020     // Create copy from CSR to a virtual register.
14021     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14022     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14023     // nounwind. If we want to generalize this later, we may need to emit
14024     // CFI pseudo-instructions.
14025     assert(Entry->getParent()->getFunction().hasFnAttribute(
14026              Attribute::NoUnwind) &&
14027            "Function should be nounwind in insertCopiesSplitCSR!");
14028     Entry->addLiveIn(*I);
14029     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14030       .addReg(*I);
14031 
14032     // Insert the copy-back instructions right before the terminator
14033     for (auto *Exit : Exits)
14034       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14035               TII->get(TargetOpcode::COPY), *I)
14036         .addReg(NewVR);
14037   }
14038 }
14039 
14040 // Override to enable LOAD_STACK_GUARD lowering on Linux.
14041 bool PPCTargetLowering::useLoadStackGuardNode() const {
14042   if (!Subtarget.isTargetLinux())
14043     return TargetLowering::useLoadStackGuardNode();
14044   return true;
14045 }
14046 
14047 // Override to disable global variable loading on Linux.
14048 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14049   if (!Subtarget.isTargetLinux())
14050     return TargetLowering::insertSSPDeclarations(M);
14051 }
14052 
14053 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14054   if (!VT.isSimple() || !Subtarget.hasVSX())
14055     return false;
14056 
14057   switch(VT.getSimpleVT().SimpleTy) {
14058   default:
14059     // For FP types that are currently not supported by PPC backend, return
14060     // false. Examples: f16, f80.
14061     return false;
14062   case MVT::f32:
14063   case MVT::f64:
14064   case MVT::ppcf128:
14065     return Imm.isPosZero();
14066   }
14067 }
14068 
14069 // For vector shift operation op, fold
14070 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14071 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14072                                   SelectionDAG &DAG) {
14073   SDValue N0 = N->getOperand(0);
14074   SDValue N1 = N->getOperand(1);
14075   EVT VT = N0.getValueType();
14076   unsigned OpSizeInBits = VT.getScalarSizeInBits();
14077   unsigned Opcode = N->getOpcode();
14078   unsigned TargetOpcode;
14079 
14080   switch (Opcode) {
14081   default:
14082     llvm_unreachable("Unexpected shift operation");
14083   case ISD::SHL:
14084     TargetOpcode = PPCISD::SHL;
14085     break;
14086   case ISD::SRL:
14087     TargetOpcode = PPCISD::SRL;
14088     break;
14089   case ISD::SRA:
14090     TargetOpcode = PPCISD::SRA;
14091     break;
14092   }
14093 
14094   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14095       N1->getOpcode() == ISD::AND)
14096     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14097       if (Mask->getZExtValue() == OpSizeInBits - 1)
14098         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14099 
14100   return SDValue();
14101 }
14102 
14103 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14104   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14105     return Value;
14106 
14107   return SDValue();
14108 }
14109 
14110 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14111   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14112     return Value;
14113 
14114   return SDValue();
14115 }
14116 
14117 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14118   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14119     return Value;
14120 
14121   return SDValue();
14122 }
14123 
14124 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14125   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
14126   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
14127     return false;
14128 
14129   // If not a tail call then no need to proceed.
14130   if (!CI->isTailCall())
14131     return false;
14132 
14133   // If tail calls are disabled for the caller then we are done.
14134   const Function *Caller = CI->getParent()->getParent();
14135   auto Attr = Caller->getFnAttribute("disable-tail-calls");
14136   if (Attr.getValueAsString() == "true")
14137     return false;
14138 
14139   // If sibling calls have been disabled and tail-calls aren't guaranteed
14140   // there is no reason to duplicate.
14141   auto &TM = getTargetMachine();
14142   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
14143     return false;
14144 
14145   // Can't tail call a function called indirectly, or if it has variadic args.
14146   const Function *Callee = CI->getCalledFunction();
14147   if (!Callee || Callee->isVarArg())
14148     return false;
14149 
14150   // Make sure the callee and caller calling conventions are eligible for tco.
14151   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
14152                                            CI->getCallingConv()))
14153       return false;
14154 
14155   // If the function is local then we have a good chance at tail-calling it
14156   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
14157 }
14158 
14159 bool PPCTargetLowering::
14160 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
14161   const Value *Mask = AndI.getOperand(1);
14162   // If the mask is suitable for andi. or andis. we should sink the and.
14163   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
14164     // Can't handle constants wider than 64-bits.
14165     if (CI->getBitWidth() > 64)
14166       return false;
14167     int64_t ConstVal = CI->getZExtValue();
14168     return isUInt<16>(ConstVal) ||
14169       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
14170   }
14171 
14172   // For non-constant masks, we can always use the record-form and.
14173   return true;
14174 }
14175